0

I'm building a simple Android Game. And I'm stuck on detecting the direction of a collision of two balls. I have a moving ball A, and a fixed ball B. Ball A is much smaller than B.

I do not care about the mass of two balls. After the collision of two balls, the ball B is disappear, and the ball A changes the direction!

I want something like this..

Collision of two balls

Here is my current code:

private void collision(Ball a, Ball b){
        if(b.isVisible){
            double d = Math.sqrt((a.cx - b.cx)*(a.cx - b.cx) + (a.cy - b.cy)*(a.cy - b.cy));

            if(d <= a.radius + b.radius) {
                b.isVisible = false;
                if(a.dx * b.dx < 0 && a.dy * b.dy < 0){
                    a.dx = - a.dx;
                    a.dy = - a.dy;
                    b.dx = - b.dx;
                    b.dy = - b.dy;
                } else if(a.dx * b.dx < 0){
                    a.dx =- b.dx;
                    a.dx = - b.dx;
                } else if(a.dy * b.dy < 0){
                    a.dy = - a.dy;
                    b.dy = - b.dy;
                } else{
                    a.dx = - a.dx;
                    a.dy = - a.dy;
                    b.dx = - b.dx;
                    b.dy = - b.dy;
                }
            }

        }

    }

But it just reverses the direction of the ball B

So, I'm finding the better solution. Anyone help? Thanks a lot!

Community
  • 1
  • 1
Tan Dat
  • 2,888
  • 1
  • 17
  • 39
  • I think you mean you want to **calculate** the direction. Since 'b' is going to disappear, why not take it out of the code. You need to calculate the angle A strikes B because it is at perpendicular to that angle that it would bounce. – Peter Lawrey Mar 23 '16 at 10:45

1 Answers1

0

I can give you some guidelines for your case without delving into equations.

The important aspects for what you're trying to achieve are the point of contact and direction of the moving ball (note your case is kind of hypothetical since masses and velocities of both balls do normally matter).

You can draw an imaginary tangent line at the point of contact between the two balls and treat it as a reflection surface. With this in mind, you can calculate the reflection angle given the direction of the moving ball (see the attached picture).

RZet
  • 914
  • 9
  • 11