Monday, June 2, 2014

How to set up a vector for a projectile to move along

This isn't that hard, I just felt like writing a blog on the subject.

You are going to need several things.

You need the point you are firing at, they point you are firing from, and trig.


Pseudo code written in java.  
// Locations in 2d space
// these vectors are objects that contain an x float and a y float
Vector MousPos;
Vector PlayerPos;
// Temp variables
float x;
float y;
float hypo;
float xR;
float yR;
// trajectory that the projectile will travel along
Vector trajectory;
x = MousePos.x - PlayerPos.x;
y = MousePos.y - PlayerPos.y;
//finding the hypotenuse
hypo = (float)Math.sqrt(x * x + y * y);
// Finding the ratios
// this will always be a value between -1 and 1
xR = x / hypo;
yR = y / hypo;
trajectory.x = xR;
trajectory.y = yR;
// You don't even have to call a sin or cos function, ain't that great?!
// to move the projectile
projectile.x += projectile.trajector.x * speed;
projectile.y += projectile.trajector.y * speed;



I'm using this code to calculate the trajectory that my lasers need to take on my ship on a case by case basis.
This allows all the bullets to converge into one point in space.

Leave a comment if you have any questions.

No comments:

Post a Comment