How to limit the rotation of a tank barrel in c#

i have created a tank and i want to limit the its barrel’s rotation on the x axis between 6 and -16

If your code is:

 float angle;

Then your limit is:

 if (angle > 6) angle = 6;
 if (angle < -16) angle = -16;

And you would use Quaternion.Euler() to set the rotation of your barrel![/code]

I had to do this in a jam earlier last week, i’ll hook you up with my solution when I get home, as long as I remember…

I split the rotators in to two pivots (one control horizontal, one vertical), don’t remember why, but if I undid that I’d prolly remember why. You need to assign y and x vectors (I had them as 1,0,0 xVector, 0,1,0 yVector). Reason for this was I had made some weird decisions in the hierarchy which ended up in different axes controlling the others, so it’s easy to control them that way.

    void LockedRotation()
    {

        CalcRotations();
        torsoObjectY.transform.localEulerAngles = yVector * rotationY;
        torsoObjectX.transform.localEulerAngles = xVector * rotationX;
    }

    void CalcRotations()
    {
        rotationX += horizontalInput * twistSpeed * Time.deltaTime;
        rotationX = Mathf.Clamp(rotationX, -xLimit, xLimit);

        rotationY += verticalInput * twistSpeed * Time.deltaTime;
        rotationY = Mathf.Clamp(rotationY, -yLimit, yLimit);
    }

And as misleading as my stuff always is, notice that CalcRotations actually does the clamping/locking :face_with_spiral_eyes:

This is definitely the way to go. Keep each angle separately, traverse and elevation/depression, and control each angle as a single float, then use Quaternion.Euler() to turn it into the desired localRotation.