I don't understand how on_input work (SOLVED)

Hello,
I have a code that allows you to move a sprite component of a game object along the x axis.
It looks like the code from the examples: Walking astronaut and War battles.
My code:

function init(self)
	msg.post(".", "acquire_input_focus")

	self.moving = false -- движется игрок или нет
	self.input = vmath.vector3() -- вектор ввода игрока
	self.dir = vmath.vector3() -- вектор направления игрока
	self.speed = 100 -- скорость перемещения игрока

	self.current_animation = nil -- текущая анимация игрока
end

function final(self)
	msg.post(".", "release_input_focus")
end

local function update_animation(self)
	if self.dir.x > 0 and self.current_animation ~= "right" then -- right
		sprite.play_flipbook("#sprite", "spaceship-red-right")
		self.current_animation = "right"
	elseif self.dir.x < 0 and self.current_animation ~= "left" then -- left
		sprite.play_flipbook("#sprite", "spaceship-red-left")
		self.current_animation = "left" 
	end
	print(self.current_animation)
end

function update(self, dt)
	if self.moving then
		local pos = go.get_position()
		pos = pos + self.dir * self.speed * dt
		go.set_position(pos)
		update_animation(self)
	else
		self.current_animation = "idle"
		sprite.play_flipbook("#sprite", "spaceship-red-idle")
	end

	self.input.x = 0
	self.input.y = 0
	self.moving = false
end

function on_input(self, action_id, action)
	if action_id == hash("right") then
		self.input.x = 1
		pprint(action)
	elseif action_id == hash("left") then
		self.input.x = -1
		pprint(action)
	end

	if vmath.length(self.input) > 0 then
		self.moving = true
		self.dir = vmath.normalize(self.input)
	end	
end

I move the character to the left while holding down this key. When I hold down the left key at the same time, the symbol moves to the right. If I do the same thing, but with the opposite keys, it will still move to the right. Although, in my opinion, the character should hesitate in one place or stand in one place.

I don’t understand why the sprite isn’t standing still.
When I do debugging, I see that repeated = false

I can’t figure out how on input works.

I would not set it to an absolute value, as it will result in left/right fighting over the final result.
Instead, I’d add/subtract to the value:

self.input.x = self.input.x + 1

and respectively

self.input.x = self.input.x - 1

That way, when both left and right are held, you’ll get self.input.x === 0 and you can handle that in your update function.

1 Like

Thanks, I also forgot to add the self.input.x > 0 check.

if self.moving and self.input.x ~= 0 then
		local pos = go.get_position()
		pos = pos + self.dir * self.speed * dt
		go.set_position(pos)
		update_animation(self)
else