- Home /
Move 3d object to the position of mouse click
I have an AR scene that has one AR camera, an image target and a 3D object as below.
I want to move the AR object to the position of the mouse click. I have tried taking the Input.mouseposition
(screen position), converting it using ScreenToWorldPosition and moving the 3D object to this position. The object is moved, but not to the mouse click position.
How can I move the object to the position of the mouse click? My code is as follows:
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;
}
}
To move 3d object with mouse, I tried this code. But it don't move the position of mouse click. link text
Try this maybe : https://gist.github.com/Opotable/3cb4937a693bd7cc8ec5
Is the object supposed to move on a flat or non-flat surface? And what camera angle are you using?
Answer by siaran · Apr 30, 2015 at 11:04 PM
First, you may want to try unparenting your Car1 object from ImageTarget, see if that makes a difference.
Also, you may want to try shooting a ray from your mouse position and setting your object position to your ray's hit point. like
GameObject car;
void Start(){
car = GameObject.Find("Car1");
}
void Update(){
if(Input.GetMouseButtonDown(0)){
RaycastHit hit;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit){
car.transform.position = hit.point;
}
}
}
Dunno if I got all the {} things correct there, but you get the idea.
I tried it. $$anonymous$$y scene has only an AR camera and a car object. I created a C# file and attached to AR camera. I used your code. But the object wasn't moved mouse click position.
Answer by 0potable · May 07, 2015 at 09:15 AM
Try this : http://pastebin.com/GSSMnE9R
Build up this very quickly. Post it once but as a comment (derp).
Save the file onto your Assets folder inside your project
Inside your
if(Input.GetMouseButtonDown(0))
, just call :Vector3 resultWorldPosition = MathfLib.MousePointToWorldPoint(yourCamera, theDistanceFromThisCamera);
Should do the trick ;)
Tell me if you want a version with raycast.
Your answer

Follow this Question
Related Questions
Cloud recognition in Vuforia 0 Answers
Very confused at what I should do 0 Answers
AR camera not working in app test 0 Answers
Returning to a scene with AssetBundle 1 Answer
Vuforia Multi Object Collision 0 Answers