Guest User

Rotate an object using the mouse in Unity3D

a guest
Mar 20th, 2012
6,982
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //How quickly to rotate the object.
  2. var sensitivityX:float = 15;
  3. var sensitivityY:float = 15;
  4.  
  5. //Camera that acts as a point of view to rotate the object relative to.
  6. var referenceCamera:Transform;
  7.  
  8. //The script in Start() is executed before Update(), so we can use it to
  9. //doublecheck our variables have valid values before we try to run the script in Update().
  10. function Start() {
  11.  
  12.     //Ensure the referenceCamera variable has a valid value before letting this script run.
  13.     //If the user didn't set a camera manually, try to automatically assign the scene's Main Camera.
  14.     if (!referenceCamera) {
  15.         if (!Camera.main) {
  16.             Debug.LogError("No Camera with 'Main Camera' as its tag was found. Please either assign a Camera to this script, or change a Camera's tag to 'Main Camera'.");
  17.             Destroy(this);
  18.             return;
  19.         }
  20.         referenceCamera = Camera.main.transform;
  21.     }
  22. }
  23.  
  24. //Update() is called once every frame, and should be used to run script that
  25. //should be doing something constantly. In this case, we potentially want to
  26. //rotate the object constantly if the user is always moving the mouse.
  27. function Update () {
  28.  
  29.     //Get how far the mouse has moved by using the Input.GetAxis().
  30.     var rotationX:float = Input.GetAxis("Mouse X") * sensitivityX;
  31.     var rotationY:float = Input.GetAxis("Mouse Y") * sensitivityY;
  32.  
  33.     //Rotate the object around the camera's "up" axis, and the camera's "right" axis.
  34.     transform.RotateAroundLocal( referenceCamera.up     , -Mathf.Deg2Rad * rotationX );
  35.     transform.RotateAroundLocal( referenceCamera.right  ,  Mathf.Deg2Rad * rotationY );
  36.  
  37. }
Advertisement
Add Comment
Please, Sign In to add comment