Drag 3d object using fingers in unity3d

2019-08-07 17:50发布

问题:

I create a scene has an AR camera and a 3d object. When application starts, I see the object on the screen. I want to move this object using fingers. I tried many codes. But I couldn't find a nice solution for me.

AR camera is tagged MainCamera. I use below code, and the result is unexpected for me. I click on object and the console output is here:

How can I move 3d object to mouse click position? I don't use any marker.

Vector3 vect3 = Camera.main.WorldToScreenPoint(car.transform.position);
Debug.Log("Vect3 = " + car.transform.position.x + "-" + car.transform.position.y + "-" + car.transform.position.z);         

Vector3 p = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10.0f));//Camera.main.nearClipPlane));
Debug.Log("Mouse = " + p.x + "-" + p.y + "-" + p.z);

回答1:

Try this code:

private Vector3 scrPt;
private Vector3 distance;

 void OnMouseDown()
 {
     scrPt= Camera.main.WorldToScreenPoint(car.transform.position);
     distance = car.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
 }

 void OnMouseDrag()
 {
     Vector3 currentScrPt= new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);     
     Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScrPt) + distance;
     car.position = currentPosition ;
 }