- Home /
Camera look at problem
i'm trying to make the player and camera look at mouse position it works fine in y axis but in x it still moves in the y only , any help ? and there is another something when i hit play the camera rotated in a different way not the one it was set for ? my code
function Update()
{
var target : Vector3 = (Input.mousePosition);
transform.LookAt(target);
}
Answer by robertbu · May 09, 2013 at 12:30 PM
This problem, in various forms, has been answered many times on this list. But most of the answers I found in a quick Google search were specialized. So here is a simple answer to what can be a complex problem. The reason your code is not working is that Input.mousePosition is in Screen coordinates and your transform lives in world coordinates. So you have to convert between the two.
function Update () {
var target = Vector3(Input.mousePosition.x, Input.mousePosition.y, 8.0);
target = Camera.main.ScreenToWorldPoint(target);
transform.LookAt(target);
}
See the "magic" 8.0? When using ScreenToWorldPoint(), the 'Z' parameter is the distance in front of the camera. Unity is 3D, so we need to specify not only a screen position to convert, but the distance in front of the camera from that position to make the conversion. Note the closer this point is to the character (i.e. the object this script is attached to), the stronger the LookAt() response.
For exmaple, imagine someone is moving a hand around on a large window. How much you move your head to follow the hand will depend on how close you are to the window. The same thing applies here. Play with different values for the 'Z' parameter and you can see how this applies to the LookAt code.
Note for your game, you will likely need to do something more complex with the 8.0. Instead of a hard-coded value, it will be some distance in front of the player, or perhaps some fraction of the distance between the camera and the player.
Thanks for your answer i really appreciate it. but when i used it the camera kept moves like crazy?
This script needs to be attached to the object you want to look at the mouse position. It should not be attached to the camera. To get you started:
Create a new scene
Put a cube in the sceen at (0,0,0).
Attach the script to the cube
Hit play
Repeat with different 'Z' values (try 9.5 ins$$anonymous$$d of 8.0 for example).
Your answer
Follow this Question
Related Questions
FPS Camera Collision 3 Answers
camera to turn 1 Answer
How can I construct a 4x4 rotation matrix to look in the direction of a Vector4? 0 Answers