0

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

Daniel
  • 10,641
  • 12
  • 47
  • 85
zakjma
  • 2,030
  • 12
  • 40
  • 81

2 Answers2

0

ScreenToWorldPoint takes a Vector3, mousePosition is basically a Vector2 (with a 0 z-axis value). You need to set the mousePosition.z value to something for it to be placed in a viewable position. Example:

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

This would set the position to 10 units away from the camera.

anothershrubery
  • 20,461
  • 14
  • 53
  • 98
  • Should I set units value before calling this code? I tried this way, but I could't see object at the position of mouse click? – zakjma Apr 29 '15 at 15:35
  • I don't know what you mean, just adjust the 10 to a figure that works for your scenario. If you are looking it to be a dynamic distance from the camera then other functionality is required, but the flow is the same. The reason you don't see the 3D object is because it isn't in front of the camera. – anothershrubery Apr 29 '15 at 15:41
0

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.

Community
  • 1
  • 1
Krzysztof Bociurko
  • 4,575
  • 2
  • 26
  • 44
  • Thanks. it works. If I don't want to change object size, how can I do it? I want to move object but not scale. – zakjma May 02 '15 at 05:41