Moving sprite object with AWSD keys, across the screen

Hello everyone!
New to Defold but I’ve been loving what I’ve seen so far! I however come in need of some guidance. I’ve been reviewing examples on how to tackle my issue however I can’t seem to get things ironed out. What I currently have is a sprite with animations for walking N,S,W,E. And he performs these animation transitions without issues when A,W,S,D are used. What I would also like to do is have the sprite physically move across the screen, while performing the walk animations that I already have working, until the direction key is released. Should be fairly simple, right? But I’m just not able to tie the movement in with my animation script. I have pasted below my movement script. I would love for some pointers or some existing examples that I might be able to take from pointers from. Thanks in advance.


local currentAnimation = 0

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

function update(self, dt)
	

end

function on_message(self, message_id, message, sender)
	-- Add message-handling code here
	-- Remove this function if not needed
end

function on_input(self, action_id, action)
	
-- Input Right	
	if action_id == hash("toggle_right") and action.pressed == true then
		if self.currentAnimation == 1 then
			msg.post("#sprite", "play_animation", { id = hash("malewalkRight") })
			self.currentAnimation = 0 
			self.speed.x = (action.pressed and 1) or (action.released and 0) or self.speed.x
		else
			msg.post("#sprite", "play_animation", { id = hash("maleidleRight") })
			self.currentAnimation = 1
		end
--Input Left	
	else if action_id == hash("toggle_left") and action.pressed == true then
		if self.currentAnimation == 1 then
			msg.post("#sprite", "play_animation", { id = hash("malewalkLeft") })
			self.currentAnimation = 0
		else
			msg.post("#sprite", "play_animation", { id = hash("maleidleLeft") })
			self.currentAnimation = 1
		end	
--Input Up
	else if action_id == hash("toggle_up") and action.pressed == true then
		if self.currentAnimation == 1 then
			msg.post("#sprite", "play_animation", { id = hash("malewalkUp") })
			self.currentAnimation = 0
		else
			msg.post("#sprite", "play_animation", { id = hash("maleidleUp") })
			self.currentAnimation = 1
		end	
--Input Down
	else if action_id == hash("toggle_down") and action.pressed == true then
		if self.currentAnimation == 1 then
			msg.post("#sprite", "play_animation", { id = hash("malewalkDown") })
			self.currentAnimation = 0
		else
			msg.post("#sprite", "play_animation", { id = hash("maleidleDown") })
			self.currentAnimation = 1
		end	
	
	end
	end
	end	
	end
end

Hi @tmscaf, and welcome!

Here is a good example on how to do this: Simple WASD movement. Hope it helps to get you started.

2 Likes

Thanks @Mathias_Westerdahl, I’ll give it a go shortly and let you know how things turn out. I appreciate the quick response.

2 Likes