Optional joystick controls

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
FreeTom
Prole
Posts: 8
Joined: Mon Aug 17, 2015 1:08 pm

Optional joystick controls

Post 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?
User avatar
Xii
Party member
Posts: 137
Joined: Thu Aug 13, 2020 9:09 pm
Contact:

Re: Optional joystick controls

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

Re: Optional joystick controls

Post by FreeTom »

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

Thanks for your help.
User avatar
D0NM
Party member
Posts: 250
Joined: Mon Feb 08, 2016 10:35 am
Location: Zabuyaki
Contact:

Re: Optional joystick controls

Post 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')
}
Our LÖVE Gamedev blog Zabuyaki (an open source retro beat 'em up game). Twitter: @Zabuyaki.
:joker: LÖVE & Lua Video Lessons in Russian / Видео уроки по LÖVE и Lua :joker:
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 3 guests