unity中实现静态的3D对象对其他对象的跟随
using UnityEngine; public class FollowPosition : MonoBehaviour { public Transform targetTrans; public Transform lookAtTrans; public Vector3 offsetPos; //与本跟随者之间的位置偏移 public bool x, y, z; //是否在对应的轴上进行跟随 Transform selfTrans; Vector3 targetPos; Vector3 curPos; void Start() { selfTrans = transform; } void LateUpdate() { if(targetTrans != null) { targetPos = targetTrans.position; curPos = selfTrans.position; if (x) curPos.x = targetPos.x + offsetPos.x; if (y) curPos.y = targetPos.y + offsetPos.y; if (z) curPos.z = targetPos.z + offsetPos.z; selfTrans.position = curPos; } if(lookAtTrans != null) { selfTrans.LookAt(lookAtTrans.position); } } }
测试的过程及效果如下:
这个时候,当cube的位置发生变化的时候sphere的即跟随运动: