Search code examples
unity-game-engine3daugmented-realitygameobject

Unity - move 3d object in an AR scene


I have an AR scene that has one AR camera, an image target and 3d object below as.

enter image description here

I create an .cs file and attach to ARCamera. I want to move AR object to mouse click position. I tried many codes for this. But I couldn't success it.

I know that Input.mouseposition returns screen position. I convert to ScreenToWorldPosition and put 3d object on this position. 3d object is moved, but not mouse click position. I don't know where it is moved.

How can I move to mouse click position? My code is here :

Camera cam;
Vector3 target = new Vector3(0.0f, 10f,0.5f);
// Use this for initialization
void Start () {
    if (cam == null)
        cam = Camera.main;
}
void Update()
{
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("MouseDown");

        Vector3 mousePos = Input.mousePosition;
        mousePos = cam.ScreenToWorldPoint(mousePos);
        GameObject.Find("Car1").gameObject.transform.position = mousePos;
    }                                                                
}

EDIT 1 If I add a plane to scene, I can move to the position of mouse click only on the plane. The code is taken from here. But the plane prevents to show AR camera view. The screenshot is below:

enter image description here


Solution

  • Instead of playing with ScreenToWorldPoint, you should use a raycast against a plane, see this answer: https://stackoverflow.com/a/29754194/785171.

    The plane should be attached to your AR marker.