- Home /
Need to flatten a Vector3
I have some code that is meant to move the object in the direction the camera is facing, but only along a flat plane. In other words if the camera is pointed North, but slightly down, I want to go North, but not down. If the camera is pointed East, I want to go East, but not down etc.
Here is the code I have am using now:
transform.position += new Vector3(cameraTransform.forward.x, 0, cameraTransform.forward.z) * Input.GetAxis("LeftStickVertical") * speed * Time.deltaTime;
It works fine until the camera is at a very high angle (close to looking straight down): I am pretty sure think this is because at this angle 'cameraTransform.forward.z' approaches zero.
So how do I build a vector for the current direction the camera is pointing, ignoring up and down. I guess another way to ask this is "how do I move the object in the same direction the camera is pointing, Y axis only?"
Answer by robertbu · Jul 31, 2013 at 12:37 AM
If you are pointed straight down, then there is no direction, but you can solve any problems other than straight down like this:
Vector3 v3 = cameraTransform.forward;
v3.y = 0;
v3.Normalize();
if (v3 != Vector3.zero) {
transform.position += v3 * Input.GetAxis("LeftStickVertical") * speed * Time.deltaTime;
}
With your code, the new flattened Vector3 was getting very short when the angle is steep, because the major component that was contributing to the unit one length of the orginal forward vector was removed. By normalizing the vector, you have a vector of constant unit one length for your movement.
Answer by monotoan · Jan 29, 2018 at 10:08 PM
Updated answer to reflect current scripting API:
Unity's "Vector3" has a built in function that can flatten any vector onto any plane. You pass in the vector you want to flatten as the first parameter, and the normal of the plane you want to flatten it onto as the second -- the normal of a plane being the normalized vector that points straight up from the plane's surface.
The normal of the Horizontal (XZ) plane in world space is Vector3.up. So, to flatten a vector on to this plane, you would do this:
Vector3 flattenedVector = Vector3.ProjectOnPlane(vectorToFlatten, Vector3.up);
Or, if you wanted to project a vector onto, say, a vertical wall aligned to the world XY plane:
Vector3 flattenedVector = Vector3.ProjectOnPlane(vectorToFlatten, Vector3.forward);
This does not solve the original problem since if the camera's forward vector is passed as the vectorToFlatten, you will get varying lengths for the flattenedVector based on the pitch of the camera. The vector still needs to be normalized. This would fix it: Vector3.ProjectOnPlane(vectorToFlatten, Vector3.up).normalized
but then it would be the same as the originally accepted answer.
Right, normalization is still necessary. Though if you only need the x-z-plane the usage of PorjectOnPlane is actually overkill because the result would be the same as if you just set the y component to 0.