- Home /
Clamping LookRotation.
I can't figure out how to clamp the rotation of my gun whilst it looks at the direction of the mouse.
Its just a gun on the hand of a character that rotates to the direction of a ray which is pointing to mouse position.
I want to clamp the maximum amount it rotates on the x and y in front of the player by about 180 degrees max.
I tried everything lol, can't do it. Please help.
// ray aim direction.
Vector3 aimDir = aimray.direction;
gun.rotation = Quaternion.LookRotation(aimDir);
I don't understand - the camera viewport is typically about 60 degrees, so if your gun is pointing where the mouse is, how can it turn more than 180 degrees?
Oh crap I forgot to mention its a 3rd person game. I need it to stop going through the player when I'm looking around ai$$anonymous$$g from the hip. Only turn 180 max.
Answer by Julien-Lynge · Nov 29, 2013 at 06:33 PM
Just FYI: there isn't a 'right' way to do this. It's all math, and there are many ways to 'clamp' a value within a range, so this is just one method that would work.
Get the quaternion representing the player's orientation.
Then get the quaternion representing where the gun should be pointing (using LookRotation).
Call http://docs.unity3d.com/Documentation/ScriptReference/Quaternion.Angle.html to get the angle between 'character forward' and 'gun target'.
If this is greater than 180 degrees, use Slerp to clamp your angle. Pass to Slerp '180 / [angle]' as the last parameter, which is the fraction between the character's forward rotation and the target rotation where 180 degrees falls.
The result of this Slerp will be the rotation you want.
Ok I think I almost have it, last part with passing to slerp confused me.
It looks around and there are no errors at leas, but doesn't clamp So in code:
playerRotation = player.rotaion;
Quaternion gunRotation = Quaternion.LookRotation(ray.direction);
float gunRotAngle = Quaternion.Angle(playerRot, gunRotation);
if(gunRotAngle > 180){
gun.rotation = Quaternion.Slerp(playerRotation, gunRotation, 1.0f);
// A bit lost at using the slerp to clamp the angle.
}
Ok got it:
// What I really wanted was a 90 degree clamp not a 180.
if(gunRotAngle > 90)
It works thanks.