user1650305
user1650305

Reputation:

ArrayList of Entites Random Movement

I have an arraylist of entites that I want to move randomly. No matter what I do, they won't move. Here is my female class:

public class Female extends Entity {
static int femaleX = 0;
static int femaleY = 0;
double walkSpeed = .1f;
Random rand = new Random();
int random;
int dir;

Player player;

public Female(int posX, int posY) {
    super(posX, posY);

}

public void update() {
    posX += femaleX;
    posY += femaleY;

    moveFemale();

}

public void draw(Graphics2D g2d) {
    g2d.drawImage(getFemaleImg(), posX, posY, null);
    if (Player.showBounds == true) {
        g2d.draw(getBounds());
    }
}

public Image getFemaleImg() {
    ImageIcon ic = new ImageIcon("res/female.png");
    return ic.getImage();
}

public Rectangle getBounds() {
    return new Rectangle(posX, posY, getFemaleImg().getHeight(null),
            getFemaleImg().getWidth(null));
}

public void moveFemale() {
    random = rand.nextInt(3);
    System.out.println(random);

    if (random == 0) {
        dir = 0;
        posX -= (int) walkSpeed;
    }
}
      }

And here is how I update the female class in the main class:

public void actionPerformed(ActionEvent ae) {
    player.update();

    for(int i = 0; i < females.size(); i++){
        Female tempFemale = females.get(i);
        tempFemale.update();
    }
    repaint();
}

If I do something like this(in the female update method):

public void update() {
    posX += femaleX;
    posY += femaleY;

    posX -= walkSpeed;

}

The characters move with no problem. Why is this?

Upvotes: 0

Views: 286

Answers (2)

chm
chm

Reputation: 1519

Because femaleX and femaleY are zero. Adding them to posX and posY doesn't change those variables, but adding a nonzero variable like walkSpeed does.

EDIT: For the randomness problem, I'll have to take a stab in the dark since I can't see all of your code, but perhaps you aren't calling your moveFemale method, which is the movement method with randomness in it. The update method is completely deterministic. If you want the females to move randomly, either call the moveFemale method or add randomness to the update method.

This is an example of a general rule in object-oriented programming: it's bad to have two methods (update and moveFemale) that appear to do the same or very similar things.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272307

femaleX and femaleY are never non-zero, as far as I can see.

Upvotes: 0

Related Questions