【问题标题】:Collision detection in Java ufo gameJava ufo 游戏中的碰撞检测
【发布时间】:2014-05-24 00:03:21
【问题描述】:

我有一个简单的 Java 游戏,您可以在其中向移动的目标发射子弹。这两个对象都是 GRects。我有碰撞检测,可以检查 ufo 和子弹何时相互交叉,但奇怪的是:

这行得通:

private void collideWithUFO() { 
    if (bullet != null) {
        GObject collObj = getElementAt(ufo.getX(), ufo.getY()); 
        if (collObj == bullet) {
            remove(ufo); 
            remove(bullet); 
            ufo = null; 
            bullet = null;
        }
     }
}

..但是如果我将getElementAt 更改为如下所示的项目符号,并检查不明飞行物,它无法检测到碰撞:

private void collideWithUFO() { 
    if (bullet != null) {
        GObject collObj = getElementAt(bullet.getX(), bullet.getY()); 
        if (collObj == ufo) {
            remove(ufo); 
            remove(bullet); 
            ufo = null; 
            bullet = null;
        }
     }
 }

我是先选择 ufo 还是先子弹应该无关紧要,但显然不是。现在这里有一些更奇怪的东西。如果我将子弹从 GRect 更改为 GOval,突然之间第二种形式的碰撞检测就起作用了。我是一个 Java 菜鸟,所以请让我知道这种行为是否有意义。

【问题讨论】:

    标签: java collision-detection collision stanford-nlp


    【解决方案1】:
    public GObject getElementAt(double x, double y)
    
    Returns the topmost graphical object that contains the point (x, y), or null if no such object exists.
    

    所以getElementAt(bullet.getX(), bullet.getY()) 只会在 ufo 是最上面的图形元素时给你 ufo,否则你会得到子弹。

    【讨论】:

    • 谢谢,现在我明白了。这也必然意味着将子弹从 GRect 更改为 GOval 也将其置于 UFO 对象之下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多