Reputation: 59
I am trying to make a sprite group in pygame follow a set of waypoints along a path from beginning to end on the screen.
The sprites only move horizontally and vertically.
There are different sprite types that are meant to follow each of the waypoints at different speeds.
The waypoint list looks as follows:
[(1, (8.0, 120.0)), (2, (264.0, 120.0)), (3, (264.0, 648.0)), (4, (504.0, 648.0)), (5, (504.0, 168.0)), (6, (856.0, 168.0)), (7, (856.0, 328.0)), (8, (664.0, 328.0)), (9, (664.0, 696.0)), (10, (808.0, 696.0)), (11, (808.0, 488.0)), (12, (1016.0, 488.0))]
The first integer in each tuple represents the order of which coordinate the sprite should go to first.
The sprite starts off just off the edge of the screen and goes to each of the points using this code that is situated in the sprite class update function:
def update(self, player_health): #ignore player_health parameter - not used yet
if self.current_coords[0] < self.sprite_waypoints[self.next_waypoint][1][0]:
self.current_coords[0] += self.speed #if x is less than waypoint x, move foward by a rate of self.speed
elif self.current_coords[1] < self.sprite_waypoints[self.next_waypoint][1][1]:
self.current_coords[1] += self.speed #if y is less than waypoint y, move foward by a rate of self.speed
elif self.current_coords[0] > self.sprite_waypoints[self.next_waypoint][1][0]:
self.current_coords[0] -= self.speed #if x is greater than waypoint x, move backward by a rate of self.speed
elif self.current_coords[1] > self.sprite_waypoints[self.next_waypoint][1][1]:
self.current_coords[1] -= self.speed #if y is greater than waypoint y, move backward by a rate of self.speed
elif self.current_coords[0] == self.sprite_waypoints[self.next_waypoint][1][0] or self.current_coords[1] != self.sprite_waypoints[self.next_waypoint][1][1]:
self.next_waypoint += 1 #if the sprite coordinates are the same as the waupoint coordinates, move on to the next waypoint
self.rect.center = self.current_coords #coordinates to blit sprite
The problem with this code is that it can't accommodate for speeds that aren't a multiple of 16 (since the distance between each coordinate is a multiple of 16 due to the map's grid size).
If i wanted to use a speed of 5 for example (move 5 pixels per update), when it gets to a waypoint (which denotes a corner of the path) it gets stuck as it never actually lands on the waypoint coordinate, only before and after it.
How can i modify this code so that it is able to accommodate for multiple speeds while being able to change direction to move to the next waypoint?
Upvotes: 0
Views: 309
Reputation: 77860
Check to see whether you're less than speed
units from the next change point. If so, then you move only that many (call if diff
) units, so that you exactly match the needed coordinate. Now you have a second partial move, with the remaining speed-diff
units, in a new direction, chosen by the logic you already have.
Does that get you moving?
Upvotes: 1