绑定相机到GameObject
- 方法一:直接将相机拖动到GameObject里面,但是这样不仅位置会变,缩放,旋转都会跟着变,而我们仅仅要的是位置position的改变,效果不好
- 方法二:代码控制,先用public方法声明一个transform组件,在unity面板中,将需要跟随的GameObject拖动赋值给相机C#脚本的public变量值,之后计算出相机与GameObject之间的偏移,在update中加上即可。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Camera : MonoBehaviour
{
//声明一个Transform组件(在unity中进行赋值)
public Transform playerTransform;
//偏移量(xyz)
private Vector3 offset;
// Start is called before the first frame update
void Start()
{
//初始时计算出偏移量
//直接写transform就是代表这个脚本所绑定的GameObject的Transform组件
offset = transform.position - playerTransform.position;
}
// Update is called once per frame
void Update()
{
//更新物体的位置
transform.position = playerTransform.position + offset;
}
}