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!