Reputation: 13
I need to calculate X and Y speed for bullet (bullet will move every "update" by these), so i have following
public int[] getXandYSpeed(int pointOfOriginX, int pointOfOriginY, int aimToX, int aimToY){
int[] coords = new int[2];
aimToX = aimToX - pointOfOriginX;
aimToY = aimToY - pointOfOriginY;
while((aimToX + aimToY) > 5){
aimToX = aimToX/2;
aimToY = aimToY/2;
}
coords[0] = aimToX;
coords[1] = aimToY;
return coords;
But, this is not really accuare and bullet have like random speed(if final in final loop is aimToX plus AimToY equals 6 so (each is 3) so final speed will be x=1 and y=1, and if final loop equals four than it will end like x=2 and y=2, and thats making difference)
So, question is, how to make it better?
Upvotes: 1
Views: 200
Reputation: 888
if you want the bullet to travel at a constant speed at any angle, you really want something more like this. Also the comments about using double from @JSlain are spot on, they will be much more accurate even if you have to round out the values when you draw/render the bullet
public double[] getSpeed(int sx, int sy, int ex, int ey)
{
double dx = ex - sx;
double dy = ey - sy;
double theta = Math.atan2(dy, dx); //get the angle your bullet will travel
int bulletSpeed = 5; //how fast your bullet can go.
double[] speeds = new double[2];
speeds[0] = Math.cos(theta) * bulletSpeed;
speeds[1] = Math.sin(theta) * bulletSpeed;
return speeds;
}
Upvotes: 1