Matan Kadosh
Matan Kadosh

Reputation: 1781

Bouncing Balls in d3

Hi I am using this example in order to have multiple balls (with the same size) that bounce inside a frame.

The thing is that i need to change it in a way that after 2 balls have collided they will bounce back into a random direction and not necessarily the "physics" way. of cource the balls mustn't overlap each other at any time.

Would love to hear some suggestions on how to create that random movement after colliding.

edit

forgot to mention, the balls should always remain on the same speed, Because all the balls in my case have the same radius they are also on the same speed. So simply incresing or decreasing the vx and vy won't do.

edit 2

In my opinion and according to some logics I made, the course should be a random angle in a range of 180 degrees from the contact point of the ball. The thing is I don't know how to make these calculation, get each ball contact point and take the range from there

Upvotes: 0

Views: 636

Answers (2)

derp
derp

Reputation: 2308

after the line

        if ( CheckCollision(ball1, ball2) ) {

The code performs the calculations to determine the new velocities for ball1 and ball2 before setting them here:

//set velocities for both balls
            ball1.vx = vx1;
            ball1.vy = vy1;
            ball2.vx = vx2;
            ball2.vy = vy2;

If you don't want them to be realistic, then you can simply change vx1, vy1 and vx2 and vy2 to a random value. You will probably have to retain this code

//ensure one ball is not inside others. distant apart till not colliding
            while (CheckCollision(ball1, ball2)) {
                ball1.posX += ball1.vx;
                ball1.posY += ball1.vy;

                ball2.posX += ball2.vx;
                ball2.posY += ball2.vy;
            }

to ensure that you don't draw the balls inside each other. This however might mean that the balls will "phase" through one in a random way

Upvotes: 2

Cyril Cherian
Cyril Cherian

Reputation: 32327

One solution, would be to change the angle of action post collision

    if ( CheckCollision(ball1, ball2) ) {
        //change the angle of both the balls
        console.log(ball1.aoa, ball2.aoa, "old");
        var a1 = Math.floor((Math.random() * 10) + 1);//change the angle using random
        ball1.aoa = Math.PI / a1;

        var a2 = Math.floor((Math.random() * 10) + 1);//change the angle using random
        ball2.aoa = Math.PI / a2;
        console.log(ball1.aoa, ball2.aoa, "new");

working code here

Upvotes: 2

Related Questions