Search code examples
c#unity-game-enginepositiongameobject

How to place gameobject to mouse position


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.


Solution

  • 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);