# Collision issues with Vector2.Reflect

I am working on a game where I can launch a ball and when it hits an object it can bounce off without being random, but when I tried to do it I ran into an issues where I was getting weird collision feedback:
watch this video and see what I’m talking about: https://1drv.ms/v/s!Ai7u0bw9Rsr-hukdwxJ_MwJ6MaIdLA

public float bulletSpeed;
public Rigidbody2D rb2d;

`````` void Start()
{
rb2d = rb2d.GetComponent<Rigidbody2D>();
rb2d.velocity = transform.up * bulletSpeed;
rb2d.fixedAngle = true;
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.transform.CompareTag("Wall"))
{
CollisionWithWall(other);
}
else if (other.transform.CompareTag("Destroy"))
{
Destroy(gameObject);
}
else if (other.transform.CompareTag("Target"))
{
Debug.Log("Hit: " + other.gameObject.tag);
}
}

void CollisionWithWall(Collision2D other)
{
//For Reflecting The Bullet
Vector3 reflectedPosition = Vector3.Reflect(transform.right, other.contacts[0].normal);
rb2d.velocity = (reflectedPosition).normalized * bulletSpeed;
//For Rotate The Bullet Towards its velocity
Vector3 dir = rb2d.velocity;
float angle = 90 - Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
rb2d.MoveRotation(angle);
//transform.eulerAngles = new Vector3(0, 0, angle);
}
``````

Why do you reflect the local right direction? Shouldn’t you reflect your velocity vector? Your custom rotation code seems to mess things up. If you just look at the orientation of your ball / circle the rectangle is perpendicular to the movement direction. However after the first bounce it’s rotated kind of arbitrarily. Therefore your velocity and your right vector do not point in the same direction.

edit

The original approach i had of course didn’t work as we can’t use the current velocity of the rigidbody inside OnCollisionEnter2D since it got already changed due to the collision. You need to know the velocity / movement direction before the collision. For this there are two possible solutions.

First you can simply store the last velocity vector in a variable inside the FixedUpdate callback. That way we know the last velocity and we can reflect it correctly:

``````Vector2 lastVelocity;
private void FixedUpdate()
{
lastVelocity = rb2d.velocity;
}

void CollisionWithWall(Collision2D other)
{
rb2d.velocity = Vector3.Reflect(lastVelocity, other.contacts[0].normal);
}
``````

If you want to rotate the object’s right direction into the movement direction and you want to move the bullet always at the same speed you could do what you originally did. However you have to ensure the rigidbody doesn’t rotate on it’s own. So you have to freeze the rotation otherwise our direction would mess up on collisions.

``````void CollisionWithWall(Collision2D other)
{
transform.right = Vector3.Reflect(transform.right, other.contacts[0].normal);
rb2d.velocity = transform.right * bulletSpeed;
}
``````