Question by
hobocampus · Oct 13, 2015 at 01:11 AM ·
transformlocalscale
Unwanted Decimal Value When Scaling Object
var player : Transform;
function OnMouseOver ()
{
if(Input.GetButtonDown("Fire1"))
{
transform.localScale += new Vector3(0F, .1F, 0);
}
if(Input.GetButton("Fire2") && transform.localScale.y > .1f)
{
transform.localScale += new Vector3(0F, -.1F, 0);
}
}
I'm using this script to increase scale on object by .1 when I left click and decrease scale by .1 when I right click. When the object's scale gets above 2.7, it goes to 2.799999 instead of 2.8. Why is this happening and is there a way to prevent it from doing so?
Comment
Best Answer
Answer by dkjunior · Oct 13, 2015 at 03:33 AM
This is an inherent problem of floating-point operations. In most cases it shouldn't affect the logic/behavior. It does, however, creates problems when you need to compare two floating-point values (as 2.8 won't match 2.799999). Standard approach for these situations is to check whether two values are very close to each other (as opposed to checking for exact equality):
float a = 2.799999;
float b = 2.8;
bool equal = Mathf.Abs(a - b) < 1e-3f;