0
votes

(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?

2
I think you should take a look at [this][1] thread [1]: stackoverflow.com/questions/2100490/…steven35
if (position.x <= -70) { Floating point is not precise, so == is dangerous.Joop Eggen
Better to show how position is defined.KKKCoder

2 Answers

3
votes

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);
}
1
votes

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");
}