1

So I'm having this problem where I am trying to make bullets ricochet off obstacles in Unity. Currently I am using Vector3.Reflect to set Vector3.Forward of my object.

Expected Result vs. Actual Result

My expected result would be that the bullet follows the red lines. Each of the objects it is bouncing off are rotated by 45 degrees so the bullet should follow a perfect 90 degree bounce. But what is actually happening is on the second bounce the bullet follows the blue line and from the point gets stuck in the corner.

public int bulletSpeed;
Rigidbody bulletRigidBody;

void Start()
{
    //Get bullet rigidbody
    if (bulletRigidBody == null)
    {
        bulletRigidBody = GetComponent<Rigidbody>();
    }

    bulletRigidBody.velocity = transform.forward * bulletSpeed;
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.tag == "Wall")
    {
        //change forward vector based on reflection against object
        transform.forward = Vector3.Reflect(collision.contacts[0].point, collision.contacts[0].normal);

        //add velocity to bullet based on new forward vector
        bulletRigidBody.velocity = transform.forward * bulletSpeed;
    }

}

Code example

Im assuming my problem is either something to do with returning the incorrect normal or because I am setting the Forward vector instead of rotating but I am unsure of how to convert Vector3.Reflect into something a Quaternion can understand

1 Answers1

2

I found the solution. I have been working on this problem for 2 days but as soon as I post the question I figure it out

private void OnCollisionEnter(Collision collision)
{
    //if (collision.collider.tag == "Wall")

        //Store new direction
        Vector3 newDirection = Vector3.Reflect(transform.forward, collision.contacts[0].normal);
        //Rotate bullet to new direction
        transform.rotation = Quaternion.LookRotation(newDirection);

        //add velocity to bullet based on new forward vector
        bulletRigidBody.velocity = transform.forward * bulletSpeed;


}