Domanda

I have a method inside of a ball class that has location, velocity, and acceleration attributes. I'm trying to create a rudimentary version of collision detection, which involves calculating the distance between the two balls. I have the following code for my distance:

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

In another part of the code I print the value of this distance repeatedly, and I keep getting zeros. Why is that?

EDIT: I figured it out. I forgot that the coordinates of the position were being stored in a vector object, so instead of saying ball2.x I should have said ball2.position.x. Now everything is calculating correctly and my program is working. Thanks for the help folks! I'm not sure if this questions should be closed or whatever, but whatever the mods think is most appropriate!

È stato utile?

Soluzione

The method is fine. The problem lies elsewhere.

It could be that ball2.x == this.x and ball2.y == this.y. This could be because ball2 and this are the same object, or because you forget to initialize x and y, or for a variety of other possible reasons.

Another possibility is that the value you're printing out is not the result of calling distance(), but is something else (for example, because of an error in the code).

Altri suggerimenti

Don't you want to compare the distance to the second ball?

  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;

}

You are currently subtracting x from x, returning 0.

Because ball2.x = x and ball2.y = y

If your ball2.x and x are both integers, then when they are within 1 unit of each other, x - x can round to 0 because you are still doing integer math. You should cast them as floats before you subtract them. then do the math.

This goes the same for ball2.y and y.

As some people already commented there is nothing wrong with your code. I copied and paste it in a demo class and got 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;
        }
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top