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));