I’m trying to make a basic 3rd person camera collider so my camera doesn’t clip through walls/floors. I have the basics working, but when make the character run the camera jumps around unexpectedly (something it didn’t do before I tried to add a collider). Any advice for a newbie like me? The code for my camera controller is below.
public class ThirdPersonCamera : MonoBehaviour
{
//in inspector, drag a cam look target into this field (cam will circle around it)
public Transform cameraTarget;
public bool lockCursor;
public float mouseSensitivity = 10f;
public float distanceFromCameraTarget = 1f;
float upDownRotation;
float leftRightRotation;
//so that camera will not tumble over the top of the character
public Vector2 upDownRotationMinMax = new Vector2(-40, 85);
public float cameraRotationSmoothTime = .07f;
Vector3 rotationSmoothVelocity, currentRotation;
//Zoom
float currentZoom = 5f;
float minZoom = .5f;
float maxZoom = 10f;
float zoomSpeed = 4f;
private void Start()
{
//lock the cursor to the center of the screen
if(lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
// Update is called once per frame
private void Update()
{
currentZoom -= Input.GetAxis("Mouse ScrollWheel") * zoomSpeed;
currentZoom = Mathf.Clamp(currentZoom, minZoom, maxZoom);
}
// Late update because target position will be set before this is called
void LateUpdate()
{
//moving mouse up and down will look up and down, and left right is left right
leftRightRotation += Input.GetAxis("Mouse X") * mouseSensitivity;
upDownRotation -= Input.GetAxis("Mouse Y") * mouseSensitivity;
//no camera tumbling, clamp between 2 degrees
upDownRotation = Mathf.Clamp(upDownRotation, upDownRotationMinMax.x, upDownRotationMinMax.y);
currentRotation = Vector3.SmoothDamp(currentRotation, new Vector3(upDownRotation, leftRightRotation), ref rotationSmoothVelocity, cameraRotationSmoothTime);
transform.eulerAngles = currentRotation;
// move the camera
transform.position = cameraTarget.position - transform.forward * distanceFromCameraTarget * currentZoom;
//send out a raycast
RaycastHit hit = new RaycastHit();
//if something collides, transform camera to hit location
if (Physics.Linecast(cameraTarget.position, transform.position, out hit))
{
Debug.DrawRay(hit.point, Vector3.left, Color.red);
transform.position = new Vector3(hit.point.x, hit.point.y, hit.point.z);
Debug.Log(transform.position);
}
}
}