# Flashlight looking at mouse in 2D

Simple code, im trying to make a cube follow the position of the mouse, i tried different things but something's not right; the position of the cube is far from the actual position of the mouse pointer, why is that?

``````//GameObject is the cube
void Update ()
{
gameObject.transform.position = Input.mousePosition;
}

``````

or in javascript:

``````var mousePos : Vector3;

function Update ()
{
mousePos = Input.mousePosition;
gameObject.transform.position = mousePos;
}

``````

or just using the lookAt function to make it simpler

``````transform.LookAt(Input.mousePosition);

``````

im doing this so that i can target a flashlight torwards the cube, this is a 2D game so the MouseLook script wont work; i keep seeing there's something to do with the screen.height but im not rly sure what to do. thx u

The mouse operates in screen space, a 2-dimensional(basically) plane in front of the camera, it uses different coordinates and isn't really a 3D thing you can look at.

However, you can have your code turn it into world coordinates by properly using ScreenToWorldPoint

This will make a Vector3 that you can use as position information (specifying your own z coordinate).

for example,

``````transform.position = myCamera.ScreenToWorldPoint( Vector3(Input.mousePosition.x, Input.mousePosition.y,10));

``````

will set your object's position 10 units directly in front of the camera, at the mouse position.

EDIT:

I changed the code to imply the camera as a variable. You can declare this with your other variables

``````var myCamera : Camera;

``````

and in the inspector, drag the camera game object into that variable slot.

the position of mouse is in pixel form and it’s discrete, you should convert mouse position to unity’s world with Camera.main.ScreenToWorld(Input.mousePosition) function