Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - how to use Vector2.Reflect()

I have looked everywhere including the Unity documentation but cannot seem to find any good examples of how to use Unity's Vector2.Reflect() function. I am trying to use this to control the direction of the ball (in a 2D Breakout game) when it hits a wall. It takes 2 arguments (inDirection, inNormal) but I cannot seem to figure out how to use this. Any help would be appreciated.

like image 472
Kaz Avatar asked Dec 13 '16 20:12

Kaz


People also ask

What is the difference between Vector2 and Vector3?

The magnitude of a Vector2 equals sqrt(x^2+y^2) . A Vector3 has a 3D direction, like a xyz point in a 3D space, or a color in RGB format, or a set of three numbers. e.g. (0,0,0) or (-0.1, 3.14, 30). The magnitude of a Vector3 equals sqrt(x^2+y^2+z^2) .

What is Vector2 C#?

Min(Vector2, Vector2) Returns a vector whose elements are the minimum of each of the pairs of elements in two specified vectors. Multiply(Single, Vector2) Multiplies a scalar value by a specified vector. Multiply(Vector2, Single)


2 Answers

enter image description here

Vector2 Reflect(Vector2 inDirection, Vector2 inNormal):

inDirection: black arrow

inNormal: red arrow

return output: green arrow

like image 134
Lincoln Cheng Avatar answered Sep 20 '22 12:09

Lincoln Cheng


The inDirection should be the velocity of your ball and the inNormal should be the unit vector that is perpendicular to your wall.

Try putting this in your ball object:

void OnCollisionEnter(Collision collision)
{
    Vector2D inDirection = GetComponent<RigidBody2D>().velocity;
    Vector2D inNormal = collision.contacts[0].normal;
    Vector2D newVelocity = Vector2D.Reflect(inDirection, inNormal);
}

NOTE: I cannot currently test that code, so it may need tweaking in terms of the names of things.

like image 25
Benjamin James Drury Avatar answered Sep 19 '22 12:09

Benjamin James Drury