Guest User

Look At Mouse

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