Home > Back-end >  Unity Clamping Rotation that is controlled by WASD
Unity Clamping Rotation that is controlled by WASD

Time:11-25

I want to clamp the rotation, the rotation is controlled by the WASD keys.

How can i do this? I tried many things but it just doesn't work.

    float vertical = Input.GetAxis("Vertical");
    float horizontal = Input.GetAxis("Horizontal");

    transform.Rotate(vertical / 4, horizontal / 4, 0.0f);

CodePudding user response:

What you will want to do is store the absolute values like e.g.

// Adjust these via Inspector
public float minPitch = -45;
public float maxPitch = 45;
public float minYaw = -90;
public float maxYaw = 90;
public Vector2 sensitivity = Vector2.one * 0.25f;

private float pitch;
private float yaw;
private Quaternion originalRotation;

private void Awake ()
{
    originalRotation = transform.rotation;
}

void Update ()
{
    pitch  = Input.GetAxis("Vertical") * sensitivity.x;
    yaw  = Input.GetAxis("Horizontal") * sensitivity.y;

    pitch = Mathf.Clamp(pitch, minPitch, maxPitch);
    yaw = Mathf.Clamp(yaw, minYaw, maxYaw);

    transform.rotation = originalRotation * Quaternion.Euler(pitch, yaw, 0);
}

CodePudding user response:

Use Math.Clamp()

float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
float minClamp = -5.0f;
float maxClamp = 5.0f;

transform.Rotate(Math.Clamp(vertical / 4, minClamp, maxClamp),
                 Math.Clamp(horizontal / 4, minClamp, maxClamp));

https://docs.microsoft.com/en-us/dotnet/api/system.math.clamp?view=net-6.0#System_Math_Clamp_System_Single_System_Single_System_Single_

  • Related