# How to calculate magnitude when resolving collision events?

I am trying to write my own 3D collision resolving logic. I want to write this myself for learning purposes.

void OnCollisionStay(Collision col)
{
Vector3 HitVector = transform.position - col.contacts[0].thisCollider.ClosestPointOnBounds(transform.position);

transform.Translate(col.contacts[0].normal * CurrentSpeed, Space.World);
}

It kind of works. The object hitting the wall is pushed back by the normal of the thing it hit, but the distance it is moving is wrong, causing jerky movement:

The multicolored line is the history of positions of the car driving North. You can see it zig zags a bit as it is pushed off the wall further than its collision bounds, causing it drive forward for a few frames before hitting the wall again.

What is the correct way to calculate the offset require the put the collider against the edge of the wall?

You may be aiming a bit high with this. Consider the physics engine was developed by hundreds of devs with high level degrees and experience.

But for the sake of learning, you could use the dot product of the direction of the car and the normal of the hit. The dot of two perpendicular vectors will return 0, so if forward and normal are perpendicular, aka the car is hitting on the side and should not bounce too much, then your value is multiplied by something close to 0 and affect just a little:

void OnCollisionStay(Collision col)
{
float dot = Mathf.Abs(Vector3.Dot(transform.forward, col.contacts[0].normal));
transform.Translate(col.contacts[0].normal * CurrentSpeed * dot, Space.World);
}