为什么这个值返回零?

时间:2014-03-12 17:23:37

标签: java physics game-physics

我在球类中有一个方法,它有位置,速度和加速度属性。我正在尝试创建一个基本版本的碰撞检测,其中包括计算两个球之间的距离。我的距离代码如下:

public float getDistance(Ball ball2)
{
    float distance = (float) (Math.sqrt(Math.pow(ball2.x - x, 2) +
                                Math.pow(ball2.y - y, 2)));
    return distance;
}

在代码的另一部分,我反复打印这个距离的值,并且我不断得到零。那是为什么?

编辑:我明白了。我忘记了位置的坐标存储在矢量对象中,所以不应该说ball2.x我应该说ball2.position.x。现在一切都正常计算,我的程序正在运行。谢谢你的帮助!我不确定这些问题是否应该被关闭或者其他什么,但无论mod认为哪种都是最合适的!

5 个答案:

答案 0 :(得分:2)

方法很好。问题出在其他地方。

可能是ball2.x == this.xball2.y == this.y。这可能是因为ball2this是同一个对象,或者是因为您忘记初始化xy,或者出于各种其他可能的原因。

另一种可能性是,您打印的值不是调用distance()的结果,而是其他内容(例如,由于代码中的错误)。

答案 1 :(得分:0)

你不想比较第二球的距离吗?

  public float getDistance(Ball ball2, Ball ball1)
{
    float distance = (float) (Math.sqrt(Math.pow(ball2.x - ball1.x, 2) +
               Math.pow(ball2.y - ball1.y, 2)));
    return distance;

}

您当前正从x中减去x,返回0。

答案 2 :(得分:0)

因为ball2.x = x而ball2.y = y

答案 3 :(得分:0)

如果你的ball2.x和x都是整数,那么当它们彼此相差1个单位时,x - x可以舍入为0,因为你仍在进行整数运算。在减去它们之前,应该将它们作为浮点数投射。然后做数学。

对于ball2.y和y来说,情况也是如此。

答案 4 :(得分:0)

正如有些人已经评论过,你的代码没有任何问题。我将它复制并粘贴到一个演示类中,得到0.223

public class Demo {
    public static void main(String[] args) {
        Demo d = new Demo();
        Ball b1 = d.new Ball(0.1f, 0.5f);
        Ball b2 = d.new Ball(0.2f, 0.7f);
        System.out.println(b1.getDistance(b2));
    }

    class Ball{
        float x,y;

        public Ball(float x, float y) {
            this.x = x;
            this.y = y;
        }

        public float getDistance(Ball ball2)
        {
            float distance = (float) (Math.sqrt(Math.pow(ball2.x - x, 2) +
                                        Math.pow(ball2.y - y, 2)));
            return distance;
        }
    }
}
相关问题