We want to start with a very essential step. We will program an applet in which a ball is moving from the left to the right hand side. I know this is nothing BIG but if you want to learn how to program games it is maybe the most important thing to understand how to animate objects!
At the beginning we have to write our basic structure of an applet again but we will add two little things. Our applet has to implement the interface Runnable and the corrosponding method run() to animate a object. The structure of the applet should look like this:
To move a object we need an other object that has to be a instance of the class Thread, we declare this object in the start - method of our applet:
Threads
A thread is a piece of program that is able to run paralell to other parts of the program (multithreading). Threads are implemented by the class Thread, the interface Runnable and the method run(), we have already implemented these two things in the step before. Important methods of the class Thread are:
You can find more functions of the thread class in the Java API!
And here comes the code!
Now this thread is running in the run() - method of our applet. Every time all methods... in the run - method have been called, we stop the thread for a short time. Your run method should look like this:
public void run ()
What we have now is a neverending loop that executes all things within the loop, waits 20 milliseconds and executes everything once again and so on. But how can we move a circle that is painted by the applet?
Well this is a very simple idea: Our circle has a x - and a y - position. If we would add 1 to the x - position everytime the thread executed, the ball should be moving across the applet, because it is painted at a different x - position everytime we execute the thread!
Ok, let's start with drawing a circle: Add these lines to the paint - method of the applet:
And we need the following instance variables at the head of the program:
int x_pos = 10;
int y_pos = 100;
int radius = 20;
To move a ball we change the value of the x_pos variable everytime the thread is executed. Our run - method should look like this:
If you add this applet to a HTML - document as seen in the chapter before, a red ball should be moving across the applet one times!
Sourcecode download
Take a look at the applet