|
||||||||||||||||||||||||||||
| ISBN: 3446217274 ISBN: 3446217274 ISBN: 3446217274 ISBN: 3446217274 | ||||||||||||||||||||||||||||
|
|
Wir empfehlen: | |||||||||||||||||||||||||||
How to move a ball
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! import java.awt.*; public class BallApplet extends Applet implements Runnable {
public void start() { } public void stop() { } public void destroy() { } public void run () { } public void paint (Graphics g) { } Threads
You can find more functions of the thread class in the Java API! 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: public void start (){
Thread th = new Thread (this); // start this thread th.start (); 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 (){
Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // run a long while (true) this means in our case "always" while (true) {
repaint(); try {
Thread.sleep (20); catch (InterruptedException ex) {
// set ThreadPriority to maximum value Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
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? {
g.setColor (Color.red); // paint a filled colored circle g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
And we need the following instance variables at the head of the program: { ...
{
x_pos ++; ... 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 Next chapterDouble buffering |
|
|||||||||||||||||||||||||||
|
Back to the topic sites: StudyPaper.com/Startseite/Computer/Informatik/Programmieren/Java StudyPaper.com/Startseite/Computer/Spiele StudyPaper.com/Startseite/Computer External Links to this site are permitted without prior consent. | ||||||||||||||||||||||||||||
| Home | deutsch | Set bookmark | Send a friend a link | Copyright © | Impressum | ||||||||||||||||||||||||||||