I’m practicing some simple 2D game programming, and came up with a theory that during animation (the actual change in a image position is best calculated with floating point numbers). I have a feeling that if you move an image around with ints the animation won’t be as smooth.
In Java it seems you can’t draw an image with floating point numbers to give an image a position. But apparently when you initially declare your x and y ‘s, you can declare them as Double, or Float, and when it comes to actually drawing the image you have to cast them to ints. Like I find HERE :
/**
* Draw this entity to the graphics context provided
*
* @param g The graphics context on which to draw
*/
public void draw(Graphics g) {
sprite.draw(g,(int) x,(int) y);
}
My question is about how Java handles the conversion?
If the code casts these doubles at the last minute, why have them as doubles in the first place?
Does Java hide the numbers after the decimal?
I know in C and C++ the numbers after the decimal get cut off and you only see whats before it. How does Java handle this casting?
Pixels on a display are discrete and limited in number; therefore display coordinates need to be integer numbers – floating point numbers make no sense, as you do not physically have a pixel at e.g.
(341.4, 234,7).That said, integers should only be used at the final drawing stage. When you calculate object movement, speeds etc, you need to use floating point numbers. Integers will cause an amazing number of precision problems. Consider the following snippet:
If
aandxare floating point numbers,xwill finally have the expected number of1. If they are integers, you will get0.Baseline: use floating point types for physics computations and convert to
intat drawing time. That will allow you to perform the physics calculations with as much precision as required.EDIT:
As far as the conversion from FP numbers to integers is concerned, while FP numbers have a greater range, the values produced by your physics calculation after normalization to your drawing area size should not normally overflow an
inttype.That said, Java truncates the floating point numbers when converting to an integer type, which can create artifacts (e.g. an animation with no pixels at the rightmost pixel column, due to e.g.
639.9being converted to639rather than640). You might want to have a look atMath.round()or some of the other rounding methods provided by Java for more reasonable results.