I am working on making a Top-Down Shooter Clone in Java. After an hour or so, I was able to figure how to position the ship’s projectile which is a laser relative to the direction of the ship’s sprite. Problem is, if I move the ship, the projectile follows relative to the ship direction when I move the ship. As you can see this is a problem because the laser should be moving independently regardless of where the ship is when it is fired.
Here’s the code which presents my problem:
private Image ship;
private int ship_dx = 500;
private int ship_dy = 400;
private int ship_velocity = 5;
private boolean isLaser = false;
private static final int laser_DyOffSetOfBall = 48;
private static final int laser_DxOffSetOfBall = 23;
private Image laser;
private int laser_dx = ship_dx+laser_DxOffSetOfBall;
private int laser_dy = ship_dy-laser_DyOffSetOfBall;
private int laser_velocity= 10;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(ship, ship_dx, ship_dy, this);
if(isLaser){
laser_dy -= laser_velocity;
laser_dx = ship_dx+laser_DxOffSetOfBall;
g.drawImage(laser,laser_dx,laser_dy,this);
if(laser_dy < 50)
{
isLaser = false;
laser_dy = ship_dy-laser_DyOffSetOfBall;
}
}
Toolkit.getDefaultToolkit().sync();
}
Here’s the game!:
You only need to set the x location of the laser on the first time it is painted, because otherwise on every repaint, the laser moves horizontally relatively to the ship. To do this you can add another boolean isFirst (for the first paint of the laser), that is set to true when isLaser first turns to be true, and the x location is only set when isFirst is true.