## Optional joystick controls

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
FreeTom
Prole
Posts: 6
Joined: Mon Aug 17, 2015 1:08 pm

### Optional joystick controls

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?
Xii
Citizen
Posts: 90
Joined: Thu Aug 13, 2020 9:09 pm
Contact:

### Re: Optional joystick controls

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.
FreeTom
Prole
Posts: 6
Joined: Mon Aug 17, 2015 1:08 pm

### Re: Optional joystick controls

Ah! Okay, maybe I should have thought of that.

D0NM
Party member
Posts: 247
Joined: Mon Feb 08, 2016 10:35 am
Contact:

### Re: Optional joystick controls

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()
Vertical = tactile.newControl()
}