Unity中让摄像机自动跟随主角进行移动 您所在的位置:网站首页 unity镜头跟随物体移动 Unity中让摄像机自动跟随主角进行移动

Unity中让摄像机自动跟随主角进行移动

2023-09-11 10:02| 来源: 网络整理| 查看: 265

首先在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!



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有