EDIT: Problem solved. I forgot putting Math.toRadians() anywhere I do Math.cos or Math.sin. :)
I'm working on a simple Java 2D game involving two tanks that shoot missiles and move around the screen. For this question, let's assume there's only one tank.
Controls:
- Adjust angle of movement counter-clockwise: LEFT arrow key
- Adjust angle of movement clockwise: RIGHT arrow key
- Move forward: UP arrow key
- Shoot missile: ENTER
Pressing LEFT or RIGHT also rotates the sprite.
I tried to code the game so that missiles will shoot from the "tank barrerl" (point marked in green). However, the code I wrote doesn't achieve this.
Instead, when pressing ENTER the missile appears in a point on the sprite or around it, that seems to be random.
(Orange point is the tank's origin: tank.getX(),tank.getY() ).
It wouldn't be a problem to code this, if it weren't for the fact the the tank rotates. The location of the green point changes everytime the user rotates the tank.
What is wrong with my code? This code should make the missile 'shoot' from wherever the "barrel" currently is. As I said, doesn't work.
This is what runs when the user presses ENTER.
enterAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
double missileXposition, missileYposition;
double tankMiddleX,tankMiddleY;
double angle, radius;
tankMiddleX = tank1.getX() + (tank1.getWidth()/2);
tankMiddleY = tank1.getY() + (tank1.getHeight()/2);
angle = tank1.getAngle();
radius = tank1.getWidth()/2;
missileXposition = tankMiddleX + ( Math.cos(angle) * radius );
missileYposition = tankMiddleY + ( Math.sin(angle) * radius );
missiles1.add( new Missile( missileXposition, missileYposition , "red" , tank1.getAngle() , tank1) );
}
};
The Missile
class:
public class Missile extends Entity {
public Missile(double x, double y, String type, double angle, Tank tank){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.type = type;
this.angle = angle;
if(type.equals("red")) image = new ImageIcon(this.getClass().getResource("sprites/redrocket1.png")).getImage();
if(type.equals("blue")) image = new ImageIcon(this.getClass().getResource("sprites/bluerocket1.png")).getImage();
width = image.getWidth(null);
height = image.getHeight(null);
if(type.equals("blue")) dx = (-1) * ( 6 * Math.cos(Math.toRadians(tank.getAngle())) );
if(type.equals("red")) dx = 6 * Math.cos(Math.toRadians(tank.getAngle()));
if(type.equals("blue")) dy = (-1) * ( 6 * Math.sin(Math.toRadians(tank.getAngle()) ) );
if(type.equals("red")) dy = 6 * Math.sin(Math.toRadians(tank.getAngle()));
}
}
Thanks a lot
==
to compare String values. Useequals()
– Alexis C.==
to.equals
- there are still 4==
s left – Njol