Search Unity

rotation issue

Discussion in 'Scripting' started by Mister-D, Jan 31, 2015.

  1. Mister-D

    Mister-D

    Joined:
    Dec 6, 2011
    Posts:
    1,694
    i ve got a rotationscript that rotates the player around y axis, when climbing a ladder i disable the script to rotate the player towards the ladders z direction, the problem is when enabling the player rotationscript again it starts rotating to the last "known" rotation again before it was disabled. i dont want this to happen, so how do i set the rotationscript to have the rotation from when the climb has ended? and not its last rotation before it was disabled?
    script:
    Code (JavaScript):
    1. var smoothSpeed : float = 2;
    2. private var sensitivityX : float = 6;
    3. var aimSens : float = 2;
    4. var normalSens : float = 6;
    5. private var rotationX : float = 0;
    6. private var startrotation : Quaternion;
    7.  
    8. function Start()
    9. {
    10.     startrotation = transform.rotation;
    11. }
    12. function FixedUpdate ()
    13.  
    14. {
    15.             if (Input.GetButton("Fire3"))
    16.             {
    17.                 sensitivityX = aimSens;
    18.             }
    19.             else
    20.             {
    21.                 sensitivityX = normalSens;
    22.             }
    23.             rotationX += Input.GetAxis("Mouse X") * sensitivityX;
    24.            
    25.             var xQuaternion : Quaternion = Quaternion.Euler(0,rotationX,0);
    26.            
    27.             transform.rotation = Quaternion.Slerp(transform.rotation, xQuaternion,Time.deltaTime * smoothSpeed);
    28.  
    29. }
     
  2. CasperCoder

    CasperCoder

    Joined:
    Jul 29, 2012
    Posts:
    13
    So you are caching the state of the players rotation in the "rotationX" variable, which isn't updated when this script is disabled. There are two ways around this.

    Option 1) You can get rid of "rotationX" and instead just apply rotation to transform.rotation directly ie:
    var turn :float = Input.GetAxis("Mouse X")* sensitivityX * Time.deltaTime* smoothSpeed;
    var xQuaternion : Quaternion = Quaternion.Euler(0,turn,0);
    transform.rotation = xQuaternion * transform.rotation;

    Option 2) You update the rotationX in an OnEnable method ie:
    function OnEnable()
    {
    rotationX = rotation.eulerAngles.y;
    }

    I always tend to favor Option 1 just because it means you aren't storing rotation state in multiple places, which can get out sync when (as in this case) state of the object is modified elsewhere.

    Hope that helps
     
    Mister-D likes this.
  3. Mister-D

    Mister-D

    Joined:
    Dec 6, 2011
    Posts:
    1,694
    tnx alot it works now the rotation doesnt snap to previous position :)