I want to create a camera input controller that behaves as a mix between third person and first person shooter style cameras. It follows the player but the player is always centered (± some offset so I can see ahead of the player) and aiming is based around the camera’s rotation instead of the players.
using UnityEngine;
using System.Collections;
public class PlayerCamera : MonoBehaviour {
//public
public Transform Player;
public float zOff = -4.0f;
public float yOff = 2.0f;
public float xSpeed = 250.0f;
public float ySpeed = 120.0f;
private Transform _transform;
private float mouseX;
private float mouseY;
// Use this for initialization
void Start()
{
_transform = transform;
Screen.lockCursor = true;
}
// Update is called once per frame
void Update()
{
if (Player == null)
return;
if (Input.GetKeyDown(KeyCode.P))
{
Screen.lockCursor = !Screen.lockCursor;
}
}
//Called after Update
void LateUpdate()
{
if (Player == null)
return;
mouseX += Input.GetAxis("Mouse X") * xSpeed * 0.02f;
mouseY += Input.GetAxis("Mouse Y") * ySpeed * 0.02f;
mouseY = Mathf.Clamp(mouseY, -30f, 30f);
Quaternion rotation = Quaternion.Euler(-mouseY, mouseX, 0);
Vector3 position = (rotation * new Vector3(0f, yOff, zOff)) + Player.position;
Debug.Log(mouseY + " : " + rotation);
_transform.rotation = rotation;
_transform.position = position;
Player.rotation = Quaternion.Euler(Player.rotation.eulerAngles.x, rotation.eulerAngles.y, rotation.eulerAngles.z);
Transform head = Player.FindChild("Head").gameObject.transform;
float x = (rotation.x * Mathf.Rad2Deg) / 2f;
head.rotation = Quaternion.Euler(x, rotation.eulerAngles.y, rotation.eulerAngles.z);
}
}
The issue I’m having is when I reach the cap that the clamp issues (± 30 degrees) and then look in the opposite direction, the previous value I’d have when looking at a specific point would be offset by a random number. This number isn’t constant and changes when I change the cap. I could probably implement a way to fit in this offset since I’ll have a constant min/max, but I don’t want a hackish way to fix this. I want to fully fix the issue.
So can anyone see an issue or have an alternative to using Input.GetAxis()? It might also be important to note that the problem persists on both a mouse and a touchpad.
EDIT: With more experimentation I’m beginning to believe that the issue lies with the position of the camera (Vector3 position) and not with the mouse input. Since this method is buggy, is there a better way to make the camera appear behind the player but still be focused on the player? So if I look down, the camera goes above the player and when I look up, the camera goes under the player.