Question by
cmcmains · Mar 17, 2017 at 07:56 PM ·
camerarotationmathmathf.clamp
How can I use Mathf.Clamp?
I've got a basic movement script going but I can't figure out how to use Mathf.Clamp so that the player can't do flips with the camera.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent (typeof(CharacterController))]
public class PlayerMove : MonoBehaviour {
public float playerSpeed = 2f;
public float mouseSens = 5f;
[SerializeField]
private CharacterController controller;
[SerializeField]
private Camera cam;
private float moveVertical;
private float moveHorizontal;
private float rotationY;
private float rotationX;
private float maxCameraRotation = 10f;
void Start ()
{
controller = GetComponent <CharacterController> ();
}
void Update ()
{
moveVertical = Input.GetAxis ("Vertical") * playerSpeed;
moveHorizontal = Input.GetAxis ("Horizontal") * playerSpeed;
rotationY = Input.GetAxis ("Mouse X") * mouseSens;
rotationX = Input.GetAxis ("Mouse Y") * mouseSens;
Vector3 movement = new Vector3 (moveHorizontal, 0f, moveVertical);
transform.Rotate (0f, rotationY, 0f);
cam.transform.Rotate (-Mathf.Clamp (rotationX, -maxCameraRotation, maxCameraRotation), 0f, 0f);
movement = transform.rotation * movement;
controller.Move (movement * Time.deltaTime);
}
}
That's the whole script, including my current attempt. Help would be appreciated!
Comment
Answer by Namey5 · Mar 18, 2017 at 01:54 AM
In this case, don't use transform.Rotate. The value used in this function is simply the direction in which to turn the object, so clamping that simply limits how fast the object can turn. Instead, you have to do the x rotation manually.
float rotationX = 0.0f;
void Update ()
{
rotationX += mouseSens * Input.GetAxis ("Mouse Y") * Time.deltaTime;
rotationX = Mathf.Clamp (rotationX, -maxCameraRotation, maxCameraRotation);
cam.transform.eulerAngles = new Vector3(rotationX, transform.eulerAngles.y, transform.eulerAngles.z);
}
It's saying that I can't modify that value type when I do what you've shown. Any ideas?
Sorry, I wrote the last line wrong. Forgot that rotations in Unity are Quaternions, not Eulers. Answer has been edited.