- Home /
Precision problem when moving Rect values
So I'm having a hard time making sure my Rect.x position always ends up at 0. It's always higher or lower, and if I use Mathf.RoundToInt, I get random values like 1, -2, 0, -3, 2, -1....
Here's my code below:
public IEnumerator SlideScreen( RectValues mainRect, int speed, int xPos, bool slideLeft ) {
// Mathf.RoundToInt force the posX to end-up with a rounded value (eg; 0 instead of 0.2562)
// This is important when sliding the screen back to 0, to make sure it always ends-up at 0.
if( !slideLeft )
{
// Move Rect right until it reaches its destination
while( mainRect.posX < xPos )
{
mainRect.posX += Mathf.RoundToInt( ( speed * Time.deltaTime * 10 ) );
yield return null;
}
}
else
{
// Move Rect left until it reaches destination
while( mainRect.posX > -xPos )
{
mainRect.posX -= Mathf.RoundToInt( ( speed * Time.deltaTime * 10 ) );
yield return null;
}
}
}
What I do with this code is move my Rect.x position to 150, then back to 0. As I said, the problem is that I can never guaranty Rect.x position to be 0 everytime, it jumps between +1 2 3 and -1 2 3
How can I force it to be 0 everytime? Thanks for your time!
Answer by aldonaletto · May 31, 2011 at 03:06 AM
Just force Rect.x to the desired position right after the final loop, like this:
// Move Rect left until it reaches destination
while( mainRect.posX > -xPos )
{
mainRect.posX -= Mathf.RoundToInt( ( speed * Time.deltaTime * 10 ) );
yield return null;
}
mainRect.posX = -xPos; // <--add this line
}
}
Thanks guys, exactly what I was looking for! Both your help is greatly appreciated.
Answer by Molix · May 31, 2011 at 03:09 AM
I'd probably just do:
while( mainRect.posX > -xPos )
{
yield return null;
mainRect.posX -= ( speed * Time.deltaTime * 10 );
}
mainRect.posX = -xPos;
That way you'll check it immediately after changing it, and if it is bad you'll clamp it before yielding and using the bad value elsewhere.