Question

I have set up a bullet firing system in my 2D Game. where when the character is moving left the bullet is launched and moves left and well. this works for the right side aswell. but heres the problem... Say I shoot left but before it exits the screen the character moves right, this change in direction also changes the direction of the already moving bullet and it moves to the right like the character. I can make the bullet move back and forth with the left and right keys.

heres the bullet class. the move() method moves the bullet.

package gameLibrary;

import java.awt.*;
import java.util.ArrayList;

import javax.swing.ImageIcon;

public class Bullet {

int x,y, x2;
Image img;
boolean visible;

public Bullet(int startX, int startY) {
    x = startX;
    x2 = startX;
    y = startY;

ImageIcon newBullet = new             
ImageIcon(getClass().getResource("/resources/bullet.png"));
img = newBullet.getImage();
    visible = true;

}
public void move(){

    if(Character.left){
        x -= 4;
        if(x < 0){
            visible = false;
            Character.left = false;
        }
    }
    if(Character.right) {
        x = x + 4;
        if(x > 854){
        visible = false; 
        Character.right = false;
    }
    }



}
public int getX(){
    return x;
}
public int getY() {
    return y;
}
public boolean getVisible(){
    return visible;
}
public Image getImage(){
    return img;
}
 }
Was it helpful?

Solution

The bullet needs to know its initial direction, so pass a boolean in the constructor and set a boolean member variable (maybe call it moveLeft). Then, in move, check the boolean member instead of checking Character.left. The if (Character.right) could just be an else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top