Page 1 of 1
Pause a sprite's movement?
Posted: Mon Jul 08, 2013 12:31 pm
by crebba
Hi,
I want to move a sprite about 20 pixels at a time every second. What would be the best way to do that?
I assume I need to delay the update of sprite.x in the update() function, but how do I let it pause for that 1 second without affecting other sprites that I may have?
Thanks!
Creabba
Re: Pause a sprite's movement?
Posted: Mon Jul 08, 2013 1:11 pm
by Plu
Include a timer variable for the sprite, make it count, and only update if it's more than 1. Then lower it by 1 for the next cycle. The example below will move the sprite 20 pixels every second:
Code: Select all
image = -- load an image here
sprite_x = 0
sprite_timer = 0
function love.update( dt )
sprite_timer = sprite_timer + dt
if sprite_timer > 1 then
sprite_timer = sprite_timer - 1
sprite_x = sprite_x + 20
end
end
function love.draw()
love.graphics.draw( image, sprite_x, 50 )
end
Re: Pause a sprite's movement?
Posted: Mon Jul 08, 2013 10:46 pm
by Eamonn
Maybe this would have been more appropriate in the Support And Development section...? But yeah, what Plu said!
Re: Pause a sprite's movement?
Posted: Tue Jul 09, 2013 4:32 pm
by Bobbias
crebba wrote:I assume I need to delay the update of sprite.x in the update() function, but how do I let it pause for that 1 second without affecting other sprites that I may have?
I noticed this line and thought I should address it. Remember, the update() function is there to process changes every single frame. The idea is that update() runs for the frame, then draw() runs, so you never want to have code inside the update() function that waits for any length of time. Instead you want to track how much time has passed each update() and only make the changes when the right amount of time has passed (which is exactly what plu's code does.) If you were to put a wait inside the update() your program would almost look frozen, and be very unresponsive, because it would only get a chance to draw things after the update() function returned from waiting. If you set it to wait 1 second in update() you'd only get 1 FPS in your game, which is really really bad.