Search Unity

Smooth Transition 3rd person cam rotating around playe

Discussion in 'Scripting' started by ofayto, Jun 8, 2010.

  1. ofayto

    ofayto

    Joined:
    Mar 12, 2010
    Posts:
    15
    Im currently having trouble in getting 3rd Person camera to work the way I want it to.

    The problems which Im facing:
    1) Smooth transition of camera moving from point A to point B upon user interaction with the mouse click

    2) Camera rotating around the player. In other words, the pivot point is based on the player, and not the camera's pivot. Actually, what I wanted to do is just an Over-The-Shoulder camera effect (when the player hold onto the right-click mouse button, it will switch from the default ThirdPersonCam to Over-The-Shoulder cam)

    Before going further, I would like to highlight that:

    1) For the smooth transition, it seems that the function for moving the camera smoothly with the Lerp seems to be ran. However, that Lerping has been overwrite by the LateUpdate function in the ThirdPersonView's script(Which I'll be showing in a moment).

    2) Camera actually does rotates around the player. However, this can only work when the camera is DIRECTLY behind the player. It does not rotate around the player if the camera has been altered to move a certain distance to the right of the position.x. After trying with the changing of the position.x value, the whole camera just does not rotate around the player.

    Now, there are two scripts in which the first was provided by the kind Unity's community and which has been modified by me. The other script was created for the switching of camera.

    ThirdPersonCam script located in a gameobject called "ThirdPersonCam":


    Code (csharp):
    1. // the target for the camera to orbit around
    2. var target : Transform;
    3.  
    4. // initial distance between the camera and the target
    5. var distance = 5.0;
    6. // min and max distance for zooming
    7. var minDistance = 3.0;
    8. var maxDistance = 10.0;
    9.  
    10. // an offset to stop the camera clipping walls
    11. var offsetFromWall : float = 0.28;
    12.  
    13. // the speed at which the scrollwheel zooms in/out
    14. var zoomRate = 20;
    15.  
    16. // some internal variables to calculate distances
    17. private var currentDistance : float;
    18. private var desiredDistance : float;
    19. private var correctedDistance : float;
    20.  
    21. // speed of camera rotation around the object in both axes and smoothing for rotation
    22. var xSpeed : float = 200.0;
    23. var ySpeed : float = 200.0;
    24. var rotationDampening : float = 3.0;
    25.  
    26. // the min and max rotation limits of the camera in the y-axis (up and over the object) and smoothing for zooming
    27. var yMinLimit : int = 0;
    28. var yMaxLimit : int = 80;
    29. var zoomDampening : float = 5.0;
    30.  
    31. // variables to store the rotation of the camera
    32. private var x  : float = 0.0;
    33. private var y : float = 0.0;
    34.  
    35. // variables for zooming axis limit
    36. public var yMinLimitZoomed: float = 0.00;
    37. public var yMaxLimitZoomed: float = 0.00;
    38.  
    39. // adds a menu option to attach this script via the Component Menu
    40. @script AddComponentMenu("Camera-Control/Mouse Orbit")
    41.  
    42.  
    43. function Start () {
    44.    // store the initial rotation of the camera on the x and y axes
    45.     var angles = transform.eulerAngles;
    46.     x = angles.y;
    47.     y = angles.x;
    48.  
    49.    // set zoom distances to the value of the initial distance
    50.    currentDistance = distance; //Original distance uses the variable called "distance"
    51.    desiredDistance = distance;
    52.    correctedDistance = distance;
    53.    
    54.    // Make the rigid body (if there is one) not change rotation
    55.       if (rigidbody) {
    56.       rigidbody.freezeRotation = true;
    57.    }
    58. }
    59.  
    60. // LateUpdate is called every frame after all other updates have happened
    61. //(preferable for camera follows since all objects should have already moved)
    62. function LateUpdate () {
    63.    
    64.    // if a target has been assigned (drag and drop one in the editor)
    65.    if (target) {
    66.       // if there is input on the vertical or horizontal axes (default is arrow keys and wasd)
    67.       if(Input.GetAxis("Vertical") || Input.GetAxis("Horizontal")) {
    68.          // store the current y-axis rotation of the target and the camera
    69.          var targetRotationAngle = target.eulerAngles.y;
    70.          var currentRotationAngle = transform.eulerAngles.y;
    71.          // interpolate between the current y-axis rotation and the target y-axis rotation over time
    72.          // setting the changing value to the x-axis rotation so the camera rotates around behind the PC
    73.          x = Mathf.LerpAngle(currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);
    74.          
    75.          ////////////////////////
    76.          //EDITTED VERSION//
    77.          ////////////////////////
    78.          x += Input.GetAxis("Mouse X") * xSpeed * 0.001;//EDITED VERSION,. DO REMOVE IF NOT WORKING
    79.          y -= Input.GetAxis("Mouse Y") * ySpeed * 0.01;//EDITED VERSION,. DO REMOVE IF NOT WORKING
    80.          
    81.       // if there is no input from the vertical/horizontal axes (we are not moving)
    82.       } else {
    83.          // allow the player to rotate the camera using the mouse by updating the camera's
    84.          // x/y rotation values based on the mouse position
    85.          x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
    86.          y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
    87.       }
    88.      
    89.          
    90.       // set the y-axis rotation value based on the result of the ClampAngle function
    91.       y = ClampAngle(y, yMinLimit, yMaxLimit);
    92.      
    93.       // store the camera's rotation
    94.        var rotation = Quaternion.Euler(y, x, 0);
    95.      
    96.      
    97.       // convert input from the scrollwheel into zooming between the min/max distance ranges
    98.       //desiredDistance -= Input.GetAxis ("Mouse ScrollWheel") * Time.deltaTime * zoomRate * Mathf.Abs (desiredDistance); //Disabled zooming feature, so that the mouse scroll is used for striking matches
    99.       desiredDistance = Mathf.Clamp (desiredDistance, minDistance, maxDistance);
    100.       correctedDistance = desiredDistance;
    101.      
    102.       // store the camer's position
    103.       var position = target.position - (rotation * Vector3.forward * desiredDistance);
    104.      
    105.       // a variable to hold a reference to raycast collision objects
    106.       var hit : RaycastHit;
    107.       // a variable to hold a flag so we know if we have already corrected the camera's position
    108.       var isCorrected : boolean = false;
    109.       // if a ray between the target and the desired position hits something then their must be something blocking the line of sight
    110.         if (Physics.Linecast (target.position, position, hit)) {
    111.             // shorten the distance between the camera and the target using the distance to the wall
    112.             // minus an offset to prevent clipping
    113.             correctedDistance = Vector3.Distance (target.position, hit.point) - offsetFromWall;
    114.             // we have corrected the camera's position
    115.             isCorrected = true;
    116.       }
    117.  
    118.       // if we haven't corrected the camera's position or the new distance is greater than the current distance
    119.       if(!isCorrected || correctedDistance > currentDistance){
    120.       // interpolate the distance of the camera from the target between the current distance and the corrected distances
    121.       // (ie. in front of the wall that is blocking our view)
    122.            
    123.          currentDistance = Mathf.Lerp (currentDistance, correctedDistance, Time.deltaTime * zoomDampening);
    124.          
    125.       }
    126.       // set our current distance to this new distance
    127.       currentDistance = correctedDistance;
    128.          
    129.       // clamp this value between the minimum and maximum distance settings
    130.       currentDistance = Mathf.Clamp(currentDistance, minDistance, maxDistance);
    131.      
    132.       // store the new position
    133.       position = target.position - (rotation * Vector3.forward * currentDistance);
    134.      
    135.         //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    136.         //FOR UPDATING THE CAMERA MOVEMENT. THE MAIN CODING THAT AFFECTS THE LOCKING OF THE POSITION AND THE ROTATION OF THE GAMEOBJECT//
    137.         /////////////////////////////////////////////////This is just purely for switching between views, FPS and TPV modes//////////////////////////////////////////////////
    138.         /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    139.         var locateThirdPersonCam = gameObject.Find("ThirdPersonCam");
    140.        
    141.         //If right click is not down,  the camera is in TPV mode
    142.         if (!Input.GetKey(KeyCode.Mouse1))
    143.         {          
    144.             // set the current rotation and position of the camera to the new values to make it move
    145.             transform.rotation = rotation;
    146.             transform.position = position; //NOTICE, THIS IS THE CODE THAT IS OVERWRITING THE LERP ANIMATION~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    147.         }
    148.        
    149.         //If right click is down, the camera is in FPS mode
    150.         if (Input.GetKey(KeyCode.Mouse1))
    151.         {  
    152.             //transform.rotation = rotation;
    153.             //transform.position = position;
    154.             y = ClampAngle(y, yMinLimitZoomed, yMaxLimitZoomed);
    155.             rotation = Quaternion.Euler(y, x, 0);
    156.             transform.rotation = rotation;
    157.         }
    158.    }
    159. }  
    160.  
    161. // keeps the value of the y-axis rotation within 360 degrees (it would cause an error otherwise)
    162. // and within the minimum and maximum limits previously defined
    163. static function ClampAngle (angle : float, min : float, max : float) {
    164.    if (angle < -360)
    165.       angle += 360;
    166.    if (angle > 360)
    167.       angle -= 360;
    168.    return Mathf.Clamp (angle, min, max);
    169. }
    switchCamView script located in a gameobject called "ThirdPersonCam":

    Code (csharp):
    1. public var transSpeed: int = 0;
    2. public var switchShootView = false;
    3. public var targetFPSDestination: Transform;
    4. public var targetTPVDestination: Transform;
    5. public var speedAdjuster: int = 0;
    6.  
    7. private var retrievePos = false;
    8.  
    9. //////////////////////
    10. ///Position Updater///
    11. /////////////////////
    12. private var oldPosX: float = 0.00;
    13. private var oldPosY: float = 0.00;
    14. private var oldPosZ: float = 0.00;
    15.  
    16. private var newPosX: float = 0.00;
    17. private var newPosY: float = 0.00;
    18. private var newPosZ: float = 0.00;
    19.  
    20. private var currentPosX: float = 0.00;
    21. private var currentPosY: float = 0.00;
    22. private var currentPosZ: float = 0.00;
    23.  
    24. function Awake()
    25. {
    26.     positionOld = transform.position;
    27. }
    28.  
    29. function Update()
    30. {
    31.     switchCamera();
    32.    
    33.     if (Input.GetKey(KeyCode.Mouse1))
    34.     {
    35.         switchShootView = true;
    36.     }
    37.    
    38.     else if (!Input.GetKey(KeyCode.Mouse1))
    39.     {
    40.         switchShootView = false;
    41.     }
    42. }
    43.  
    44. function switchCamera()
    45. {          
    46.     var locateThirdPersonCam = GameObject.Find("ThirdPersonCam");
    47.    
    48.     //goes into FPS mode
    49.     if(switchShootView)
    50.     {
    51.         retrievePos = true;
    52.        
    53.         //Retrieve position
    54.         if(retrievePos)
    55.         {
    56.             oldPosX = transform.position.x;
    57.             oldPosY = transform.position.y;
    58.             oldPosZ = transform.position.z;
    59.            
    60.             newPosX = targetFPSDestination.position.x;
    61.             newPosY = targetFPSDestination.position.y;
    62.             newPosZ = targetFPSDestination.position.z;
    63.            
    64.             retrievePos = false;
    65.         }
    66.        
    67.         transform.position.x = Mathf.Lerp(oldPosX, newPosX, Time.deltaTime * speedAdjuster);
    68.         transform.position.y = Mathf.Lerp(oldPosY, newPosY, Time.deltaTime * speedAdjuster);
    69.         transform.position.z = Mathf.Lerp(oldPosZ, newPosZ, Time.deltaTime * speedAdjuster);       
    70.     }
    71.    
    72.     //goes into normal TPV mode
    73.     if (!switchShootView)
    74.     {
    75.         hasClicked = false;
    76.         retrievePos = true;
    77.        
    78.         //Retrieve position
    79.         if(retrievePos)
    80.         {
    81.             oldPosX = transform.position.x;
    82.             oldPosY = transform.position.y;
    83.             oldPosZ = transform.position.z;
    84.            
    85.             newPosX = targetTPVDestination.position.x;
    86.             newPosY = targetTPVDestination.position.y;
    87.             newPosZ = targetTPVDestination.position.z;
    88.            
    89.             retrievePos = false;
    90.         }
    91.        
    92.         transform.position.x = Mathf.Lerp(oldPosX, newPosX, Time.deltaTime * speedAdjuster);
    93.         transform.position.y = Mathf.Lerp(oldPosY, newPosY, Time.deltaTime * speedAdjuster);
    94.         transform.position.z = Mathf.Lerp(oldPosZ, newPosZ, Time.deltaTime * speedAdjuster);
    95.     }
    96. }
    Thanks in advance guys!
     
  2. sandolkakos

    sandolkakos

    Joined:
    Jun 3, 2009
    Posts:
    285
  3. ofayto

    ofayto

    Joined:
    Mar 12, 2010
    Posts:
    15
    @sandolkakos: That's just the script for making a third person camera.

    As Ive stated in my previous post, I have a third person camera script that is working (was provided by the Unity forum too). Ive tweaked it to work in the way I want them too. However, the result is not quite good.

    In any case, thanks for trying to help sandolkakos.

    Once again, just to highlight the problems again, I'll quote a few lines from my previous post.

    Sorry for the long codes posted. Ive been trying to figure out the camera scripts for almost a week now, but to no avail...

    Thanks in advance Guys!!
     
  4. ofayto

    ofayto

    Joined:
    Mar 12, 2010
    Posts:
    15
    Bumped...sorry for bumping but...Im really getting more and more desparate...Im going insane soon...its really hard to solve :(
     
  5. Zydin

    Zydin

    Joined:
    Jan 16, 2010
    Posts:
    1
    Before rotating, update the camera position to the player position, rotate it, then just back it up along that same angle the same distance it was before. Then render. I'm more of a C# guy and not a JS, but if you need an example I can try.