//将脚本绑定在需要被限定范围的物体上 using UnityEngine; using System.Collections; public class ControlLimited : MonoBehaviour { float dis; //移动的最大距离 [SerializeField] private float MoveMaxDistance = 50;//最大拖动距离 private Vector3 Origin; Transform mTrans; [SerializeField] void Start() { Origin = transform.localPosition; //设置原点 mTrans = transform; Debug.Log("开始拖拽123"+gameObject); } void LateUpdate() {//LateUpate防止移动的过程中发生闪烁 dis = Vector3.Distance(mTrans.localPosition, Origin); //拖动距离,这不是最大的拖动距离,是根据触摸位置算出来的 if (dis >= MoveMaxDistance) //如果大于可拖动的最大距离 { Vector3 vec = Origin + (mTrans.localPosition - Origin) * MoveMaxDistance / dis; //求圆上的一点:(目标点-原点) * 半径/原点到目标点的距离 mTrans.localPosition = vec; } } }