博客地址:www.lxiaocode.com
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*
* Camera Follow.cs
* 需求:绑定此脚本的摄像头跟随指定游戏物体。
* 1. 摄像头跟随游戏物体。(核心功能)已完成
* 2. 限制摄像头显示范围。(可选功能)已完成
* 作者:lxiao
*/
public class CameraFollowLxiao : MonoBehaviour
{
//摄像机跟随的游戏对象
public Transform target;
//摄像机与游戏物体的相对位置向量
private Vector3 offset;
//摄像机限制
public bool limitBounds = false;
public float left = -5f;
public float right = 5f;
public float bottom = -5f;
public float top = 5f;
private Vector2 screenSize;
private Camera _camera;
private void Start()
{
if (target != null) //非空校验
{
//计算两点的相对位置
offset = transform.position - target.transform.position;
if (limitBounds)
{
_camera = GetComponent<Camera>();
//计算屏幕大小
Vector3 bottomLeft = _camera.ScreenToWorldPoint(Vector3.zero);
Vector3 topRight = _camera.ScreenToWorldPoint(new Vector3(_camera.pixelWidth, _camera.pixelHeight));
//计算摄像机移动范围
screenSize = new Vector2(topRight.x - bottomLeft.x, topRight.y - bottomLeft.y);
}
}
}
private void Update()
{
if (target != null) //非空校验
{
//更新位置
transform.position = target.transform.position + offset;
//位置限制
if (limitBounds)
{
Vector3 boundPosition = transform.position;
if (boundPosition.x > right - (screenSize.x / 2f)) boundPosition.x = right - (screenSize.x / 2f);
if (boundPosition.x < left + (screenSize.x / 2f)) boundPosition.x = left + (screenSize.x / 2f);
if (boundPosition.y > top - (screenSize.y / 2f)) boundPosition.y = top - (screenSize.y / 2f);
if (boundPosition.y < bottom + (screenSize.y / 2f)) boundPosition.y = bottom + (screenSize.y / 2f);
transform.position = boundPosition;
}
}
}
}