I'm trying to create a very simple physics engine in JavaScript, so far I got this: https://github.com/201flaviosilva/Impacto
Well, I stuck in collision resolution/handling, I have a function that finds where the collision happened:
detectRectangleAndRectangleCollisionDirections(rect1, rect2) {
if (this.overlapRectangleAndRectangle(rect1, rect2)) {
const bounds = this.getBoundsOfTwoOverlappingRectangles(rect1, rect2);
// console.log("Collision");
const merged = new Vector2(rect1.getCenterX() - UtilsMathInstance.rectangleCenterXFromRectangle(bounds),
rect1.getCenterY() - UtilsMathInstance.rectangleCenterYFromRectangle(bounds));
// console.log(merged);
const mergedN = new Vector2(merged.x, merged.y);
mergedN.normalize();
const collisions = [];
// console.log(mergedN);
if (mergedN.y > 0.5) collisions.push("TOP");
if (mergedN.y < -0.5) collisions.push("BOTTOM");
if (mergedN.x < -0.5) collisions.push("LEFT");
if (mergedN.x > 0.5) collisions.push("RIGHT");
return collisions;
}
return false;
}
I Have 3 types of physics bodies, Dynamic, Kinematic, and Static.
The problem, for example, when a Rectangle collided with another Rectangle this function returns 2 collision axis, imagine the rectangle A colliding with the rectangle B on the right of rectangle A. In this situation the rectangle A enters rectangle B, so he has the right and the top and bottom inside. So after I got the return of this function I invert the velocity of the object, but with this implementation, I invert a 1 axis that was not supposed to be inverted :)
Please any help is very helpful :)
Image of the example: Collision Example