Page 1 of 1

having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 12:38 am
by bkumanchik
I am trying to use the hat to move a sprite left and right and the A button to fire, I've spent all day trying to figure this out.

Here's my code, any help would be appreciated:


--move turret
function move_turret()
--don't move it if turret is exploding
if not turret_hit then
--if love.keyboard.isDown("left") then
if Joystick:getHat( "l" ) then
if tx >= lb + 2 then
tx = tx - 4
end
--elseif love.keyboard.isDown("right") then
elseif Joystick:getHat( "r" ) then
if tx <= rb - 8 then
tx = tx + 4
end
end
end
end


--fire turret
function fire_turret()
--if love.keyboard.isDown("space") then
if love.joystick.isDown( 0, "x" ) then
love.audio.play( pew_sound )
--pressed = true
t_fired = true
t_shot_x = tx
t_shot_y = ty
end
end

Re: having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 2:07 am
by BrotSagtMist
The syntax as per wiki is "direction = Joystick:getHat( number_of_hat )"
So i assume you have to write
Joystick:getHat(1)=="r"

Re: having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 4:04 am
by bkumanchik
Didn't work, I get:

---------------------
Error

main.lua:124: attempt to index global 'Joystick' (a nil value)


Traceback

main.lua:124: in function 'move_turret'
main.lua:62: in function 'update'
[C]: in function 'xpcall'
---------------------
I've tried everything :(

Re: having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 11:05 am
by GVovkiv
You mean something like that?

Code: Select all

function love.load()
    local joysticks = love.joystick.getJoysticks()
    joystick = joysticks[1]

    position = {x = 400, y = 300}
    speed = 300
end

function love.update(dt)
    if not joystick then return end

    if joystick:getHat(1) == "l" then
        position.x = position.x - speed * dt
    elseif joystick:getHat(1) == "r" then
        position.x = position.x + speed * dt
    end

    if joystick:getHat(1) == "u" then
        position.y = position.y - speed * dt
    elseif joystick:getHat(1) == "d" then
        position.y = position.y + speed * dt
    end
end

function love.draw()
    love.graphics.circle("fill", position.x, position.y, 50)
end

Re: having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 1:26 pm
by BrotSagtMist
Ohwell, the : syntax means that something of the type "Joystick" has this function, its not the actual name of anything.
You need of course create something of this type first.
Eg some may need player1:getHat()....

You actually should just work with callbacks instead
https://love2d.org/wiki/love.joystickhat
Eg:
function love.joystickhat( joystick, hat, direction )
D=direction
end
if D=="r" then etc...
is a more straight forward approach to what you want to archieve.

Re: having issues reading gamepad - hat and buttons

Posted: Tue Aug 24, 2021 5:13 pm
by bkumanchik
That worked, thanks!