Pause a sprite's movement?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
crebba
Prole
Posts: 1
Joined: Thu Jun 27, 2013 5:59 pm

Pause a sprite's movement?

Post 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
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Pause a sprite's movement?

Post 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
User avatar
Eamonn
Party member
Posts: 550
Joined: Sat May 04, 2013 1:29 pm
Location: Ireland

Re: Pause a sprite's movement?

Post by Eamonn »

Maybe this would have been more appropriate in the Support And Development section...? But yeah, what Plu said! :)
"In those quiet moments, you come into my mind" - Liam Reilly
Bobbias
Prole
Posts: 36
Joined: Sat Jun 29, 2013 1:26 pm

Re: Pause a sprite's movement?

Post 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.
Post Reply

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 7 guests