unity中控制相机跟随物体移动
-
Main Camera下添加组件(follow target)
-
脚本中定义
public Transform trans;
-
将transform拖拽到trans中,让trans可以引用到transform数值(方式1)
-
因为属于当前GameObject下的脚本组件,不使用拖拽的方式的话,可以直接在代码中用下面方式获取到transform的数值(方式2)
transform.position //此方法是在父类的MonoBehaviour中定义
- 定义目标对象
public GameObject player;
-
添加目标引用对象
-
脚本里添加相对位置的设置逻辑
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class followTarget : MonoBehaviour
{// public Transform trans;public GameObject player;private Vector3 offset;// Start is called before the first frame updatevoid Start(){offset = transform.position - player.transform.position;}// Update is called once per framevoid Update(){transform.position = player.transform.position + offset;}
}
到此可实现控制相机跟随物体移动!