Discovering the mouse position in Unity with the New Input System: A Paraphrased Guide

The problem arises because your objects are positioned in world coordinates, while the mouse operates in screen coordinates. In order to utilize it, you must obtain the location of your UI object. If the anchor point of your UI object is defined as screen space, you will require both the camera and the screen space position, which corresponds to the mouse position.


My attempt to relocate an object to the
mouse position
is resulting in a significant x value of 300, whereas the initially placed object has an x position of -4 at that location.

rigidBody.velocity = new Vector3(Input.mousePosition.x, EndPointY, 0)*4;

So how can I get the
current mouse position

Thank you..

Solution 1:

To obtain the on-screen measurements in pixels, use
. To convert these measurements to world units, utilize Camera.

To manipulate a 3D object, you have two options: either use the mouse by accessing the link
Learn how to Drag
, or utilize the provided code to relocate an object from its current
position to the mouse

 //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;

Solution 2:

The process of converting with


is simple when dealing with 2D Vectors.

    Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
    Vector2 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);

Solution 3:

The current mouse position is causing an issue because your objects are using world coordinates while the mouse is using screen coordinates.

Utilize Camera.ScreenToWorldPoint() to convert the mouse position.

Solution 4:

If you were interested in employing the new Unity InputSystem, you could proceed in the following manner.

using UnityEngine;
using UnityEngine.InputSystem;
Vector2 screenPosition = Mouse.current.position.ReadValue();
Vector2 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition)

Please ensure that the InputSystem package is installed in order for this to function properly.

Frequently Asked Questions

Posted in Uncategorized