unity3d - Why comparing float values is such difficult? -


i newbie in unity platform. have 2d game contains 10 boxes vertically following each other in chain. when box goes off screen, change position above of box @ top. chain turns infinitely, repeating parallax scrolling background.

but check if box goes off screen comparing position specified float value. sharing code below.

void update () {     offset = currentsquareline.transform.position;     currentsquareline.transform.position = new vector2 (0f, -2f) + offset;      vector2 vectorone = currentsquareline.transform.position;     vector2 vectortwo = new vector2 (0f, -54f);      if(vectorone.y < vectortwo.y) {         string name = currentsquareline.name;         int squarelinenumber = int.parse(name.substring (11)) ;         if(squarelinenumber < 10) {             squarelinenumber++;         } else {             squarelinenumber = 1;         }         gameobject squarelineabove = gameobject.find ("square_line" + squarelinenumber);          offset = (vector2) squarelineabove.transform.position + new vector2(0f, 1.1f);         currentsquareline.transform.position = offset;     } } 

as can see, when compare vectorone.y , vectortwo.y, things ugly. boxes lengthen , boxes shorten distance between each other give exact vector values in code above.

i've searched solution week, , tried lots of codes mathf.approximate, mathf.round, none of them managed compare float values properly. if unity never compares float values in way expect, think need change way.

i waiting godlike advices, thanks!

edit

here screen. have 10 box lines vertically goes downwards.

screen structure

when square_line10 goes off screen. update position above of square_line1, distance between them increases unexpectedly.

okay, found solution works charm.

i need use array , check them in 2 loops. first 1 moves boxes , second 1 check if box went off screen below

public gameobject[] box; float boundary = -5.5f; float boxdistance = 1.1f; float speed = -0.1f;  // update called once per frame void update () {     (int = 0; < box.length; i++) {         box[i].transform.position = box[i].transform.position + new vector3(0, speed, 0);     }      (int = 0; < box.length; i++)     {         if(box[i].transform.position.y < boundary)         {             int topindex = (i+1) % box.length;              box[i].transform.position = new vector3(box[i].transform.position.x, box[topindex].transform.position.y + boxdistance, box[i].transform.position.z);             break;         }     } } 

i attached maincamera.


Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -