I'm a coding noob getting into Unity & C#, and I copied the following code from a tutorial online to get an FPS character and camera up and running:
The controls work great, except it needs something called "camera clamping" added to it so that I can't rotate the camera up or down enough to look behind myself.
This is the script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private Transform PlayerCamera;
[SerializeField] private CharacterController PlayerController;
[SerializeField] private float MouseSensitivity = 5f;
[SerializeField] private float MovementSpeed = 4f;
[SerializeField] private float JumpForce = 12f;
[SerializeField] private float Gravity = -9.81f;
private Vector3 Velocity;
private Vector3 PlayerMovementInput;
private Vector2 PlayerMouseInput;
private float CamXRotation;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
PlayerMovementInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
PlayerMouseInput = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"));
Move();
Look();
}
void Move()
{
Vector3 MoveVector = transform.forward * PlayerMovementInput.z transform.right * PlayerMovementInput.x;
if(PlayerController.isGrounded)
{
Velocity.y = -3f;
if(Input.GetKeyDown(KeyCode.Space))
{
Velocity.y = JumpForce;
}
}
else
{
Velocity.y -= Gravity * -2f * Time.deltaTime;
}
PlayerController.Move(MoveVector * MovementSpeed * Time.deltaTime);
PlayerController.Move(Velocity * Time.deltaTime);
}
void Look()
{
CamXRotation -= PlayerMouseInput.y * MouseSensitivity;
transform.Rotate(0f, PlayerMouseInput.x * MouseSensitivity, 0f);
PlayerCamera.localRotation = Quaternion.Euler(CamXRotation, 0f, 0f);
}
}
What lines of code can I add to this script to give the camera clamping?
CodePudding user response:
You can replace the first line of your Look()
to the following
CamXRotation = Mathf.Clamp(CamXRotation - PlayerMouseInput.y * MouseSensitivity, minAngle, maxAngle) ;
CodePudding user response:
There is a simple way to fix the camera, you can refer to the following code. Vector3.Lerp() takes as arguments two points and a decimal between 0-1 that represents a position between the two endpoints. The left endpoint is 0 and the right endpoint is 1. 0.5 returns the endpoint between the two points. Bring the rigTransform closer to the target position in a gradual and slow manner. That is - the camera will follow the player character. thank you, hope it helps
public float moveSpeed;
public GameObject target;
private Transform rigTransform;
void Start(){
rigTransform = this.transform.parent;
}
void FixedUpdate () {
if(target == null){
return;
}
rigTransform.position = Vector3.Lerp(rigTransform.position,
target.transform.position,
Time.deltaTime * moveSpeed);
}
}