How to place gameobject to mouse position

4.6k Views Asked by At

I want to place gameobject to same place where I pressed with mouse in X,Y coordinates. Z should be the same always

How can I achieve this?

I tried currently

Vector3 a = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));
myGameObject.transform.position = Vector3.Lerp(myGameObject.transform.position, a, 0.01f);

But this doesn't work. It just moves my object in Z coordinate.

1

There are 1 best solutions below

0
On BEST ANSWER

You change the z-axis to 0. You should keep your original z coordinate like this:

Vector3 a = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0));

a.Set(a.x, a.y, myGameObject.transform.position.z);

myGameObject.transform.position = Vector3.Lerp(myGameObject.transform.position, a, 0.01f);