I am making a 2D top down shooter and am struggling with aimed shots by enemies. At the moment it works OK but it's not very accurate. Here is my code: (startX,startY,playerX,playerY are class variables). Can anybody help me make this more accurate? Math's isn't my best subject!
private void aimShot() {
this.setLaserX(startX);
this.setLaserY(startY);
float distanceX = startX - playerX;
float distanceY = startY - playerY;
boolean xIsNegative = false;
boolean yIsNegative = false;
if (distanceX < 0) {
xIsNegative = true;
distanceX = -distanceX;
}
if (distanceY < 0) {
yIsNegative = true;
distanceY = -distanceY;
}
if (distanceX == 0) {
distanceX = 1;
}
if (distanceY == 0) {
distanceY = 1;
}
float ratio;
float speedX, speedY;
if (distanceX > distanceY) {
ratio = distanceY/distanceX;
speedX = 10*(1-ratio);
speedY = 10*ratio;
} else {
ratio = distanceX/distanceY;
speedY = 10*ratio;
speedX = 10*(1-ratio);
}
if (xIsNegative) {
speedX = -speedX;
}
if (yIsNegative) {
speedY = -speedY;
}
intSpeedX = Math.round(speedX);
intSpeedY = Math.round(speedY);
}