[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Re: Keeping a sprite on screen with rect.clamp



On Mon, Aug 16, 2010 at 8:43 PM, Mark Reed <markreed99@xxxxxxxxx> wrote:
I want to calculate a straight path of points between two points and
each frame do:

sprite.x, sprite.y = sprite.path[step]
step++

And have the sprite move along that line.  I've lost all basic math
skills, and don't want to spend an hour debugging such a simple thing.

Mark
Hi,
 
What you probably want is lerp (linear interpolation), which linearly interpolates between two 2D points.  In practice, you'll want to use time for x, so you use two lerp commands, one for the x coordinate and one for the y coordinate:

def lerp(a,b,x):
    #Actually, this function is more complicated, but for the
    #special case of time ranging from 0.0 to 1.0, it can be written:
    return a + x*(b-a)
start_point = [#blah1,#blah2]
end_point = [#blah3,#blah4]
point = [ lerp(start_point[0],end_point[0],time), lerp(start_point[1],end_point[1],time) ]
#Not tested, but should work.  As time goes from 0.0 to 1.0, "point" will
#be a point from "start_point" to "end_point".


If you want to be really really really specific with your sprite's movement, there are some spline classes you can use to make your sprite be interpolated through multiple points, with a smooth path between them.  There's probably some easily accessible ones on pygame.org--I know that there's a Kochanek-Bartels spline class in the math section of my graphics library. 

Ian