Vector Math (162196)

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! :slight_smile:

Thanks!
–Michael

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.

In Unity it would look like this:

Vector3 desiredMotion = playerVelocity -
    (wallNormal * (Vector3.Dot(playerVelocity, wallNormal)));

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:

public static Vector3 ProjectOnPlane(Vector3 vector, Vector3 planeNormal)
{
	return vector - Vector3.Project(vector, planeNormal);
}

public static Vector3 Project(Vector3 vector, Vector3 onNormal)
{
	float num = Vector3.Dot(onNormal, onNormal);
	if (num < Mathf.Epsilon)
	{
		return Vector3.zero;
	}
	return onNormal * Vector3.Dot(vector, onNormal) / num;
}

public static float Dot(Vector3 lhs, Vector3 rhs)
{
	return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;
}

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.

Something like

parallelToWall = Vector3.Cross(upVector, wallNormal)

You can normalize and scale the result vector to whatever you like.