1.不垂直于地面的情况是 通过射线检测地面 返回碰撞的点 直接赋值给当前物体 也可以用于垂直于地面的情况
2.在移动端只需要把Input.mousePosition替换成Input.GrtTouch(0).position即可
if (Input.GetMouseButtonDown(0))
{
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log(hit.collider.gameObject.tag);
if (hit.collider.gameObject.CompareTag("sheep"))
{
currentObj = hit.collider.transform;
sheep = currentObj.GetComponent<Sheep>();
sheep.StartDrag();
objScreenPos = mainCamera.WorldToScreenPoint(currentObj.position);
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, objScreenPos.z);
mousePos = mainCamera.ScreenToWorldPoint(mousePos);
offest = currentObj.position - mousePos;
}
}
}
if (Input.GetMouseButton(0))
{
if (currentObj != null)
{
//相机视野方向垂直于地面时
Vector3 curMousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, objScreenPos.z);
curMousePos = mainCamera.ScreenToWorldPoint(curMousePos);
Vector3 newPos = curMousePos + offest;
currentObj.transform.position = new Vector3(newPos.x, currentObj.position.y, newPos.z);
//相机视野方向不垂直于地面时
//Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
//RaycastHit hit;
//if (Physics.Raycast(ray, out hit, 100, 1 << 9))
//{
// currentObj.transform.position = hit.point;
//}
yield return new WaitForFixedUpdate();
}
}