Kaz
Kaz

Reputation: 147

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.

Upvotes: 8

Views: 20493

Answers (2)

Lincoln Cheng
Lincoln Cheng

Reputation: 2303

enter image description here

Vector2 Reflect(Vector2 inDirection, Vector2 inNormal):

inDirection: black arrow

inNormal: red arrow

return output: green arrow

Upvotes: 22

Benjamin James Drury
Benjamin James Drury

Reputation: 2383

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.

Upvotes: 10

Related Questions