目前有一个模式在特定条件下让物体跟随camera,但是物体是全局坐标下创建的,肯定不能直接让其成为camera的子物体,于是就需要用坐标转换去计算并赋值物体位置
首先需要确定跟随物,我项目里是camera,这里演示就写targetGO了。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FollowCubeTest : MonoBehaviour
{
Vector3 pos;
Quaternion rot;
public Transform targetGO;
// Start is called before the first frame update
void Start()
{
//计算当前物体相对于目标物体的偏移量,以目标物作为坐标系
pos = targetGO.InverseTransformDirection(transform.position - targetGO.position);
rot = Quaternion.Inverse(targetGO.rotation) * transform.rotation;
}
// Update is called once per frame
void Update()
{
//当前物体需要在目标物的坐标上加上相对的偏移量,这里将偏移量转成世界坐标就可以直接相加
transform.position = targetGO.position + targetGO.TransformDirection(pos);
transform.rotation = targetGO.rotation * rot;
}
}