I wanted to add something special to the Particle-Balls demo I made. At first, the idea seemed pretty simple: When clicking on a moving ball, split it in two with a 90° angle between them (π/2 in radians). To keep it simple, both balls will have the same size as the original and the same speed.

Moving objects
So far, the way I have always animated objects is by storing a 2D position (x, y) and a 2D speed (horizontal speed and vertical speed). If the vertical speed is zero the object will be moving horizontally. If the vertical speed and horizontal are the same, the object will be moving at 45 degrees (π/4) and so on. It is very easy to update the position on every step of the animation according to the speed:
-
// Speed is the number of pixels per second.
-
// Interval is the time between calls in milliseconds.
-
this.position.x += this.speed.x * (interval/1000);
-
this.position.y += this.speed.y * (interval/1000);
Calculating the moving vector
When I started writing the code to split the ball in two, soon I realized my math was way deep in my memory where I couldn’t find it. Yes, trigonometry had to be involved, since I needed to calculate the angle of a moving ball based on the vertical and horizontal velocity. Then I would add 45 degrees (π/4) to the existing ball and create a clone of it, but subtracting 45 degrees (π/4) from the original angle. Easy, uh?
Let’s see. First we need to get the angle of the vector the object is moving on. This vector is determined by the vertical and horizontal speed, which form a right triangle:
Or in Javascript:
-
var angle = Math.atan2(ball.speed.y, ball.speed.x);
Angle of new vectors
Once we have the angle, we can calculate the angle of the new vectors:
-
var V1angle = angle + Math.PI/4; // Add 90 degrees
-
var V2angle = angle – Math.PI/4; // Subtract 90 degrees
2D speeds of new vectors
Once we have the final angles we can calculate the new horizontal and vertical speeds of the new vectors. But first we need Pitagoras to calculate the actual speed of the original vector:
In Javascript:
-
var speed = Math.sqrt(Math.pow(ball.speed.x,2)+Math.pow(ball.speed.y,2));
Given the hypotenuse (speed) and the angle, we can calculate the sides:
In Javascript:
-
ball1.speed.x = speed * Math.cos(V1angle);
-
ball1.speed.y = speed * Math.sin(V1angle);
-
-
ball2.speed.x = speed * Math.cos(V2angle);
-
ball2.speed.y = speed * Math.sin(V2angle);
And that is it! At the end, the math is not that complicated, as you can see. But if you haven’t used trigonometry in years, it kind of hurts a little bit when you have to figure it out.
PS: Thanks to my German sister Sarah for your help (we figured it out while having dinner)

Jeee Eneko, I’m impressed… always knew your pretty smart but thats really cool.