0

(libGDX, Java) I'm trying to make an object move from one side of the screen to the other and when it reach the other side it start over. The code I use for the action:

if (position.x < 300) {
position.x -= 1;
}
if (position.x == -70) {
position.x = 131;
}

position is a Vector2. 1 is the movement speed of the object and where I have the problem. The loop work fine if the position.x -= A WHOLE NUMBER, but if I want it to be 0.3f, 1.5f... the loop won't work and the object just continue moving. How can if fix it so that the loop will work with any number?

3
  • I think you should take a look at [this][1] thread [1]: stackoverflow.com/questions/2100490/… Commented Nov 4, 2014 at 18:13
  • 2
    if (position.x <= -70) { Floating point is not precise, so == is dangerous. Commented Nov 4, 2014 at 18:13
  • Better to show how position is defined. Commented Nov 4, 2014 at 18:14

2 Answers 2

3

It's so because of the binary representation of floating numbers. Every integer (not too big) has its own representation as a binary number. But 0.3 doesn't have it's accurate representation.

http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm

When comparising floats use:

bool equal(float actual, float expected) {
  return (abs(actual - expected) < 0.000001);
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3395989 If you want more information, go to this site, type in 0.3 and click float.
1

You can use Float.floatToIntBits().

Float.floatToIntBits(position.x) == Float.floatToIntBits(-70)

Here another example :

Float fObj1 = new Float("5.35");
Float fObj2 = new Float("5.34");

int i2 = fObj1.compareTo(fObj2);

if(i2 > 0){
  System.out.println("First is grater");
}else if(i2 < 0){
  System.out.println("Second is grater");
}else{
  System.out.println("Both are equal");
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.