Jul
31
Flash Ball Collision Prevent Stick and Rotate
July 31, 2008 |
Recently I have found that many people bump into the same problem when making multiple ball collision with random movement in Flash using ActionScript - when 2 balls collide, they will often stick to each other (especially when ed is < 1) and spin around orbiting each other, rotate.
The reason is because the hit detection doesn't always come in time and may also caused by the fact that a few balls are too close to each other. There is a fix to detect the overlap and correct the problem, update the position when overlap's found:
var absV:Number = Math.abs(vel0.x) + Math.abs(vel1.x);
var overlap:Number = (ball0._width / 2 + ball1._width / 2) - Math.abs(pos0.x - pos1.x);
pos0.x += vel0.x / absV * overlap;
pos1.x += vel1.x / absV * overlap;
By using the roll-back kind of collision solver code above, which acts like a sweep test, searches for the earliest collision in the real time frame and puts all balls back to that time, solves the collision and carry on with the simulation until the next collision happens.
In the above example, you can see that balls don’t clutch together. and they let each other go when collide.
The source code can be downloaded at:
http://www.lab.highub.com/flash/physics/collision/ball_collision.fla
Similar Posts
- Flash ActionScript Detect Get Image Width Height
- ComboBox Dropdown Popup List Appears Behind
- Flash ActionScript Detect Mouse Press and Hold
Comments
4 Comments so far



































I used to have this problem, this mostly happens in a crowded environment with many movie clips bouncing off each other, and it seems worse when they are moving at high speeds. Thanks for this great help!
It’s cool in a way that it determines how much the balls are actually overlapping. It does this by getting their total radii, and subtracting their distance. Not sure if this is the best solution, but so far i can’t find a better one. thanks for sharing this!
This is great … Question though, where do you learn this sort of mathematics for simulating collisions? I’m interested in learning how the math here works, rather than just rotely copying your function. (I’ve kept a reference to you and this page in my code.)
Hi, rsmith
I got the idea from an old Java article.
There are many math websites online, like math.com
I don’t know other people’s learning path, base on my personal experience, there is a learning curve in everything, there is no short cut or ‘divine math book’. It takes a lot of time to practice, from copy to modify other people’s code, from modify to write your own solution. The basic theory can be learned from any math book, it’s the practice that counts.