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.
That is the current mouse position. The issue is that your objects are in world coordinates and the mouse is using screen coordinates.
You need to convert the mouse position using Camera.ScreenToWorldPoint().
The conversion with ScreenToWorldPoint
is straight-forward for 2D Vectors:
Vector2 screenPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
Vector2 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition);
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;
}
}
If you wanted to use the new Unity InputSystem you could do the following:
using UnityEngine;
using UnityEngine.InputSystem;
...
Vector2 screenPosition = Mouse.current.position.ReadValue();
Vector2 worldPosition = Camera.main.ScreenToWorldPoint(screenPosition)
Note that you need to install the InputSystem package for this to work.