I have many particles moving around and hit detection to see when they touch. If two particles touch they should bounce off in the opposite direction.
particle.moveSelf = function() {
var radians = this.angle * Math.PI / 180;
var moveX = this.velocity * Math.sin(radians);
var moveY = this.velocity * Math.cos(radians);
for (var i = 0; i < particles.length; i++) {
var distance = this.position.getDistance(new Point(particles[i].position.x, particles[i].position.y));
//if distance < radius 1 + radius 2, bounce this circle away
if (distance < (this.radius + particles[i].radius) && this.id !== particles[i].id) {
this.velocity = -this.velocity;
}
}
this.position.x += moveX;
this.position.y += moveY;
};
When I run this code, the circles get stuck in each other moving back and forth by 1*velocity every frame.
There are lots of questions on how to work out the velocity or angle of the bounce but my problem is just that it gets stuck in an infinite oscillation.
I done this before so here are some insights:
the safest way is add list of collisions per each particle
and clear/fill the collision lists with indexes of all particles that collide to each other
you can also do this with one list inside for (i=0;i<...) loop instead
update position and speed of collided items only
then add in each collision a reflection (unit or speed or force impulse) vector to it
when it is done then just update the positions/speed ...
you can also compute the combined kinetic energy vector of all bounced particles and compute the new speeds form it via mass energy distribution
[Notes]