I need help with a movement script

I have followed this tutorial on movement and I got this code. But whenever I press the move key it keeps the character moving and when I press the other one it starts to go the other way. How can I fix this?

function init(self)
    msg.post(".","acquire_input_focus")
    self.runSpeed = 50
    self.curAnim = "idle"
    msg.post("#sprite", "play_animation", { id=hash("idle") })
    self.speed = vmath.vector3()
end
function update(self, dt)
    local pos = go.get_position()
    if self.speed.x ~= 0 then    
        pos = pos + self.speed * dt
        go.set_position(pos)
        if self.curAnim ~= "run" then
            msg.post("#sprite", "play_animation", { id=hash("run") })
            self.curAnim = "run"
        end
    end
end
function on_input(self, action_id, action)
    if action_id == hash("MOVE_RIGHT") then
        self.speed.x = self.runSpeed
        sprite.set_hflip("#sprite", false)
    end    
    if action_id == hash("MOVE_LEFT") then
        self.speed.x = self.runSpeed * -1
        sprite.set_hflip("#sprite", true)
    end        
end

Your speed vector isn’t being reset. Put the following at the end of your update function:

self.speed = vmath.vector3()

I tried that but it doesent work. Sorry I am new to coding.

function update(self, dt)
	local pos = go.get_position()
	if self.speed.x ~= 0 then    
		pos = pos + self.speed * dt
		go.set_position(pos)
		if self.curAnim ~= "run" then
			msg.post("#sprite", "play_animation", { id=hash("run") })
			self.curAnim = "run"
			self.speed = vmath.vector3()
		end

No worries. The line needs to go at the end of the function like so:

function update(self, dt)
    local pos = go.get_position()
    if self.speed.x ~= 0 then    
        pos = pos + self.speed * dt
        go.set_position(pos)
        if self.curAnim ~= "run" then
            msg.post("#sprite", "play_animation", { id=hash("run") })
            self.curAnim = "run"
        end
    end
    self.speed = vmath.vector3()
end

Okay it works now but the run anim keeps playing.

You need to add a second case to your ‘if’ statement so the code detects when movement has stopped and plays the idle animation. For example:

if self.curAnim ~= "run" then
    msg.post("#sprite", "play_animation", { id=hash("run") })
    self.curAnim = "run"
elseif self.curAnim ~= "idle" then
    msg.post("#sprite", "play_animation", { id=hash("idle") })
    self.curAnim = "idle"
end

2 Likes

Okay I added that but now this error pops up
image

Revise all blocks of functions and conditions. Most likely there is not enough “end” somewhere in the last lines of the file.

1 Like