7

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.

Kaz
  • 137
  • 2
  • 3
  • 17

2 Answers2

19

enter image description here

Vector2 Reflect(Vector2 inDirection, Vector2 inNormal):

inDirection: black arrow

inNormal: red arrow

return output: green arrow

Lincoln Cheng
  • 2,263
  • 1
  • 11
  • 17
  • Isn't this more of a bounce (of invisible wall defined by normal) than a reflect (around the norm vector)? A true vector reflection would be like in the image but with black arrow reversed – Spider Sep 03 '21 at 01:16
  • @Spider In the diagram, you want to reflect the vector off the blue vertical line, as if the blue line was a mirror. The diagram is correct. – shieldgenerator7 Nov 24 '21 at 10:01
  • @shieldgenerator7, I see there is always this perspective thought shift, when I look at the normal as the actual mirror – Spider Nov 26 '21 at 23:56
10

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.

Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27
  • Looks like inNormal must *really* be a unit vector, or your result will be messed up, as Unity would apply a raw formula without normalizing it for performance. – hsandt Feb 28 '19 at 00:12
  • @hsandt That's what I was wondering too. So far my tests have shown that the `ContactPoint2D.normal` is always a unit vector – shieldgenerator7 Nov 24 '21 at 10:08