Reputation: 1149
I've got 2 sprites (well... 3). One sprite is traveling in a straight line at a steady speed at a random angle (in radians). The other sprite is shooting at the moving sprite. Currently the projectile sprite lands slightly behind the target because the projectile is given its destination based on the center of the target when it's fired. I could have it constantly update, but that would just look silly if the projectile changed directions like a homing missile.
So, how on earth do I go about this?
class Projectile (pygame.sprite.Sprite):
container = pygame.sprite.Group()
def __init__ (self, pos, target):
pygame.sprite.Sprite.__init__ (self, self.container)
self.image = FIREBALL
self.rect = self.image.get_rect()
self.rect.center = pos
self.true_loc = self.rect.center
self.destination = target.rect.center
self.speed = 200
diffx = self.destination[0]-self.rect.center[0]
diffy = self.destination[1]-self.rect.center[1]
self.angle = math.atan2(diffx, diffy)
def combineCoords (self, coord1, coord2):
return map(sum, zip(*[coord1, coord2]))
def update (self, time_passed):
new_move = (math.sin(self.angle) * time_passed * self.speed,
math.cos(self.angle) * time_passed * self.speed)
self.true_loc = self.combineCoords(self.true_loc, new_move)
self.rect.center = self.true_loc
The target is a class instance that is basically the same thing with specific class attributes it needs. Specifically, I don't know how to calculate the distance the target will travel based off it's angle and speed based on the distance the Projectile has to travel to get there. Both will have varying speeds and angles. I should have paid attention in math class...
EDIT: It just dawned on me that it's going to be slightly trickier than I initially anticipated, as I dynamically move sprites based on the player's framerate. I was just attempting to calculate the distance between the projectile and target.center, divide that number by how many frames will pass until it reaches it's destination, then update self.destination by moving it by the target's angle by multiplying it's movement and the frames. However with this method if the player's screen hitches for whatever reason (which is common) the projectile will completely miss. Great... I'm back to square one, haha.
Upvotes: 1
Views: 326
Reputation: 7501
If you fix your timestep, you will have stability in your physics. You can keep a variable video framerate, but a constant timestep for physics.
The famous fix-your timestep link http://gafferongames.com/game-physics/fix-your-timestep/ and a pygame example: http://www.pygame.org/wiki/ConstantGameSpeed?parent=CookBook
Theres's a bunch of info and sublinks at https://gamedev.stackexchange.com/questions/4995/predicting-enemy-position-in-order-to-have-an-object-lead-its-target
Upvotes: 1