Basically, I’m working on a player controller using the CharacterController node as a base. With CharacterController, you have an UpDirection used for various things, but I also want a “Right direction” variable that I can use to apply acceleration, and other stuff. Of course, the Right direction is the Vector which is perpendicular to the UpDirection.
So in order to get it, I’m just rotating the UpDirection by 90 degrees, like this:
public Vector3 RightDirection => UpDirection.Rotated(Vector3.Forward, Mathf.Pi/2);
This mostly works, but the resulting Vector is just ever so slightly imprecise (maybe because of a floating point error? idk). It probably won’t have any effect on gameplay whatsoever, but it still annoys me, so I would like a way to get the perpendicular vector more precisely
The canonical UP, RIGHT and FORWARD vectors in Vector3 are all perpendicular.
I’m guessing your UpDirection is not the canonical (0.0, 1.0, 0.0) up vector, but rather your own. If it’s not perfectly vertical, rotating half PI around the canonical forward vector isn’t going to give you a perpendicular vector. It’ll be perpendicular in the plane of the rotation, but not perpendicular in the third dimension.
The typical solution for this is to take the cross product of the up vector and the right vector; that will get you a forward vector that’s perpendicular to your up and right, as long as they’re not actually parallel. You can then use that forward vector as your axis of rotation, to rotate the up vector by half pi.
rot_axis = your_up.cross(Vector3.RIGHT)
rightvec = your_up.rotated(rot_axis, PI * 0.5)
The UpDirection will most times be (0, 1, 0), but sometimes I need to change it. Altough I am using the 3d character controller, the game actually plays in 2 dimensions, so using Vector3.Forward as the axis should be fine. Your code seems to give the same result as mine. I guess it might really just be a floating point error without a perfect solution. But before doing this, I actually used GlobalBasis.X as the RightDirection, and I just rotated the characterbody based on the UpDirection (I changed this because I wanted the movement to be indipendent from the rotation), and that was pretty precise, so maybe there’s a way.
Floating point error is definitely a thing, though it should be pretty small. What kind of numbers are you getting, compared to what you expect?
If you really want to have something precise and you know your up vector and right vector are close to the canonical directions, you could just do something like: