Hi,
I have a 2d game where the ball (Player) bounces from obstacles like a laser using Vector2.Reflect.
I tried everything, and through the debugger I noticed that sometimes ContactPoint2D.contacts[0].normal returns a different value.
So, with this function, I reflect the ball:
void ReflectBall(ContactPoint2D contact, Vector2 ballDirection)
{
Vector2 inDirection = Vector2.Reflect(ballDirection, contact.normal);
float rot = Mathf.Atan2(inDirection.y, inDirection.x) * Mathf.Rad2Deg;
_transform.eulerAngles = new Vector3(0, 0, rot);
}
And now, using the debugger, I see that the normal of the contact point is x(0.5) y(-0.9)
Now I set the debugger to break only when the normal does not equal that value (0.5, -0.9).
And I tested on the same game object, hitting it on the same spot:
Here is the object with it’s collider:
as well its physics components:
Now here is the OnCollisionEnter function:
void OnCollisionEnter2D(Collision2D col)
{
Vector2 forward = _transform.right;
// ball hit bound of gamefield, level is going to reset
if (col.gameObject.layer == LayerMask.NameToLayer(Constants.LayerBounds))
{
shouldResetTransform = true;
Reset(false);
}
//if ball hit on figure
else
{
string tag = col.gameObject.tag;
if (tag.Equals("Normal") || tag.Equals("Hard") || tag.Equals("NotDisappear"))
{
ContactPoint2D contact = col.contacts[0];
ReflectBall(contact, forward);
OnHitResponse(col.gameObject);
}
}
}
OnHitResponse() is a heavy function, but it’s called after RefflectBall().
I’d really appreciate any ideas. Thanks