- Home /
Why my rotation gets different values?
Hello I've started using unity 2 months ago. Did some small games now I am trying to make a rotation puzzle game. The game itself is done. However I wanted to save the last rotation of the pieces and wrote this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UltimateRotationSaver : MonoBehaviour
{
public float picRot;
public void Awake()
{
//get z rotation if there is none get a random *90 rotation
picRot = PlayerPrefs.GetFloat(GetComponent<SpriteRenderer>().sprite.name, Random.Range(0, 4) * 90);
Debug.LogWarning("Start Rotation" + transform.eulerAngles.z);
}
void Start()
{
//use picRot of the Awake
transform.rotation = Quaternion.Euler(0, 0, picRot);
}
private void OnMouseDown()
{
//On click save
PlayerPrefs.SetFloat(GetComponent<SpriteRenderer>().sprite.name, transform.eulerAngles.z);
Debug.LogWarning("Current Rotation" + transform.eulerAngles.z);
}
}
So the problem is... SOMETIMES just sometimes not always, my game can not be completed. I've used Debug.Log to see why, and realized that SOMETIMES I get "9,659347E-06" instead of "0" when the picture is in the right angle. So game can not end because all z rotations are not equals to zero.
I could not figure out what should I do. Tried using rounding the float values, it did fix the debug notifications but not the game itself maybe it is because I've used it wrong. In the end I am not even sure why it happens but my guess is "transform.rotation = Quaternion.Euler(x, y, z)"
also if needed... this is the code that rotates the pictures:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchRotate : MonoBehaviour
{
private void OnMouseDown()
{
if (!Game.youWin)
transform.Rotate(0f, 0f, 90f);
}
}
Answer by Captain_Pineapple · Jul 20, 2020 at 05:42 PM
well yes this is one of the fundamental issues when calculating with floats or doubles.
(A * B) / B can result in a slightly different number then A. So if you want to check for some value you should use some epsilon approximation.
So instead of if(value == 0)
you should check: if(Mathf.Abs(value) < 0.05)
This way you can be sure that the desired value is reached to an "acceptable level"
I will run and try it in a few $$anonymous$$utes. Thank you very much for your answer =)
Edit: I've tried. Worked like a charm. Thank you again
To expand on @Captain_Pineapple's answer, UConn's What Every Programmer Should Know About Floating-Point Arithmetic is an excellent resource for more info on floating point numbers. It explains why you need to check for nearly-equal instead of exactly equal, etc.