带有点的 Java ArrayList 更新似乎用最近的点替换了所述数组中的所有元素

对我想要做的事情的简短描述:我正在构建一个简单的游戏,其中用户控制车辆,一段时间后越来越多的鬼开始跟随玩家,它们遵循与玩家相同的轨迹,但有延迟。


为了实现这一点,我创建了一个数组,其中包含玩家位置的历史记录作为点序列。然而,问题是,当我查看存储在该数组中的数据时,我发现在所有索引上只存储了最近的位置。


首先,我在 botManager 类中创建数组:


public class BotManager {


private ArrayList<Bots> bots;

private List<Point> history;


BotManager() {

    history = new ArrayList<>();

    bots = new ArrayList<>();

}

然后在管理器类的更新方法中,我将玩家的当前位置添加到数组中


public void update(Point currLoc) {

    history.add(currLoc);


    for (Bots bot : bots) {

        bot.setLocationData(history);

        bot.update();

    }

}

看看主 GameView 类中的更新方法,以防我在这里忘记了一些东西


public void update() {

    player.update(playerPoint);

    botManager.update(playerPoint);

}

在 bots 类的构造函数中,我传递历史列表 (locationData) 并确定其长度以找出定位延迟。之后以下代码处理机器人的位置。


@Override

public void update() {

    loc = locationData.get(delay - 1);

    this.rectangle = new Rect(loc.x - Constants.BOTSIZE/2, loc.y - Constants.BOTSIZE/2,

            loc.x + Constants.BOTSIZE/2, loc.y + Constants.BOTSIZE/2);


}

回到问题,每当我检查历史数组的内容时,我发现它只包含所有索引上的一个点,并且即使我移动播放器也是最新的,导致鬼总是留在顶部我。


所以我的问题是,我在这里做错了什么?


qq_笑_17
浏览 170回答 1
1回答

守着星空守着你

从您发布的代码不明确的,但会不会是,你只是修改了Point其中添加,而不是更新的对象的点对象?尝试public void update(Point currLoc) {&nbsp; &nbsp; history.add(new Point(currLoc)); // new Point object added here&nbsp; &nbsp; for (Bots bot : bots) {&nbsp; &nbsp; &nbsp; &nbsp; bot.setLocationData(history);&nbsp; &nbsp; &nbsp; &nbsp; bot.update();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java