- Home /
How to clamp the rotation of this?
This is part of a code for a turret with a barrel. It works almost perfect but the thing I am missing is the clamping of the barrels rotation up and down. There is a sort of clamp as can be seen by the if statement that checks weather the turret is facing a certain angle so the barrel only starts moving when facing within a certain area of where you are looking but that clamps all angles equally. Making it smaller clamps the vertical same as horizontal.
So what I need really is another clamp for rotations of the barrel itself. How can I do that?
Code:
//Aimtarget is a raycast hit from the camera, the barrel follows it so long as the aimAngle is smaller than 50.
//What I need to clamp is the barrel.rotation on x z and y. I tried all kinds of things like clamping the bRot.x = 0.0f but that just screws everything up.
aimTDir = transform.InverseTransformPoint(aimTarget.position);
aimBAngle = Vector3.Angle(aimTDir, -transform.forward);
if(aimBAngle < 50.0f){
Quaternion bRot = Quaternion.LookRotation(aimHitPoint - barrel.position);
barrel.rotation = Quaternion.Slerp(barrel.rotation, bRot, Time.deltaTime * 5.0f);
}
// yeah, please help me clamp this barrel. Thanks.
PS: Quaternions really get me dumbstruck, so sorry for noobyness.
When I read this line:
//What I need to clamp is the barrel.rotation on x z and y. I tried all kinds of things like clamping the bRot.x = 0.0f but that just screws everything up.
I think your problem might be that you are trying to clamp the wrong value. Quaternions x,y,z (and w) values do not represent the values you see in the inspector. The docs explain them as:
They are based on complex numbers and are not easy to understand intuitively
And the x,y,z and w have this comment next to them ;)
Don't modify this directly unless you know quaternions inside out.
Ins$$anonymous$$d you should get the eulerAngles, clamp it, and then convert it back to a Quaternion using Quaternion.Euler.
Something like this:
Quaternion unclampedRotation; // set this to your value
Vector3 euler = unclampedRotation.eulerAngles;
euler.x = $$anonymous$$athf.Clamp(euler.x,$$anonymous$$Value,maxValue);
Quaternion clampedRotation = Quaternion.Euler(euler);
(I wrote this without a editor, so it might contain silly syntax erors, but it should give you an idea)
If this was indeed the problem, please reply so that I can write this up as an answer ins$$anonymous$$d of a comment)
Well I think my problem is mainly co$$anonymous$$g from the way I have everything set up. I have to use another method for the barrel.
Nothing is working so far.
Your answer
Follow this Question
Related Questions
Get slerp to work just as LookAt(,Vector3.right) does 1 Answer
Have An Object Rotate Around Transform A So That Transform B is Looking at Transform C (C#) 0 Answers
Rotation - Simple Question 0 Answers
How to make an enemy look at you and follow you 0 Answers
Look at like rotating around y axis 1 Answer