I am making a top down view tank game and I cant seem to get the bullet accuracy to be 100%
It is either just off or just on depending on my mouse position
I am using the formula below to calculate the angle to travel to reach the target (MousePosition)
double dx = MousePosition.x - TankPosition.x;
double dy = MousePosition.y - TankPosition.y;
double angle = Math.atan2(dy, dx);
double tx = Math.cos(angle) * speed;
double ty = Math.sin(angle) * speed;
x += tx;
y += ty;
I am guessing that your problem is an integer vs. float issue, and a matter of rounding. If you are using integers, it will round your result every tick update. This means that depending on your mouse position, it will either be spot on (if your mouse is at a position unaffected by rounding) or slightly off, and will vary depending on said target position seemingly randomly, which sounds like your description of the problem. You’re going to want to keep track of position as a float, and round it only when using it to draw, and not when making calculations to it.