- Home /
Question by
timo0060 · Jun 27, 2012 at 06:34 PM ·
javascriptmouselookat
Making character look at mouse
So I'm trying to make the character look at the mouse and so far all I have is this code to find the mouse position and to look at it,
// this creates a horizontal plane passing through this object's center
var plane = Plane(transform.position, Vector3.up);
// create a ray from the mousePosition
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// plane.Raycast returns the distance from the ray start to the hit point
var distance: float;
if (plane.Raycast(ray, distance)){
// some point of the plane was hit - get its coordinates
hitPoint = ray.GetPoint(distance);
hitPoint.y = 0;
transform.LookAt(hitPoint);
My problem is that the whole character rotates on all his axis, He should only rotate on the y, (Top down shooter), so How can I get it so that he looks at the cursor smoothly and only on the rotate on the y axis?
Comment
Best Answer
Answer by aldonaletto · Jun 27, 2012 at 07:02 PM
Just remove this line:
hitPoint.y = 0;
This line "sits" the hitPoint at y=0, but it should be at the player's y coordinate - what it already was because the plane was created at the player's center.
NOTE: For a more generic case, you could do instead:
hitPoint.y = transform.y;
This would fix any height differences if the plane wasn't at the object's level.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073401im_/https://answers.unity.com/themes/thub/images/avi.jpg)