-1
\$\begingroup\$

I am new to Unity, and I am trying to create a bouncing ball, so I've been researching bouncing related physics and I found a formula:

Formula:

-2*(V dot N)*N + V

Where V is the velocity vector and N is the normal of the surface on which the ball will bounce

Here is my script :

using UnityEngine;

using System.Collections;

public class BallPhysics : MonoBehaviour {



    void Start () {
        rigidbody2D.velocity =new Vector2 (-1,-3);

    }

    // Update is called once per frame
    void Update () {

    }
    void OnTriggerEnter2D(Collider2D col) {

        if (col.gameObject.name == "Pong") {
            tBounce ();
                }


    }

    void tBounce(){
        RaycastHit2D hit = Physics2D.Raycast (new Vector2 (transform.position.x,transform.position.y), rigidbody2D.velocity);
        Vector2 n = hit.normal;
        Vector2 v = rigidbody2D.velocity;
        Vector2 R = -2 * (Vector2.Dot (v, n)) * n + v;
        rigidbody2D.velocity = R;
    }
}

I am giving the ball a velocity vector in the start function, i am using OnTriggerEnter2D for collision handling and raycast2D to get the normal of a surface.

The problem is that the script doesn't reflect the velocity vector called R, I think the problem is in the normal vector.

For example let's say V is a Vector2(-1,-1) so basically R should be (-1,1), but it's not. R is (3,1) !

I've successfully been able to make a ball bouncing on Horizontal/vertical surface by reversing the ball velocity but this won't work properly with arbitrary angles, that's why I am using this formula. So what's the problem ?

\$\endgroup\$
0
\$\begingroup\$

normalize your normal vector n before using in in the reflect formula.

Vector2 n = hit.normal;
n.Normalize();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.