I'm making a fps controller, and I'm trying to clamp my cameras x rotation. Here's my code so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] Camera cam;
[SerializeField] float camSpeed;
[SerializeField] float walkSpeed;
[SerializeField] float jumpSpeed;
float yaw;
float camPitch;
Vector3 direction;
Vector3 worldDirection;
Rigidbody myrigbody;
void Start()
{
myrigbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
camPitch = -Input.GetAxis("Mouse Y") * camSpeed;
cam.transform.Rotate(new Vector3(camPitch, 0, 0));
yaw = (yaw + Input.GetAxis("Mouse X") * camSpeed) % 360f;
direction = new Vector3(Input.GetAxis("Horizontal") * walkSpeed, myrigbody.velocity.y, Input.GetAxis("Vertical") * walkSpeed);
worldDirection = transform.TransformVector(direction);
if(Input.GetKeyDown(KeyCode.Space))
{
myrigbody.AddForce(new Vector3(0, jumpSpeed, 0), ForceMode.Impulse);
}
}
private void FixedUpdate()
{
myrigbody.MoveRotation(Quaternion.Euler(0, yaw, 0));
myrigbody.velocity = worldDirection;
}
}
I know that I want to clamp my cameras X rotation within a range of -89 to 89, but no matter what I try I can't figure out how to clamp the rotation while using cam.transform.Rotate(). I don't think I can clamp camPitch, because it is reset every frame, and I can't figure out a way to directly clamp the cameras rotation. The cameras rotation is not resetting, so if I could somehow clamp it it would work. Is this possible, or do I need to try a different method? How do i get this to clamp correctly?
transform.Rotate()
, which is what you're using. The axes are different but the approach used in the solution is equally applicable to your question. – Kevin Apr 30 '21 at 04:39