Object following mouse problem.

Hello,

I used this code for making my object follow the mouse (2d):
var followingObject : Transform;

var xPos: float;
var yPos: float;
 
function Update () {

xPos=Input.mousePosition.x;
yPos=Input.mousePosition.y;
    
followingObject.position = Vector2(xPos,yPos);
    
}

it seems doesn’t work good its like not on the mouse by alot of diffrence, cause the mouse starts from the down left of screen and the object from the center, so how to make perfectly on the mouse? i used raycast but i didnt like it cause it was not working good like the object run off the mouse

thanks.

The mouse works in screen coordinates. Your object lives in world coordinates. You have to translate the two. Plus since the world is 3D and the mouse is 2D you have to set how far in front of the camera. One way to make this conversion is to use Camera.ScreenToWorldPoint(). It is example code where the Z distance is set to 10.

function Update () {
  var v3T = Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
  v3T = Camera.main.ScreenToWorldPoint (v3T);
  followingObject.position = v3T;
}