Here is a C# script for Unity that ensures a third-person camera moves closer to the player when an object obstructs the view. This script utilizes raycasting to detect occlusion and adjust the camera’s position accordingly.
using UnityEngine;
public class ThirdPersonCamera : MonoBehaviour
{
public Transform player;
public float defaultDistance = 5f;
public float minDistance = 1f;
public float smoothSpeed = 10f;
public Vector3 offset;
private float currentDistance;
void Start()
{
currentDistance = defaultDistance;
}
void LateUpdate()
{
HandleCameraOcclusion();
}
void HandleCameraOcclusion()
{
Vector3 desiredPosition = player.position - transform.forward * defaultDistance + offset;
RaycastHit hit;
if (Physics.Raycast(player.position + offset, -transform.forward, out hit, defaultDistance))
{
currentDistance = Mathf.Clamp(hit.distance, minDistance, defaultDistance);
}
else
{
currentDistance = defaultDistance;
}
Vector3 newPosition = player.position - transform.forward * currentDistance + offset;
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * smoothSpeed);
transform.LookAt(player.position + offset);
}
}
How It Works:
- The camera starts at a default distance from the player.
- A raycast is fired from the player toward the camera.
- If the ray hits an obstacle, the camera moves closer, adjusting its position to maintain visibility.
- If no obstacle is detected, the camera stays at the default distance.
- The camera smoothly transitions to the new position.
You can adjust:
defaultDistancefor normal camera distance.minDistanceto set the closest the camera can get.smoothSpeedto control movement smoothness.