Search Unity

Resolved Why does Quaternion not rotate to my desired position?

Discussion in 'Scripting' started by JialeHe28, Mar 15, 2023.

  1. JialeHe28

    JialeHe28

    Joined:
    Sep 16, 2022
    Posts:
    9
    I have a script that rotates a platform a set amount of degrees after an x amount of time and after reaching my desired rotation, and after checking if it has reached my desired rotation, it restarts the timer and sets a new desired rotation. The problem is that even though it works fine when I set the rotation degrees to 90, at other values like 45 when it seemingly reaches my desired position, unity returns false.

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class PlataformasGiratorias : MonoBehaviour
    7. {
    8.     private float _Timer = 0f;
    9.     private float _initialrotation;
    10.     [SerializeField]private float _DesiredRotation; //The degrees I want the platform to rotate.
    11.     [SerializeField]private float _rotationSpeed;
    12.     [SerializeField]private float _setTime = 3;  //The amount of time between rotations.
    13.  
    14.     private void Start()
    15.     {
    16.         _initialrotation=_DesiredRotation;
    17.     }
    18.     void Update()
    19.     {
    20.        
    21.         Debug.Log(transform.rotation.eulerAngles.z);
    22.         Debug.Log(transform.rotation.eulerAngles.z + "  " + _DesiredRotation);
    23.         _Timer += Time.deltaTime;
    24.  
    25.         if (_Timer > _setTime)
    26.         {
    27.  
    28.             transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.Euler(0, 0, _DesiredRotation), _rotationSpeed * Time.deltaTime);
    29.  
    30.             if (transform.rotation.eulerAngles.z == _DesiredRotation)
    31.  
    32.             {
    33.                 _DesiredRotation = (_DesiredRotation + _initialrotation) % 360;
    34.                 _Timer = 0;
    35.             }
    36.         }
    37.     }
    38. }
    39.  
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,853
    I would suggest looking up floating point precision (or imprecision).

    This line:
    Code (CSharp):
    1. if (transform.rotation.eulerAngles.z == _DesiredRotation)
    Two floating point numbers are highly unlikely to be exactly accurate. In instances like these, you should use
    Mathf.Approximately
    , or anything that checks if it's 'roughly' close to its intended orientation.
     
  3. JialeHe28

    JialeHe28

    Joined:
    Sep 16, 2022
    Posts:
    9
    Thanks!
     
    spiney199 likes this.