1
votes

I have the basic movement and rotation working however I can not work out a way to limit the rotation up and down. I want to make it so that you cant look more than 90° up and down.

Ive tried multiple ways such as using if statments and using clamp.

using UnityEngine;

public class FPSController : MonoBehaviour {

public float speed = 5f;
public float sensitivity = 2f;
public GameObject Camera;

CharacterController controller;

float moveFB;
float moveLR;

public float rotX;
public float rotY;



void Start()
{
    controller = GetComponent<CharacterController>();
    Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void FixedUpdate ()
{
    moveFB = Input.GetAxis("Vertical");
    moveLR = Input.GetAxis("Horizontal");

    rotX = Input.GetAxis("Mouse X") * sensitivity;
    rotY = Input.GetAxis("Mouse Y") * sensitivity;


    transform.Rotate(0, rotX, 0);
    Vector3 movement = new Vector3(moveLR * speed * Time.deltaTime, 0, moveFB * speed * Time.deltaTime);
    controller.Move(transform.rotation * movement);
    Camera.transform.Rotate(-rotY, 0, 0);

}

}

With this code you will be able to rotate the camera beyond 90 degrees causing it to be upside down etc

2

2 Answers

0
votes

"Camera" is a built-in unity class, I would recommend renaming it to "camera". Try this to clamp the camera's rotation:
(with your other public floats)

public float minAngle = -90;
public float maxAngle = 90;

(at the end of FixedUpdate)

Vector3 temp = camera.transform.localEulerAngles;
camera.transform.localEulerAngles = new Vector3(Mathf.Clamp(Mathf.DeltaAngle(0, temp.x), minAngle, maxAngle), temp.y, temp.z);

Edit: changed eulerAngles to localEulerAngles
Edit 2: changed the order of the arguements of Mathf.DeltaAngle

0
votes

I fixed it here. Not to sure on how it works but it works. Credit to video:https://www.youtube.com/watch?v=F5eE1YL1ZJY

using UnityEngine;

public class FPSController : MonoBehaviour {

public float speed = 5f;
public float sensitivity = 2f;
public GameObject Camera;

CharacterController controller;

float moveFB;
float moveLR;

public float rotX;
public float rotY;

public float minAngle = -90f;
public float maxAngle = 90f;





void Start()
{
    controller = GetComponent<CharacterController>();
    Cursor.lockState = CursorLockMode.Locked;
}
// Update is called once per frame
void FixedUpdate ()
{
    moveFB = Input.GetAxis("Vertical");
    moveLR = Input.GetAxis("Horizontal");

    rotX = Input.GetAxis("Mouse X") * sensitivity;
    rotY -= Input.GetAxis("Mouse Y") * sensitivity;
    rotY = Mathf.Clamp(rotY, minAngle, maxAngle);


    transform.Rotate(0, rotX, 0);
    Vector3 movement = new Vector3(moveLR * speed * Time.deltaTime, 0, moveFB * speed * Time.deltaTime);
    controller.Move(transform.rotation * movement);
    Camera.transform.localRotation = Quaternion.Euler(rotY, 0, 0);



}

}