- Home
- Tutorials
- Flash
- Intermediate
- Balls chain with constraints, colision, mouse follow and the math needed
Balls chain with constraints, colision, mouse follow and the math needed

Constraints, fun is comming!
function keepDistance(obj1, obj2, dist) { orig = {x:obj1._x, y:obj1._y}; dest = {x:obj2._x, y:obj2._y}; myAngle = Math.atan2((orig.y-dest.y), (orig.x-dest.x)); myDistance = Math2.distanceBetween(orig.x, orig.y, dest.x, dest.y); if (myDistance<=dist-0.1) { obj1._x -= Math2.cos(myAngle)*((myDistance-dist)/2); obj1._y -= Math2.sin(myAngle)*((myDistance-dist)/2); obj2._x += Math2.cos(myAngle)*((myDistance-dist)/2); obj2._y += Math2.sin(myAngle)*((myDistance-dist)/2); } }
There are not a lot of changes here..basically we want to avoid one ball over another one. So, when the distance is lower than the distance that we want, we will have to move both movies along the angle, with the distance, in an opposite orientation. Since both balls are equal in size, we use the distance divided by 2.
Note that 0.1 is just a correction to avoid litle movements.
Next section will cover the integration of all the work we have so far.

