I’m currently coding a first person camera for my FPS project, and I’m trying to get the camera to clamp its rotation at about 100/-100 degrees on the y axis, to prevent the player model’s head from being able to spin endlessly. I thought I had it down initially, until I realized I had clamped the rotation relative to the world’s axis, not locally. I’ve tried a few ideas and tutorial, none seeming to work. Here is my current code, any help is appreciated!
The lines being out of order is just me being unorganized, I do plan on cleaning it up when I get everything working.
Everything works well when I run, until I rotate my character. Since the clamping parameters aren’t local, when I rotate the character 90° on y, the camera can only look left, and can turn 180 relative to the character. I’d like to clamp the camera locally so I can rotate the character, and the camera clamps relative to the players transform, not the world.
Line 12 places the camera at the coordinates of an object that I parented to my character’s head bone, so I can have the camera follow the objects position, without it following the heads rotation, as parenting the two would do. It also allows me to offset the object from the head, so the camera isn’t so low.
I know I am late but what you need to do is move the goal posts by the parent’s rotation to the the clamping parameters, which would be something like xRotation = Mathf.Clamp(xRotation, -90f + X, 90f + X);, which partially solves the problem. The next thing you need to do before it is do is: if (X > 180) X -= 360; if (Y > 180) Y -= 360;
so it will look something like this:
float X = this.transform.parent.rotation.x;
float Y = this.transform.parent.rotation.y;
if (X > 180) X -= 360;
if (Y > 180) Y -= 360;
xRotation = Mathf.Clamp(xRotation, -90f + X, 90f + X);
yRotation = Mathf.Clamp(yRotation, -90f + Y, 90f + Y);
And that’s specifically clamping. You can also edit the parents part for how many parents that you have
Nope, that’s wrong. rotation is a quaternion and the x and y components are not angles. Also you should not read back eulerAngles from the object as eulerAngles only work together when you consider all 3 values. Just looking at one or modifying one or two can result in completely wrong orientations as eulerAngles can flip at unexpected times.
TBH I don’t quite get the original question. It seems to be about restricting the head rotation which of course would be a child of the player. However how any when is the player rotated in the first place? Since “yRotation” is used as a local rotation it should work just fine as the localRotation is relative to the players body. So it’s not really clear what the issue was. This was already pointed out by Stevens a year ago.
Without knowing the actual hierarchy setup we can’t really reason about the code. The code on its own just applies a local rotation so it should work fine as long as the object that is rotated here is a child of some other object.