- Home /
2D Custom Bouncing Diagonal
Hi,
I am simply trying to get the Player to bounce off of objects with the following script. The concern I am having is that when the Player collides diagonally, it gets more velocity than it would have if it just collided in a straight line, or rather it gets pushed further back when hitting the object at a velocity with values greater than 0 for the x and y, as opposed to a velocity of just a single x or y value greater than 0. My goal, if I am understanding physics correctly, is that even when the Player collides with the object "diagonally" it will move only as far as it would have in a head-on collision. Thank you for any time and help. (Sorry to clarify, the below code would be attached to the object that the Player collides with, not the Player itself.)
private void OnCollisionEnter2D(Collision2D collision)
{
var player = collision.collider.GetComponent<PlayerInput>();
if (player != null)
{
var rigidbody2D = player.GetComponent<Rigidbody2D>();
if (rigidbody2D != null)
{
Vector2 direction = -collision.GetContact(0).normal.normalized;
rigidbody2D.velocity = direction * _bounceVelocity;
}
}
}
Your answer
Follow this Question
Related Questions
Edge Collider issue 1 Answer
Collision issues with Vector2.Reflect 1 Answer
2D Bounce gains energy each time 1 Answer
Help with Collision2D.relativeVelocity? 1 Answer
Physics2D.SetLayerCollisionMask delays before being applied 0 Answers