Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var mousePlane:GameObject; //The 3D plane in the scene that we project the mouse's screen location onto. This gives us a point in 3D space for the objects to look at.
- var cam:Camera; //The camera the object(s) will be looking at.
- var planeOffset:float = -1f; //How far away the mouse appears to be from the camera.
- var mouseLocationIndicator:Transform; //An (optional) gameobject used to show the location the object is really looking at.
- function Start() {
- //If the programmer hasn't assigned a camera to cam, try to assign it the
- //Main Camera in the scene. If that fails, then let the user know how to
- //fix the problem, and destroy this script so it doesn't spam error messages
- //into the console.
- if (!cam) {
- if (!Camera.main) {
- Debug.LogError("No Main Camera found. Please either assign a camera, or tag an existing camera as 'Main Camera'.");
- Destroy(this); //Remove the script since it will only cause errors if it continues to run with no camera assigned.
- return;
- }
- cam = Camera.main;
- }
- //Parent the mousePlane to the camera's transform, so they move and rotate together.
- mousePlane.transform.parent = cam.transform;
- //Hide the plane so it doesn't show up in the scene.
- mousePlane.renderer.enabled = false;
- //Offset the plane some distance from the camera to make the objects (eg, eyes) turn more or less to look at the mouse.
- if (planeOffset<0f) {planeOffset=cam.nearClipPlane*2f;}
- mousePlane.transform.position = cam.transform.position + cam.transform.forward * planeOffset;
- //Rotate the plane so its normal points directly towards the camera (so rays cast from the camera will intersect with it).
- mousePlane.transform.up = -cam.transform.forward;
- }
- function Update () {
- //The point underneath the mouse on the screen covers a line in 3D. So we use a Ray
- //(a kind of straight line) intersected with a plane to find the point we want the
- //object(s) to look at.
- var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
- //Find the point of intersection between the ray and the plane.
- var hitinfo:RaycastHit;
- if (Physics.Raycast(ray,hitinfo)) {
- //If there is a point of intersection, make all the objects look at it...
- transform.LookAt(hitinfo.point);
- if (mouseLocationIndicator) {
- mouseLocationIndicator.position = hitinfo.point;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment