I am trying to find out how to take the vector of the movement of a player and use the normal of a wall they hit (or will hit), and do the math to move them where they should move based on the wall collider.
Heres a nifty image I just made. Lets say we have a vector3 named “playerMovement” and they player is about to hit the wall and the RaycastHit is named “hitInfo”
I do not know the math I need to do to get the orange vector. Please help!
If you’re using a Rigidbody with forces, or a CharacterController with movement, these objects will automatically handle this sort of movement for you. I would definitely take a look at these two components as they will most likely fit the bill of what you need.
However, if you really want to do it with straight math, you can use the math found here.
That’s pretty simply. Usually you would simply project the velocity onto the normal vector of the wall. That gives you the amount of the velocity along the normal vector. When you subtract that resulting vector from the original vector you’ll end up with only the left over part of the velocity which is parallel to the wall.
However the latest Unity version has a new method which does this already for you: Vector3.ProjectOnPlane.
If you’re interested in how those methods actually work, here’s their implementation:
In order to find the vector that is parallel to the wall and perpendicular to the normal of the wall you’ll want to use the cross product. The cross product takes two vectors and returns a third so in this case you want to cross the “up=up out of the plane of your image)” direction (probably ‘y’ in your scene) with the normal to the wall.