2D movement velocity from an initial degree?
My 2D platformer has things that can shoot in ANY direction, i.e. 360 degrees.
Every buttet has its own struct as follows...
typedef struct bullet
{
float XPos, YPos;(move by XVel and YVel)
float XVel, YVel;(stay the same after shooting)
float shootVel;(Num of pixels the bullet moves every 10ms)
etc..
}
The bullets'' position needs to be updated every 10ms by a constant velocity of 6.0f pixels (the shootVel) in any direction.
What I need is a way to convert the degree of the initial shooting to the buttets'' x and y velocities.
My code is as follows..
at every 10ms
{
bullet.XPos += bullet.XVel;
bullet.YPos += bullet.YVel;
bullet->blit();
}
So if i shoot at a degree of 70, the xvel would be about 5.7f and the yvel would be about .04f.
Or if I shoot at 180 (straight down), XVel = 0, YVel = 6.0f.
How do I calculate the required velocities mathematically?
Radians = Degrees * Pi / 180.0;
Velocity.X = Speed * cos(Radians);
Velocity.Y = Speed * -sin(Radians);
That''s the algorithm if 0 degrees is right and 90 degrees is up.
~CGameProgrammer( );
Velocity.X = Speed * cos(Radians);
Velocity.Y = Speed * -sin(Radians);
That''s the algorithm if 0 degrees is right and 90 degrees is up.
~CGameProgrammer( );
Simple trigonometry. But 180 degrees on the unit circle doesnt point down, it points to the left.
bullet.XVel = bullet.shootVel * cos(angle)
bullet.YVel = bullet.shootVel * sin(angle)
note that this is pseudocode; in real code, cos() takes radians not degrees, but converting between the two is trivial.
xvel = 6 * cos(70)
xvel = 6 * 0.342
xvel = 2.052
yvel = 6 * sin(70)
yvel = 6 * 0.939
yvel = 5.634
so in that frame, your bullet moves 2 pixels right and 6 pixels up
oops, I forgot that you need to compensate for the inversed y direction on the monitor by using -sin() instead of just sin()
Edited by - foofightr on 3/22/00 12:50:38 AM
bullet.XVel = bullet.shootVel * cos(angle)
bullet.YVel = bullet.shootVel * sin(angle)
note that this is pseudocode; in real code, cos() takes radians not degrees, but converting between the two is trivial.
xvel = 6 * cos(70)
xvel = 6 * 0.342
xvel = 2.052
yvel = 6 * sin(70)
yvel = 6 * 0.939
yvel = 5.634
so in that frame, your bullet moves 2 pixels right and 6 pixels up
oops, I forgot that you need to compensate for the inversed y direction on the monitor by using -sin() instead of just sin()
Edited by - foofightr on 3/22/00 12:50:38 AM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement