Here is the C# version, LookAtMouse.cs
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour
{
void Update ()
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Vector3 temp = new Vector3(ray.direction.x, ray.direction.y, 0);
transform.LookAt(temp);
}
}
Attach it to anything you want to look at the mouse point. To understand what is going on, here is a simple translation to english:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
Code is always wrapped up from the inside out, from left to right. This means that the first thing executed here is Input.mousePosition. It simply returns the pixel coordinates from the screen, where 0,0 is the bottom left and 1920,1080 is the top right on for example a FullHD setup. Next it sends the coordinates value to the function ScreenPointToRay, which happens to be a function that belongs to Camera.main (Camera.main simply means “The camera tagged as MainCamera”, and if there are multiple tagged that when you might get into trouble).
Whatever the case, once the function gets the pixel coordinates it then sends a raycast (invisible line) from that pixel at the camera location and forward from the camera (the way the camera is looking). That ray is the output of the function ScreenPointToRay, and we save that in a newly created variable simple called ray.
Vector3 temp = new Vector3(ray.direction.x, ray.direction.y, 0);
A ray in general has several values, direction being the one that we are interested in. Picture the ray coming from the camera and going off into infinity; we need to know the (relative to the camera) horizontal position and the vertical position of that ray. Well we get that from the direction, and we can directly access it from a Vector3 stored on the ray itself. For example we can access the direction as such: ray.direction. In out case we don’t care about depth, so what we’ll do is create a new Vector3 that simple stores the x and y coordinates and sets the depth (z) to 0. The new variable is called temp.
transform.LookAt(temp);
On of the neat function the transform has is a function called LookAt. It simply takes a Vector3 variable, where the content (three numbers) represents a position in space. The function then automatically does a lot of behind-the-scenes work and translates those coordinates into a rotation of the object so that the object is always rotated and looking at that spot. Keep in mind that it will look at that point using the local forward of the object. What this means is that if you have for example a turrent and it is pointing 90 degrees wrong from where you want it to look, then that is because the forward if that object is not set up correctly in the modeling application where it was created. Rotating it to the correct position in the 3d app and export it, and it should work in Unity (if using 3dsmax it might be a good idea to reset XForm before exporting it again).