- Home /
Converting Input.mousePosition to world coordinates
Hey everyone,
I am trying to make a gun always point at the mouse cursor. The MouseLook script allows users to control the rotation of an object using the mouse, but the object doesn't actually LOOK at the mouse cursor at all times...
This is my code to do this:
function Update() {
var screenPoint = Input.mousePosition;
transform.LookAt(Camera.main.ScreenToWorldPoint(screenPoint));
}
Unfortunately it doesn't work. :( Any ideas what I'm doing wrong?
Answer by fafase · Aug 31, 2012 at 04:38 PM
How's your camera? Are you in 3D? 2D? Perpendicular to the ground?
You could use:
var hit : RaycastHit;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), hit))
transform.LookAt(hit.point);
}
Edit:Sorry I edited 3 times in a row...
Except you might have to modify the y-position. Since the contact point is on the ground, you need to lift it up a bit.
That is if your guy is free to shoot in all direction. If he is restricted then no worries. Hopefully you see what I mean.
Your answer
Follow this Question
Related Questions
GameObject rotates away from camera when using ScreenToWorldPoint 0 Answers
Find TextureCoordinates from plane with out raycast only using mouse position on plan 0 Answers
Game object moving in opposite direction instead of same direction while dragging it 0 Answers
ScreenToWorldPoint() not working 2 Answers
World point for MousePosition 1 Answer