Hi,
What could cause velocity to suddenly change two frames after a collision? I have a ball, no physics materials, no drag, bouncing around with no gravity and continuous collision detection in an enclosed space. I compute collision reactions in OnCollisionEnter myself (it’s a zero-g ball-and-paddle game) using this very simple code:
void OnCollisionEnter(Collision collision)
{
Debug.Log($"---- COLLISION ---- {Time.time}");
ContactPoint contact = collision.GetContact(0);
float ballSpeed = _velocityLastFrame.magnitude;
Vector3 travelDirection = _velocityLastFrame.normalized;
Vector3 reboundDirection = _velocityLastFrame == Vector3.zero ? Vector3.zero : Vector3.Reflect(inDirection: travelDirection, inNormal: contact.normal);
Vector3 reboundVelocity = ballSpeed * reboundDirection;
_rb.velocity = reboundVelocity;
}
_velocityLastFrame is saved from _rb.velocity every FixedUpdate().
private void FixedUpdate()
{
_velocityLastFrame = _rb.velocity;
Debug.Log($"vel={_velocityLastFrame.magnitude} - {Time.time}");
}
Here is what I see in the log:
---- COLLISION ---- 40.44
---- COLLISION ---- 40.44
---- COLLISION ---- 40.44
---- EXIT ---- 40.44
---- EXIT ---- 40.44
vel=4.996597 - 40.46
vel=3.046128 - 40.48
EXIT is printed during OnCollisionExit, which does nothing.
Why does velocity drop from 4.996 to 3.046? Nothing weird happens around this point. It’s often just a collision off of a flat surface. I inserted a Debug.Break() statement when these cases are detected and I see situations like:
Any idea what could be causing this behavior?
Thanks!
– B.