Gradually editing the scale of an object
Hello. Excuse me for any grammatical errors.
I'm trying to gradually resize an object and I know how to do this but i'm having some troubles on the scale check, let me explain it better..
I'm using this code to resize the object :
IEnumerator makeObjSmaller()
{
while (transform.localScale != new Vector3 (0.15F, 0.15F, 0.15F)) {
transform.localScale -= new Vector3 (0.01F, 0.01F, 0.01F);
yield return new WaitForSeconds (0.001f);
}
}
The problem here is that the scale will never be equals to (0.15F, 0.15F, 0.15F), I don't know why but after about 10 cicles the scale becomes equal to something like "x.xyzabc" (letters simply are variables).
Assuming that the initial value of the object's scale is (40, 40, 40), during the while cicle it should become something like ( 39.99, 39.98 ... 0.06, 0.05) so only two digits after the comma not 6, it will become something like (0.059584) that's not equal to (0.05).
Answer by Hellium · Aug 09, 2018 at 10:08 PM
Because of the lack of precision when using floating values, relying on comparison is risky. The Vector3
structure has a custom implementation of the !=
operator, but you may not get the desired outcome. Instead, compare the "distance" between the two vectors with a small threshold.
while ((transform.localScale - new Vector3 (0.15F, 0.15F, 0.15F).sqrMagnitude < 0.01f )
Your answer
Follow this Question
Related Questions
Stuck with scaling an object 1 Answer
2D Mobile GUI Scaler 1 Answer
UI Mobile Scaling 1 Answer
2d infinite runner 2 Answers
Change Gravity on falling objects 1 Answer