I’m trying to normalize the distance between two balls once a collision has been detected
the collision detection
do_shapes_collide: function(shape1,shape2)
{
var reach1 = shape1.radius + shape1.velocity() + vr.o.border_width;
var reach2 = shape2.radius + shape2.velocity() + vr.o.border_width;
var distance = vr.distance(shape1, shape2);
return distance < reach1 + reach2;
},
so once we’ve determined these sphere’s are colliding, I need to reset their distance from each other… I’m getting flashbacks to my days in algebra class with point/slope formula’s etc…
I’ve got the required distance that needs to exist between them and (what I believe to be) the angle of collision.
I need to set shape x/y on the on the angle of collision.
drawing a blank on what I should do from here to set shape‘s x and y…
if (vr.do_shapes_collide(shape, next_shape))
{
var req_distance = shape.radius + next_shape.radius + (vr.o.border_width * 2);
var slope = (shape.y - next_shape.y) / (shape.x - next_shape.x);
shape.x =
shape.y =
}
Think vectors. If you’ve got the two shapes are overlapping, you’ve got a vector from the center of one to the center of the other like so (this only makes sense after adding their velocities to their positions, since that’s when they’ll overlap):
That’s the vector from
shapetonext_shape. And it has less magnitude (it’s shorter) than it needs to be for the shapes to stay apart. So to find the amount the shapes need to moveNow scale the
diffvector to the match that distance/magnitudeAn finally, move one shape in one direction, and the other shape in the opposite direction
The two shapes should now be just up against each other.
You’ll also want to set their velocities to be in the positive/negative direction of
diff, so they continue on that trajectory after the collision, if indeed they maintain their velocities.Note that this doesn’t really “bounce” the shapes off each other, but only moves them away enough to resolve the overlap that exists after they’ve begun to overlap. So it’s rather simplistic. But there are ton of sources that’ll give you more precise methods for collision detection and collision response.