I'm making a game, in which I am setting a location with a float, the problem is the float isn't going higher them 255? This is how I'm making the float go higher: 1. add method:
public Location add(float x, float y, float z){
this.x += x; this.y += y; this.z += z;
return this;
}
2. update method
public void update(){
float speed = 0.00001f;
float rotspeed = 0.00001f;
if (Keyboard.isKeyDown(Keyboard.KEY_UP)) Main.renderer.rotate(-rotspeed, 0, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) Main.renderer.rotate(rotspeed, 0, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) Main.renderer.rotate(0, rotspeed, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) Main.renderer.rotate(0, -rotspeed, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_W)) Main.renderer.renderLocation.add(0, 0, speed);
if (Keyboard.isKeyDown(Keyboard.KEY_S)) Main.renderer.renderLocation.add(0, 0, -speed);
if (Keyboard.isKeyDown(Keyboard.KEY_D)) Main.renderer.renderLocation.add(-speed, 0, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_A)) Main.renderer.renderLocation.add(speed, 0, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) Main.renderer.renderLocation.add(0, -speed, 0);
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) Main.renderer.renderLocation.add(0, speed, 0);
fixRenderRotation();
}
The update is being called in a while loop in a child thread.
This is what I'm using the float for
public void update(){
System.out.println("render_location "+renderLocation.x+" "+renderLocation.y+" "+renderLocation.z+" rotation "+rotation.x+" "+rotation.y+" "+rotation.z);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glLoadIdentity();
GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
//GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
GL11.glRotatef(rotation.x, 1F, 0F, 0F);
GL11.glRotatef(rotation.y, 0F, 1F, 0F);
GL11.glRotatef(rotation.z, 0F, 0F, 1F);
((RenderObject.UnknownRenderInformation) collection.getRenderInformation()).act();
}
It's the renderLocaiton
variable.
I am not stopping it from going higher.
float
only has ~6 digits of accuracy. I suggest using an int
and dividing by 100,000 or using a double
When you add 1e-5f
to 256f
the answer is 256f
as this is closest represent-able value. You have the same problem with double but at a much higher point. If you add 1e-5
to 137438953472
the same thing will happen as you are working beyond the precision of a double
.
If you use an int you will a different problem. Add 1
to 2147483647
and the int
will overflow to -2147483648
BTW You have a problem with float before you reach 256. Due to representation error 128f + 1e-5f == 128.00002
which I suspect is not what you intended.
In fact if you keep adding 1e-5f it will only takes 65536 times to increment between integer value/whole numbers instead of the 100,000 you might have expected.
It is useful to know the limits of your types.