ScreenToWorldPoint apparently always returns the center of the camera, not the mouse position. Although I could be wrong about that.
[Post describing this concept further.][1]
The best way is to use raycasting with a similar function, ScreenPointToRay.
This is a simple C# script that snaps the Transform to face the mouse, from a topdown perspective. With a little tweaking of vectors it should work perfect for you as well from the side. (You could probably use only X and Y and set Z to 0)
using UnityEngine;
using System.Collections;
public class RotateToMouse : MonoBehaviour {
public Vector3 lookPos;
// Update is called once per frame
void Update ()
{
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
if (Physics.Raycast(ray, out hit))
{
lookPos = new Vector3 (hit.point.x, 0f, hit.point.z);
transform.LookAt(lookPos);
}
}
}
One thing to watch out for is that you absolutely MUST have a collider that the ray will hit, otherwise you will get a null reference exception. You could just add a public LayerMask that only hits the collider's layer to the script, set up the collider in a separate layer, and then add the LayerMask variable to the Physics.Raycast(ray, out hit, HERE).
The "0f" in the look position in the "Y" spot is so that no matter how close or far away the collider is it always sets the lookPos "Y" position to absolute zero. That way the object does not look up or down in a 2D environment, which would probably look odd.
I hope that helps!
Thanks, and God bless!
Howey
[1]: http://answers.unity3d.com/questions/18205/world-mouse-position-not-depending-on-screen-mouse.html
↧