You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何获取同一类的另一个对象的变量值?游戏碰撞检测需求

解决Sphere与Player碰撞检测的同步问题

核心问题分析

你在Sphere类中新建Player对象的做法,会导致这个对象和Game类中实际控制的Player实例完全独立,两者的位置自然无法同步。正确的思路是让Sphere直接引用Game中已经存在的那个Player实例,而不是重新创建。

具体实现方案

1. 给Sphere类添加接收Player实例的构造方法

在Sphere类中,添加构造方法接收Game里的Player对象并保存为成员变量,这样就能获取到Player的实时位置:

public class Sphere {
    private Player player;
    private int x;
    private int y;

    // 传入Game中已有的Player实例
    public Sphere(Player player) {
        this.player = player;
    }

    // 碰撞检测逻辑
    public boolean checkCollision() {
        // 调用Player的Getter获取实时位置
        int playerX = player.getX();
        int playerY = player.getY();
        // 这里替换为你的碰撞判断规则(示例为矩形碰撞)
        return Math.abs(this.x - playerX) < 50 && Math.abs(this.y - playerY) < 50;
    }

    // Sphere自身的位置Setter/Getter
    public void setX(int x) { this.x = x; }
    public int getX() { return x; }
    // ...其他位置相关方法
}

2. 在Game类中创建Sphere时传入Player实例

Game类中已经持有Player的实例,创建Sphere时直接把这个实例传进去即可:

public class Game {
    private Player player;
    private Sphere sphere;

    public Game() {
        player = new Player();
        // 将已有的Player实例传递给Sphere
        sphere = new Sphere(player);
    }

    public void updateGameState() {
        player.move(); // 更新Player的位置
        // 调用Sphere的碰撞检测,此时用的是Player的实时位置
        boolean collided = sphere.checkCollision();
        // 处理碰撞后的逻辑...
    }
}

3. 替代方案:由Game类统一处理碰撞检测

如果不想让Sphere持有Player的引用,可以把碰撞检测逻辑放到Game类中,由Game作为中间协调者获取两者的位置进行判断:

public class Game {
    private Player player;
    private Sphere sphere;

    public Game() {
        player = new Player();
        sphere = new Sphere();
    }

    public boolean checkCollision() {
        int playerX = player.getX();
        int playerY = player.getY();
        int sphereX = sphere.getX();
        int sphereY = sphere.getY();

        // 碰撞判断规则
        return Math.abs(sphereX - playerX) < 50 && Math.abs(sphereY - playerY) < 50;
    }
}

关键总结

  • 避免在需要同步状态的类中新建关联对象,要传递已有的实例引用,保证状态同步
  • 两种可行思路:让Sphere持有Player引用自行检测,或由Game类统一处理碰撞逻辑

内容的提问来源于stack exchange,提问作者TillRohlFingMann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 19:55:24