Friday, January 26, 2018

unity - 2D bouncing formula doesn't work properly


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 ?





No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...