gpt4 book ai didi

java - 实体随机移动的ArrayList

转载 作者:行者123 更新时间:2023-12-01 15:04:53 26 4
gpt4 key购买 nike

我有一个实体数组列表,我想随机移动它。无论我做什么,他们都不会动。这是我的女性类(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;
}
}
}

这是我在主类中更新女性类的方法:

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

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

如果我做这样的事情(在女性更新方法中):

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

posX -= walkSpeed;

}

角色移动没有问题。这是为什么?

最佳答案

因为femaleXfemaleY为零。将它们添加到 posXposY 不会更改这些变量,但添加像 walkSpeed 这样的非零变量却可以。

编辑:对于随机性问题,我必须在黑暗中尝试,因为我看不到你的所有代码,但是也许你没有调用你的 moveFemale 方法,这就是带有随机性的运动方式。更新方法是完全确定性的。如果您希望女性随机移动,请调用 moveFemale 方法或在 update 方法中添加随机性。

这是面向对象编程中一般规则的示例:有两个方法(update 和 moveFemale)看起来执行相同或非常相似的操作是不好的。

关于java - 实体随机移动的ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13111898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com