To make car collisions more realistic, you need to take into account
- their mass
- the shape of the object, hitting a long object at a point away from its center of gravity will cause the object to tend to rotate rather than move away.
- friction against the ground and against colliding objects.
- the location of the object's center of gravity.
Matter.js - has it all. I know because I am currently combining the PIXI graphics engine and the Matter.js graphics engine into one.
You can add this library to your project and compare the behavior of Matter.js and your code.
Here is an example of physics for the collision of circle objects, taking into account that the collision may not occur at a normal angle.
https://microstudio.dev/i/this_name_is_taken/poolballphysics/
https://www.youtube.com/watch?v=9IULfQH7E90 - 1:18 - here it is explained how the physics engine works.
Generally, the smaller the step, the better.
Search for videos on YouTube with titles - 2d physics engine
I will check your code.
I see that the graphics are nicer now than when I first looked at the project.
It looks nice.
Edit
Code analysis :
you don't use deltaTime, in the future it will take its revenge when, for example, chilow frames drop by half.
Physics calculations should take into account how much time has passed since the last update.
Objects behave strangely because, from what I have analyzed, collisions are counted twice for the same pair of cars in one frame.
"collisionSolid(other)" function
- I don't really understand the code of the collisionSolid(other) function, I would do it like this
calculateCollisionVelocity(m1, v1, m2, v2) {
// Calculating the final velocity of objects after a collision
let velocity = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2);
return velocity;
}
collisionSolid(other) {
let vx1 = this.vx;
let vy1 = this.vy;
let vx2 = other.vx;
let vy2 = other.vy;
this.vx = this.calculateCollisionVelocity( this.mass, vx1, other.mass, vx2);
this.vy = this.calculateCollisionVelocity( this.mass, vy1, other.mass, vy2);
other.vx = this.calculateCollisionVelocity( other.mass, vx2, this.mass, vx1);
other.vy = this.calculateCollisionVelocity( other.mass, vy2, this.mass, vy1);
}
It's not perfect because
- collision is triggered twice.
- does not take into account the place of collision
- does not take into account angles