I am trying to find the bug that gives the opposite direction to the ball when a cue ball hits it from the very edge. For example, when a cue ball hits from the ball grom the right side, it should go to the left, but it is going to the right as well. Why is it so? It is happening if you hit it with high speed and when really edge is aimed.
Here is some code from the game:
private resolveBallsCollision(first: Ball, second: Ball): boolean {
if (!first.visible || !second.visible) {
return false;
}
// Find a normal vector
const n: Vector2 = first.position.subtract(second.position);
// Find distance
const dist: number = n.length;
if (dist > ballConfig.diameter) {
return false;
}
// Find minimum translation distance
const mtd = n.mult((ballConfig.diameter - dist) / dist);
// Push-pull balls apart
first.position = first.position.add(mtd.mult(0.5));
second.position = second.position.subtract(mtd.mult(0.5));
// Find unit normal vector
const un = n.mult(1 / n.length);
// Find unit tangent vector
const ut = new Vector2(-un.y, un.x);
// Project velocities onto the unit normal and unit tangent vectors
const v1n: number = un.dot(first.velocity);
const v1t: number = ut.dot(first.velocity);
const v2n: number = un.dot(second.velocity);
const v2t: number = ut.dot(second.velocity);
// Convert the scalar normal and tangential velocities into vectors
const v1nTag: Vector2 = un.mult(v2n);
const v1tTag: Vector2 = ut.mult(v1t);
const v2nTag: Vector2 = un.mult(v1n);
const v2tTag: Vector2 = ut.mult(v2t);
// Update velocities (summ velocities from hit & rotation)
first.velocity = v1nTag.add(v1tTag);
second.velocity = v2nTag.add(v2tTag);
first.velocity = first.velocity.mult(1 - physicsConfig.collisionLoss);
second.velocity = second.velocity.mult(1 - physicsConfig.collisionLoss);
// Update rotations
first.rotation = { x: 0, y: 0, z: 0 }
second.rotation = { x: 0, y: 0, z: 0 }
return true;
}