Getting mouse position in unity

后端 未结 4 2152
感情败类
感情败类 2020-12-11 03:32

I\'m trying to move a object to the mouse position. But it\'s giving me large x value like 300 but at that place the pre placed object\'s x position is -4.

         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-11 03:50

    Input.mousePosition will give you the position of the mouse on screen (pixels). You need to convert those pixels to the world units using Camera.ScreenToWorldPoint().

    You can follow this link to learn how to drag a 3d object with the mouse or you can copy this code to move an object from the current position to the mouse position.

     //the object to move
    public Transform objectToMove;
    
     void Update()
     {
         Vector3 mouse = Input.mousePosition;
         Ray castPoint = Camera.main.ScreenPointToRay(mouse);
         RaycastHit hit;
         if (Physics.Raycast(castPoint, out hit, Mathf.Infinity))
         {
             objectToMove.transform.position = hit.point;
         }
     }
    

提交回复
热议问题