I’m trying to create a third-person camera using Cinemachine (I have a FreeLook
Camera being used) and the new Input System, however, I only want my camera to pitch and move when I hold down right click.
For some reason, when I apply my if (Input.GetMouseButtonDown(1))
condition and playtest my code in the game window, the engine acts like I never put down that right-click condition in the first place.
Here’s my code:
using System;
using UnityEngine;
using UnityEngine.InputSystem;
using Cinemachine;
public class CameraManager : MonoBehaviour
{
#region Variables
[SerializeField] private Transform target;
private float _distanceToPlayer;
private Vector2 _input;
private Vector3 _offset; //for the else statement
[SerializeField] private float smoothTime; //for the else statement
private Vector3 _currentVelocity = Vector3.zero; //for the else statement
[SerializeField] private MouseSensitivity mouseSensitivity;
[SerializeField] private CameraAngle cameraAngle;
private CameraRotation _cameraRotation;
#endregion
private void Awake()
{
_distanceToPlayer = Vector3.Distance(transform.position, target.position);
_offset = transform.position - target.position; //for the else statement
}
public void Look(InputAction.CallbackContext context)
{
_input = context.ReadValue<Vector2>();
}
private void Update()
{
if (Input.GetMouseButtonDown(1))
{
_cameraRotation.Yaw += _input.x * mouseSensitivity.horizontal * BoolToInt(mouseSensitivity.invertHorizontal) * Time.deltaTime;
_cameraRotation.Pitch += _input.y * mouseSensitivity.vertical * BoolToInt(mouseSensitivity.invertVertical) * Time.deltaTime;
_cameraRotation.Pitch = Mathf.Clamp(_cameraRotation.Pitch, cameraAngle.min, cameraAngle.max);
}
}
private void LateUpdate()
{
if (Input.GetMouseButton(1))
{
transform.eulerAngles = new Vector3(_cameraRotation.Pitch, _cameraRotation.Yaw, 0.0f);
transform.position = target.position - transform.forward * _distanceToPlayer;
}
else
{
var targetPosition = target.position + _offset;
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref _currentVelocity, smoothTime);
}
}
private static int BoolToInt(bool b) => b ? 1 : -1;
}
[Serializable]
public struct MouseSensitivity
{
public float horizontal;
public float vertical;
public bool invertHorizontal;
public bool invertVertical;
}
public struct CameraRotation
{
public float Pitch;
public float Yaw;
}
[Serializable]
public struct CameraAngle
{
public float min;
public float max;
}
If it helps people with my question I’m using the 2021 Unity Editor.
UPDATE:
I decided to disable Cinemachine temporarily to see what would happen, it enables my right click requirement, but for some reason when I stop holding right click, my camera is warped to a different position, I know that this warping seems to be related to the code in my else statement, but I’m unsure how it’s being caused.