I have a problem with my Java game(2d, top down view) where my character shoots a bullet in the direction of the mouse. I tried some code I found here but I'm having a problem. thebullet only seldom moves in the right direction. it often moves straigt up, down, left and right. seen the point that I also had this problem with other code I tried I don't think that the problem is in this code. any ideas?

int deltax = bullet.endpos.x - bullet.startx;//this code is when I create a new bullet
int deltay = bullet.endpos.y - bullet.starty;
direction = Math.atan(deltay / deltax);
speed = 5.0;

bullet.x=(bullet.x - (speed * Math.cos(direction)));
bullet.y=(bullet.y - (speed * Math.sin(direction)));
有帮助吗?

解决方案

You don't need to know the real angle in this code.

The code should be:

int deltaX = bullet.endpos.x - bullet.startx; //this code is when I create a new bullet
int deltaY = bullet.endpos.y - bullet.starty;
double radius = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
double normalizedDeltaX = deltaX / radius;
double normalizedDeltaY = deltaY / radius;
speed = 5.0;

bullet.x -= /*maybe your error is here, and there should be += as you need to increment coordinates, not decrement*/ speed * normalizedDeltaX;
bullet.y -= /*the same thing here*/ speed * normalizedDeltaY;

Or if you would really you this angle later (what for?) in this case Math.atan2 is more appreciated, because you won't lose third and fourth quarters of the plane:

double direction = Math.atan2(deltaY, deltaX);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top