Anarkie
Anarkie

Reputation: 695

Bouncing a ball from circular boundary

enter image description here

This is the formula I found out :

r = v − [2 (n · v) n]

This is how I applied

    //Calculating normal
    nx = 350 -  SmileyReds[i].xpos ;
    ny = 350 -  SmileyReds[i].ypos ;

  //new calc
   v_newx = SmileyReds[i].xspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * nx;
   v_newy = SmileyReds[i].yspeed - (2 *( nx * SmileyReds[i].xspeed + ny * SmileyReds[i].yspeed ) ) * ny;

   SmileyReds[i].xspeed = v_newx;
   SmileyReds[i].yspeed = v_newy;

But instead of bouncing, the balls disappear when they hit the boundary:

Full src and preview http://jsfiddle.net/gj4Q7/4/

Thank you for your time, any tips are welcome!

Upvotes: 4

Views: 627

Answers (1)

Stefan Haustein
Stefan Haustein

Reputation: 18793

I think you need to normalize the normal :)

After

//Calculating normal
nx = 350 -  SmileyReds[i].xpos;
ny = 350 -  SmileyReds[i].ypos;

insert

var len = Math.sqrt(nx * nx + ny * ny);
nx = nx / len;
ny = ny / len;

You can see that you can otherwise easily get values in the range of 350*350 for the speed, catapulting your objects into space...

Upvotes: 3

Related Questions