How to get diagonal input on gamepad stick?

Hello. I have a simple question.

I’m creating 2D shmup, I want to provide 8-directional input on both digital pads and analog stick.
But I can’t find how to get diagonal input from analog stick.

I tried below input settings and took the gamepad input logs.

image

function on_input(self, action_id, action)
  state.on_input(action_id, action, TSys.state)
  if action_id == hash("s_up") then
    if action.pressed then
      print("s_up", action.value) -- a value between 0.0 an -1.0
    elseif action.released then
      print("s_up released")
    end
  elseif action_id == hash("s_down") then
    if action.pressed then
      print("s_down", action.value) -- a value between 0.0 an -1.0
    elseif action.released then
      print("s_down released")
    end
  elseif action_id == hash("s_left") then
    if action.pressed then
      print("s_left", action.value) -- a value between 0.0 an -1.0
    elseif action.released then
      print("s_left released")
    end
  elseif action_id == hash("s_right") then
    if action.pressed then
      print("s_right", action.value) -- a value between 0.0 an -1.0
    elseif action.released then
      print("s_right released")
    end
  end
  
end

But, It seems that previous direction input is released before next direction input is pressed, so it seems that I can’t detect diagonal input.

How can I get diagonal input from analog stick?
Thanks.

You can get multiple input events per frame. In the case of diagonal movement you get both a right and up for instance and combine these during a frame. Something like this:

function init(self)
  self.movement = vmath.vector3()
end


function update(self, dt)
  local pos = go.get_position()
  pos = pos + self.movement * 100 * dt
  go.set_position(pos)

  -- reset each frame
  self.movement.x = 0
  self.movement.y = 0
end

function on_input(self, action_id, action)
  if action_id == hash("s_up") then
    self.movement.y = 1
  elseif action_id == hash("s_down") then
    self.movement.y = -1
  elseif action_id == hash("s_left") then
    self.movement.x = -1
  elseif action_id == hash("s_right") then
    self.movement.x = 1
  end
end
3 Likes

Thank you!
Ignoring action.pressed and action.released, it goes well :slight_smile:

Yes, since the movement vector is reset every frame and you get controller input every frame it should be fine. If the on_input and update would at some point in the future be decoupled (not planned by the way) then it makes sense to keep tracking pressed and released though.

1 Like