首先在Unity场景中主摄像机上绑定一个脚本,在这里我绑定的是CameraFollow.cs的一个脚本,然后打开脚本,并复制以下的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour {
private Transform target;
private Vector3 offset;
private Vector2 velocity;
private void Update()
{
if (target == null && GameObject.FindGameObjectWithTag("Player") != null)
{
//查找目标tag标签为Player游戏物体的位置值
target = GameObject.FindGameObjectWithTag("Player").transform;
//计算出目标点到摄像机位置的偏移值
offset = target.position - transform.position;
}
}
private void FixedUpdate()
{
if(target != null)
{
//平滑缓冲,游戏物体不是僵硬的移动而是做减速缓冲运动到指定位置
float posX = Mathf.SmoothDamp(transform.position.x,
//target.position.x - offset.x等于主摄像机的位置坐标
target.position.x - offset.x, ref velocity.x, 0.05f);
float posY = Mathf.SmoothDamp(transform.position.y,
target.position.y - offset.y, ref velocity.y, 0.05f);
//防止很大弧度的屏幕抖动
if (posY > transform.position.y)
{
transform.position = new Vector3(posX, posY, transform.position.z);
}
}
}
}
注意:让摄像机跟随的游戏物体标签一定要设置为Player!