Simple WASD movement (SOLVED)

@Travis_Mix It looks ok, but I have some comments:

Local vs self vs global
You should read up on and understand Lua scopes. The local speed = 5 at the top will be shared by all instances of game objects with this script attached. Maybe you intend this, maybe you don’t. If you only have one instance of this script then it’s ok, and you probably only have one player controlled game objects, but still it’s worth mentioning. I’ve tried to explain the scopes in Defold in this post.

Set speed in on_input() and move in update()
I would recommend that you set the speed of your game object when you detect input and then apply dt and move the game object in update(). Maybe something like this:

function init(self)
	self.speed = vmath.vector3()
	msg.post(".", "acquire_input_focus")
end

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

function on_input(self, action_id, action)
	if action_id == hash("move_up") then
		-- this might look strange but it's a compact form of if-elseif-else
		-- if action.pressed is true self.speed.y will be set to 1
		-- if action.pressed is false self.speed.y will be set to 0
		-- if neither is true (eg action.repeated) then self.speed.y will remain as it is
		self.speed.y = (action.pressed and 1) or (action.released and 0) or self.speed.y
	elseif action_id == hash("move_down") then
		self.speed.y = (action.pressed and -1) or (action.released and 0) or self.speed.y
	elseif action_id == hash("move_left") then
		self.speed.x = (action.pressed and -1) or (action.released and 0) or self.speed.x
	elseif action_id == hash("move_right") then
		self.speed.x = (action.pressed and 1) or (action.released and 0) or self.speed.x
	end
end
1 Like