计算物体的相对坐标:
Vector3 pos1;
Vector3 pos2;
//pos1相对于pos2的坐标,即pos1是pos2的子级
Vector relativePos1=pos1-pos2;
//pos2相对于pos1的坐标,即pos2是pos1的子级
Vector relativePos2=pos2-pos1;
一个通过鼠标移动物体的代码实例:(被移动的物体是一个Plane,否则要考虑物体本身的体积)
using UnityEngine;
public class ChipContro : MonoBehaviour {
Ray ray;
RaycastHit hit;
//物体相对于鼠标位置的偏移量
public Vector3 offect;
public void OnMouseDown() {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
//物体的位置相对于鼠标位置的坐标,即物体跟随鼠标移动的偏移量
offect = gameObject.transform.position - hit.point;
}
public void OnMouseDrag() {
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit))
//物体位置=鼠标位置+相对坐标
transform.position = hit.point+offect;
}
}