PJ/Assets/scripts/CameraFollow.cs

36 lines
988 B
C#
Raw Normal View History

using UnityEngine;
public class CameraFollow : MonoBehaviour
{
public Transform player;
public BoxCollider2D bounds;
public float smoothness = 0.125f;
private float minX, maxX, minY, maxY;
private Camera cam;
void Start()
{
cam = GetComponent<Camera>();
float camHeight = cam.orthographicSize;
float camWidth = camHeight * cam.aspect;
minX = bounds.bounds.min.x + camWidth;
maxX = bounds.bounds.max.x - camWidth;
minY = bounds.bounds.min.y + camHeight;
maxY = bounds.bounds.max.y - camHeight;
}
void LateUpdate()
{
if (player == null) return;
float targetX = Mathf.Clamp(player.position.x, minX, maxX);
float targetY = Mathf.Clamp(player.position.y, minY, maxY);
Vector3 targetPosition = new Vector3(targetX, targetY, transform.position.z);
transform.position = Vector3.Lerp(transform.position, targetPosition, smoothness);
}
}