Page 1 of 1

Optional joystick controls

Posted: Thu Apr 08, 2021 9:37 pm
by FreeTom
Hi all,

I want to have my game use a joystick if it's plugged in but not crash if it's not. So for instance I currently have things like:

Code: Select all

if joystick:isGamepadDown("dpleft") or love.keyboard.isDown("left") then
	-- move left
end
This means if my controller is plugged in I can use either joystick or keyboard controls. However, if it's not, then I get the error
attempt to index global 'joystick' (a nil value)
In searching for solutions I found there is/was a library called 'cock' that claimed to allow a dummy joystick but it didn't seem great.

Is there some way I can avoid the ugliness of having two if-then blocks for every input?

Re: Optional joystick controls

Posted: Thu Apr 08, 2021 9:59 pm
by Xii

Code: Select all

if (joystick and joystick:isGamepadDown("dpleft")) or love.keyboard.isDown("left") then
Most programming languages have short-circuiting comparison operators. In (A and B), A is evaluated first, and if it's false (or nil here), the expression immediately returns false because it can never be true, and thus B isn't evaluated at all.

Re: Optional joystick controls

Posted: Sun Apr 11, 2021 9:22 am
by FreeTom
Ah! Okay, maybe I should have thought of that.

Thanks for your help.

Re: Optional joystick controls

Posted: Mon Apr 19, 2021 6:45 am
by D0NM
There are many libraries that solve all the problems

Here is the lib & manual: https://github.com/tesselode/tactile
(its author has a more modern LIB called Baton https://github.com/tesselode/baton )

Code: Select all

Control = {
  Horizontal = tactile.newControl()
    :addAxis(tactile.gamepadAxis(1, 'leftx'))
    :addButtonPair(tactile.keys('a', 'left'), tactile.keys('d', 'right')),
  Vertical = tactile.newControl()
    :addAxis(tactile.gamepadAxis(1, 'lefty'))
    :addButtonPair(tactile.keys('w', 'up'), tactile.keys('s', 'down')),
  Fire = tactile.newControl()
    :addAxis(tactile.gamepadAxis(1, 'triggerleft'))
    :addAxis(tactile.gamepadAxis(1, 'triggerright'))
    :addButton(tactile.gamepadButtons(1, 'a'))
    :addButton(tactile.keys 'x')
}