# Having an object point towards mouse position in 3d world

Hello. I’ve been trying to get this to work for… Let’s just say many hours now, and despite finding a bunch of suggestions and help threads i’ve been unable to solve it. So in a last attempt i’m writing here, hoping someone will be willing to help me find the solution.

I’m trying to have a pistol point at the mouse. It’s fairly simple in theory.

I’ve tried using raycast to solve this by creating a gameobject i wanted to follow the mouse, but the problem with this is, that when i use transform.position, unity tells me that i’m unable to use vector3 as transform position.

While i’ve been able to get the information from the damn mouse, i’m unable to figure out a way to actually tell the object to move to the location.

So the big issue that i’m having is what to put inside the if statement. I realize that i’ve stored raycast in my variable, but i have no idea how to translate the contents of the variable to a float or a int or anything that i can use in combination with transform.position/translate or some other function that allows me to move my object to the mouses position.

A different thing i tried was the “lookAt”, but since the mouse is on a 2d axis, it didn’t really work.

Thanks in advance for the time.

What you need is a combination between two things-

1. A flat plane, or ground collider

2. A raycast from the screen.

Now, as I understand it, you know how to get the mouse position. Now, use

``````Camera.main.ScreenpointToRay(mousePosition);
``````

to get a ray, then use Physics.Raycast against the ground collider to get the point.

One thing to remember is that using this method will cause the character to look slightly at the ground, more so if the mouse is close to them. To get around this, modify the value of the returned point from the raycast by the player’s position on your ‘up’ axis, something like this-

``````point = new Vector3(point.x, player.transform.position.y, point.z);
``````

Then when you use LookAt, the player will always look around in a circle, not looking down at the ground.