Projectile Ricochet Issue. Travels along the surface rather than reflecting off of it

I have projectiles that are supposed to ricochet (bounce or reflect off surfaces it hits). It works pretty well, but for some reason sometimes it just doesn’t work and instead of bouncing off of the surface the projectile begins to travel parallel to it.

I tried to fix this by having a variable store the projectile’s velocity at the end of update(). I thought that maybe the issue was that it was registering the collision and changing its direction before the reflection in OnCollisionEnter2D() could be made. It may have been my imagination, but this did seem to help make it less frequent, but the issue still happens.
Either way the issue still happens and I can’t figure out what is causing it.

Here is the code having to do with the ricochet.

private void Update()
{
  if (!_directionSet)
  {
    //calculates the direction the target is from projectile
    _targetDirection = (_targetLocation - _rb.position).normalized;
    
    _directionSet = true;
  }
  _rb.velocity = _targetDirection * _speed;

  //Other stuff that is not relevant to the problem

  _previousVelocity = _rb.velocity;
}

private void OnCollisionEnter2D(Collision2D collision)
{
  if (type == Type.Bounce)
  {
     //gets the normal of the surface the projectile collided with
     Vector2 _surfaceNormal = collision.GetContact(0).normal;

     //calculate the direction of reflection off of the surface
     _targetDirection = Vector2.Reflect(_previousVelocity, _surfaceNormal).normalized;

     _rb.velocity = _targetDirection * _speed;
  }
}

If anyone has any idea about what the problem could be or how to fix it I would really appreciate the help.

Thanks!

Hi @kylecat6330,

did you create physical material with some awesome bouncines value and atached it to projectile? Maybe it will help, did used it in some multiplayer tank project and helped a lot.


The Physic Material is used to adjust
friction and bouncing effects of
colliding objects.

To create a Physic Material select
Assets > Create > Physic Material from
the menu bar. Then drag the Physic
Material from the Project View onto a
Collider in the scene.


Ofcourse Stone is not the best… but add some bounciness and bullets will act like with rubber warheads… hope will do.
191829-20220127-232140.png

Solved it by storing the intended direction of the projectile in _previous Velocity rather than using the projectile’s velocity at the end of update.