More accurate movement in graphics

When we start to do graphics we use ints for what we draw on the screen because pixels are integers. However, this soon become a problem because of its limitations:

Simple code: position and speeds are int

Consider the following code:

class Ball {
	int x,y;	//position
	int vx, vy;	//speed

	Ball(){
		//Do something in the constructor to set the position and speeds.
		vx = 2;
		vy = 3;
	}

	void move() {
		x += vx;
		y += vy;

		//needs to bounce off edges

		//needs to check for collisions
	}

The smallest amount that the ball can move is one pixel per cycle. However, if we're using gravity, or if we're doing our animation loop rapidly, it will need to move less than one pixel per cycle. How do we do this?

Better code: position and speeds are double

class Ball {
	int x,y;	//position
	double xx, yy;	//double versions of the position
	double vx, vy;	//speed
	int r = 30;		//radius

	static final g = 0.01;	//gravity

	Ball(){
		//Do something in the constructor to set the position and speeds.
		vx = 2.0;
		vy = 0.8;
	}

	void move() {

		vy = vy + g;

		xx += vx;
		yy += vy;

		//needs to bounce off edges

		//needs to check for collisions

		x = (int)xx;
		y = (int)yy;
	}

What we do is have speeds and position variables that are double.
Notice that the radius can still be an int. There's no strong reason to make it a double.

Then all calculation of position, changes in speed, etc. are always using the double variables, and once we've finished all our calculations, we cast the doubles to integers so that they can be plotted on the screen. The screen does require ints since pixels are always ints.

Remember to write vx = 2.0; instead of just vx = 2; when you're using doubles.