Can someone clarify how this works to me?

I’ve been going through the tutorials and this portion confused me.

  1. For each input direction, set the X or the Y component of the input vector in self. If the user presses the up arrow and left arrow keys simultaneously, the engine will call this function twice and the input vector will end up being set to (-1, 1, 0).

and here is the relevant code snippet

function on_input(self, action_id, action)          -- [14]
	if action_id == hash("up") then
		self.input.y = 1                            -- [15]
	elseif action_id == hash("down") then
		self.input.y = -1
	elseif action_id == hash("left") then
		self.input.x = -1
	elseif action_id == hash("right") then
		self.input.x = 1
	end

	...
end

My question is regarding the elseif in particular, and I guess the caveat here is the fact that the engine calls the function twice.

So is the resulting logic that both calls from the player input are sent to on_input before update is ever called so both self.input.x and self.input.y have been set?

Thanks for the help!

1 Like

That is correct. In the update loop, all on_input calls are made before update calls.

2 Likes

Described in details here: :wink:

1 Like

on_input() is call once for each input from a device before update() is called, otherwise you would not be able to move diagonally. The order each device signal is processed by on_input() appears to be fixed. E.G hold down (A&D) and you always move left, so the signal from D is processed before A’s. I guess there will be a way to code this to remove this asymmetry.

In this tutorial example (the update code isn’t shown), the movement in all directions is stored in a vector that is used to transform the position in update. Left/right is stored in self.input.x and up/down in self.input.y. So it doesn’t matter which axis is captured first, as both values are stored in the self.input vector when update is called.

Edit: I misunderstood your comment. I think if you want A and D to cancel each other out if pressed simultaneously, you could set self.input to zero at the start of the frame and then add the +1 or -1 to the vector components. Then it would sum to zero if they pressed both keys (in the same frame).

1 Like

At the end of your update code you will reset input to zero otherwise you will have movement problems. I was talking about a detail of the movement mechanics which is no big deal really, so no worries that I did not explain it very well.