Question by
unity_DLrwyjXuAuZTvg · Feb 08, 2020 at 09:36 PM ·
cameracamera-movementcamera-look
Move camera to look around with mouse
I have a script attached to a camera that follows a 3rd person character, the user controls the character with WASD keys but also able to look around the axis with the mouse while playing, the script works fine, but has one issue, I can't move the camera along the Vertical axis, the player is able to move the camera left and right but up and down are not working for some reason!! This is my Script (C#):
public class PlayerFollow : MonoBehaviour
{
public Transform PlayerTransform;
private Vector3 _cameraOffset;
[Range(0.01f, 1.0f)]
public float SmoothFactor = 0.5f;
public bool LookAtPlayer = false;
public bool RotateAroundPlayer = true;
public bool RotateMiddleMouseButton = true;
public float RotationsSpeed = 5.0f;
public float CameraPitchMin = 1.5f;
public float CameraPitchMax = 6.5f;
// Use this for initialization
void Start()
{
_cameraOffset = transform.position - PlayerTransform.position;
}
private bool IsRotateActive
{
get
{
if (!RotateAroundPlayer)
return false;
if (!RotateMiddleMouseButton)
return true;
if (RotateMiddleMouseButton && Input.GetMouseButton(2))
return true;
return false;
}
}
// LateUpdate is called after Update methods
void LateUpdate()
{
if (IsRotateActive)
{
float h = Input.GetAxis("Mouse X") * RotationsSpeed;
float v = Input.GetAxis("Mouse Y") * RotationsSpeed;
Quaternion camTurnAngle = Quaternion.AngleAxis(h, Vector3.up);
Quaternion camTurnAngleY = Quaternion.AngleAxis(v, transform.right);
Vector3 newCameraOffset = camTurnAngle * camTurnAngleY * _cameraOffset;
// Limit camera pitch
if (newCameraOffset.y < CameraPitchMin || newCameraOffset.y > CameraPitchMax)
{
newCameraOffset = camTurnAngle * _cameraOffset;
}
_cameraOffset = newCameraOffset;
}
Vector3 newPos = PlayerTransform.position + _cameraOffset;
transform.position = Vector3.Slerp(transform.position, newPos, SmoothFactor);
if (LookAtPlayer || RotateAroundPlayer)
transform.LookAt(PlayerTransform);
}
}
Comment
Your answer
Follow this Question
Related Questions
Make Camera follow rotation of 2 Players 1 Answer
Sit Down First person 0 Answers
Spyro Like Camera Follow 0 Answers
When attaching my custom camera script camera shakes when player starts to move fast. 0 Answers
viewing on the Mouse Y axis not working. 0 Answers