r/pythonarcade • • Aug 24 '19

Is there a simple destination-based movement?

Like if I have starting coordinates and destination coordinates, and I want my sprite to automatically stop at the destination without headaches.

3 Upvotes

5 comments sorted by

View all comments

Show parent comment

4

u/[deleted] Aug 25 '19 edited Aug 25 '19

Unfortunately, if you were looking for some form of sprite.move_smoothly_until_you_reach_this_point(dest, speed) function that you could just call once and it would take care of everything for you, such a thing doesn't exist.

The closest you can get is to implement it yourself using a method that sets a destination and a subroutine of update that does the actual work, which still involves keeping track of the destination and moving it each frame (pseudocode follows):

def move_smoothly_until_you_reach_this_point(self, dest, speed):
    """
    Sets a destination on the sprite so that it will move towards that destination each frame.
    dest is a tuple of x and y.
    """
    self.destination = dest
    self.speed = speed
    
def move_to_destination(self):
    """
    Subroutine of `update`. Moves the sprite "self.speed" units towards a specified destination on this frame.
    Assumes you have self.destination, self.x, and self.y defined.
    """
    dest_x = self.destination.x
    dest_y = self.destination.y
    current_distance = ((self.x - dest_x) ** 2 + (self.y - dest_y) ** 2) ** 0.5
    if (current_distance < self.speed):
        self.change_x(self.destination.x)
        self.change_y(self.destination.y) 
    else:
        self.change_x(self.x + self.speed * (self.x - dest_x) / current_distance)
        self.change_y(self.y + self.speed * (self.y - dest_y) / current_distance)

There's no real way to stop the sprite from going too far without using a conditional statement that simply snaps the sprite to the destination coordinates when the distance left to the destination is less than the distance advanced. You just have to use that conditional here.