How to limit only one axis rotation? c#

I’m trying to limit object rotation. I don’t want to affect x and y rotation. Only to z-axis rotation.

This code limits z-axis rotation to 30 degrees but it affects to x and y.

using UnityEngine;
using System.Collections;

public class LimitRotation : MonoBehaviour
{
    float z;
    float x;
    float y;

    void Start()
    {
        z = transform.eulerAngles.z;
        x = transform.eulerAngles.x;
        y = transform.eulerAngles.y;
    }

    void Update()
    {
        z -= Input.GetAxis("Horizontal") * 30 * Time.deltaTime;
        z = Mathf.Clamp(z, -30, 30);
        transform.rotation = Quaternion.Euler(x, y, z);
    }
}

How i should edit this code?

  • Setting the euler to 0 in the update
    function (every frame), the object will
    appear to not rotate and will stay locked
    at the “rotation” value of 0.
  • Setting the euler to the transforms
    euler angle every frame simply says
    “do what you were doing”. We want it
    to “do what it was doing” except we
    want to change 1 specific value, the
    z axis.

In your original code you were setting xyz to the transforms eulers in the START function. This says… on start (which is only called once) the xyz values are equal to whatever they were set to at the start of play mode. I am guessing it was at 0,0,0. So now…x = 0, y = 0, z = 0. By setting the xyz in the update now… you were saying transform.eulerAngles.x = 0, transform.eulerAngles.y = 0, transform.eulerAngles.z = 0

By setting the euler angles to what they currently are in the update function, it “frees up” those values to be able to change… freely.

TLDR : update the direct values of any euler you dont want to change, you cant store the value in start and reference it later because it will be changing. Move the x/y/z from start to update

I’m trying to limit object rotation. I don’t want to affect x and y rotation. Only to z-axis rotation.

void Update()
{
    float h = Input.GetAxis("Horizontal") * 30 * Time.deltaTime;
    z = transform.eulerAngles.z;
    x = transform.eulerAngles.x;
    y = transform.eulerAngles.y;
    Vector3 desiredRot = new Vector3(x, y, z + h);
    if (desiredRot.z > 30)
    {
        desiredRot = new Vector3(x, y, 30);
    }
    else if (desiredRot.z < -30)
    {
        desiredRot = new Vector3(x, y, -30);
    }

    transform.rotation = Quaternion.Euler(desiredRot);
}