From GPWiki
Jump to: navigation, search

If you've read the tutorials on Spaceship Physics and Gravity, then you aren't too far from understanding projectiles. The only new concept is that of relative velocities. When a projectile is launched from a moving object, that projectile gains the velocity of the object in addition to the velocity inherent in the projectile itself. For example, if you're running along at 10m/s (a fair clip) and you shoot a gun in the same direction, the speed of the bullet is increased by 10m/s, thanks to your running. If you were simply standing still, the bullet would merely be travelling at standard bullet speed.. see what I mean?

Now, this gets complicated if the object doing the shooting is NOT moving parallel with the projectile's initial direction. Imagine that you're running forward and shooting sideways.. the bullet is moving sideways (relative to you) at standard bullet speed, and forward at 10m/s (thanks, again, to your running). We need to use trigonometry to add the two velocity vectors together in order to obtain the resultant speed and direction. We can use the EXACT same formula as we used previously for acceleration, but in this case, it's a one-time thing. When we applied forces, we did it for a duration (thrust) or continuously (gravity), whereas projectiles get one essentially instantaneous push when they're launched.

sngXComp = msngSpeed * Sin(msngHeading) + BULLET_SPEED * Sin(msngFacing) sngYComp = msngSpeed * Cos(msngHeading) + BULLET_SPEED * Cos(msngFacing)

This code calculates the X and Y components of the resultant velocity by adding the components of the object's velocity and the bullet's velocity.

msngBulletSpeed = Sqr(sngXComp ^ 2 + sngYComp ^ 2)

Here we've calculated the final speed of the bullet using pythagoras.

If sngYComp > 0 Then msngBulletHeading = Atn(sngXComp / sngYComp) If sngYComp < 0 Then msngBulletHeading = Atn(sngXComp / sngYComp) + PI

And finally, we use ArcTangent to determine the final direction of the bullet. That's all there is to it!

See the Gravity Demo source code for projectiles on the Earth's surface, or check out the Spaceship Bullets Demo source to see how it works in space!