I am making a 2D game where balls bounce from the edges of the screen, However, there seem to be two types of issues with this kind of bounce method, and every tutorial I checked uses the same method. Even though these issues happen rarely in the game, I created the exact moment they happen, you can see both issues in the video. https://streamable.com/g6fj4u
- Sometimes, the objects do not recognize the collision between each other, and even if they do, they bounce in the wrong direction.
- When colliding with the corner, object loses momentum and moves alongside one of the edges
This is the code I am using;
private void Awake()
{
_transform = transform;
_rigidBody2D = GetComponent<Rigidbody2D>();
_rigidBody2D.velocity = _moveDirection * _speed;
}
private void FixedUpdate()
{
_previousVelocity = _rigidBody2D.velocity;
}
private void OnCollisionEnter2D(Collision2D collision)
{
Vector2 normal = collision.GetContact(0).normal;
Vector2 reflection = Vector2.Reflect(_previousVelocity, normal).normalized;
_rigidBody2D.velocity = reflection * _speed;
}
_previousVelocity
after each collision. So if a ball has a double collision in a single physics tick (like colliding quickly with two walls as it strikes an inside corner) the first collision is semi-forgotten and the second reflects velocity as though the first didn't happen. \$\endgroup\$