I friends, I will be very gratefull for any answer, a thanks in advance, this is my problem:
In pyglet this is the basic code to update a sprite in the screen:
sprite.x=50
pixels=10
def update开发者_高级运维(dt):
if move_right == True:
sprite.x += pixels * dt
pyglet.clock.schedule_interval(update, 1/60.0)
This results in the sprite moving from point x to the right at 10 pixels speeed per second if the Right key was pressed.
But lets assume I need to move exactly from point X1 to point X2 at a variable and STOP exactly at point X2, how I would do that?
Imagine this:
x_start=20 x_finish=40 I want to move from x=20 to x=40, and stop at x=40. Pixels per second can be any value, lets assume 10 pixels in this example.If I use the usual code I could do:
sprite.x=20
pixels=10
def update(dt):
if sprite.x != 40:
if move_right == True:
sprite.x += pixels * dt
pyglet.clock.schedule_interval(update, 1/60.0)
This would not work, because pixels*dt is not equal to 10, dt is irregular and a float (1/60=0.01, 0.01*10=0.1, and dt is irregular too, so sometimes is 0.01, others is 0.019, others 0.021...etc), so each time the update executes the sprite.x evolution is something like this --> 10, 10,1, 10,24, 10,38, 10.51...etc
So, the if sprite.x != 40: would never work (because sprite.x will allways be a float and hardly will be 40) and my player will never stop.
I know that this problem my have a very easy solution but I have no clue and I am in despair. I am beggining my journey in pyglet so I am very ignorant at this stage, and need help to find a solution, I cant find a way out.
Is there other techniques to update a sprite every frame without using sprite.x += pixels*dt? Are there other solutions?
Very very gratefull, Best regards from Portugal
Here's one way to do it
sprite.x=20
pixels=10
def update(dt):
if sprite.x != 40:
if move_right == True:
sprite.x = min(sprite.x + pixels * dt, 40)
pyglet.clock.schedule_interval(update, 1/60.0)
精彩评论