public class ObjectDragger : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
bool dragged = false;
private Vector3 newPosition;//赋值给物体的坐标位置
private Rigidbody body;
void Awake(){
//获取自身重力
body = gameObject.GetComponent<Rigidbody>();
//获取自身初始坐标
newPosition = transform.position;
}
void OnMouseDown()
{
//按下鼠标时获取自身当前坐标的屏幕坐标
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
//按下鼠标时记录物体的世界坐标,和鼠标世界坐标的向量偏移
offset = gameObject.transform.position -
Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
}
void OnMouseDrag()
{
//按下拖动鼠标时
dragged = true;
Debug.Log("按下拖动鼠标时");
}
void FixedUpdate(){
if (dragged){
dragged = false;
//当前鼠标的屏幕坐标
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
//保持物体与鼠标的位置偏移量
newPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
if (body != null)
body.velocity = (newPosition - transform.position) / Time.deltaTime;
Debug.Log(body.velocity);
}
}
void LateUpdate(){
//移动代码
transform.position = newPosition;
}
}