I need a camera follow script to chase a moving ball. I've attached the script below to my camera, but when the ball turns left and right the camera does not turn
using UnityEngine;
public class FollowPlayerCamera : MonoBehaviour
{
public GameObject[] playerBalls; // Array of player balls
public float smoothSpeed = 0.125f; // How smoothly the camera follows the ball
public Vector3 offset; // Offset from the ball position
private ActivatePlayer playerController; // Reference to the BallPlayerController script
private Transform target; // The current active player to follow
void Start()
{
playerController = FindObjectOfType<ActivatePlayer>();
if (playerController != null)
{
// Ensure there is at least one player in the array
if (playerBalls.Length > 0)
{
// Set the first player in the array as the initial target
target = playerBalls[playerController.selectedPlayerIndex].transform;
}
}
else
{
Debug.LogWarning("BallPlayerController script not found in the scene!");
}
}
void LateUpdate()
{
if (playerController == null)
{
return;
}
// Find the active player to follow
if (playerController.selectedPlayerIndex >= 0 && playerController.selectedPlayerIndex < playerBalls.Length)
{
target = playerBalls[playerController.selectedPlayerIndex].transform;
}
if (target == null)
{
// If there's no target, exit the function
return;
}
// Calculate the desired position of the camera
Vector3 desiredPosition = target.position + offset;
// Interpolate smoothly towards the desired position
Vector3 smoothedPosition = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
// Set the camera's position
transform.position = smoothedPosition;
}
}
Vector3.Lerp
is used wrongly. \$\endgroup\$