Guest User

Look At Mouse Simple

a guest
Apr 1st, 2012
1,456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. 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.
  2. var cam:Camera; //The camera the object(s) will be looking at.
  3. var planeOffset:float = -1f; //How far away the mouse appears to be from the camera.
  4. var mouseLocationIndicator:Transform; //An (optional) gameobject used to show the location the object is really looking at.
  5.  
  6. function Start() {
  7.  
  8. //If the programmer hasn't assigned a camera to cam, try to assign it the
  9. //Main Camera in the scene. If that fails, then let the user know how to
  10. //fix the problem, and destroy this script so it doesn't spam error messages
  11. //into the console.
  12. if (!cam) {
  13. if (!Camera.main) {
  14. Debug.LogError("No Main Camera found. Please either assign a camera, or tag an existing camera as 'Main Camera'.");
  15. Destroy(this); //Remove the script since it will only cause errors if it continues to run with no camera assigned.
  16. return;
  17. }
  18. cam = Camera.main;
  19. }
  20.  
  21. //Parent the mousePlane to the camera's transform, so they move and rotate together.
  22. mousePlane.transform.parent = cam.transform;
  23.  
  24. //Hide the plane so it doesn't show up in the scene.
  25. mousePlane.renderer.enabled = false;
  26.  
  27. //Offset the plane some distance from the camera to make the objects (eg, eyes) turn more or less to look at the mouse.
  28. if (planeOffset<0f) {planeOffset=cam.nearClipPlane*2f;}
  29. mousePlane.transform.position = cam.transform.position + cam.transform.forward * planeOffset;
  30.  
  31. //Rotate the plane so its normal points directly towards the camera (so rays cast from the camera will intersect with it).
  32. mousePlane.transform.up = -cam.transform.forward;
  33. }
  34.  
  35. function Update () {
  36.  
  37. //The point underneath the mouse on the screen covers a line in 3D. So we use a Ray
  38. //(a kind of straight line) intersected with a plane to find the point we want the
  39. //object(s) to look at.
  40. var ray:Ray = cam.ScreenPointToRay(Input.mousePosition);
  41.  
  42. //Find the point of intersection between the ray and the plane.
  43. var hitinfo:RaycastHit;
  44. if (Physics.Raycast(ray,hitinfo)) {
  45.  
  46. //If there is a point of intersection, make all the objects look at it...
  47. transform.LookAt(hitinfo.point);
  48.  
  49. if (mouseLocationIndicator) {
  50. mouseLocationIndicator.position = hitinfo.point;
  51. }
  52.  
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment