advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : The Java Game Development Tutorial :

Contents
Introduction
Basic structure of an applet
Move a ball
Double buffering
Ball bouncing and change the direction
Using sound in applets
Using pictures in applets
Mouse events
Keyboard events
The first complete game
Artificial intelligence for a pong like game
Generation of random 2D landscapes

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 very important 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 an object. The structure of the applet should look like this:

import java.applet.*;
import java.awt.*;

public class BallApplet extends Applet implements Runnable
{
    public void init() { }

    public void start() { }

    public void stop() { }

    public void destroy() { }

    public void run () { }

    public void paint (Graphics g) { }

}

Threads
A thread is a piece of program that is able to run parallel 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:

  • Thread.start(): starts a thread
  • Thread.stop(): stops a thread
  • Thread.sleep(time in milliseconds): stops thread for a certain amount of time

You can find more functions of the thread class in the Java API!

And here comes the code!

To move a object we need another object that has to be an instance of the class Thread; we declare this object in the start - method of our applet:

public void start ()
{
    // define a new thread
    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 ()
{
    // lower ThreadPriority
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

    // run a long while (true) this means in our case "always"
    while (true)
    {
      // repaint the applet
      repaint();

      try
      {
        // Stop thread for 20 milliseconds
        Thread.sleep (20);
      }
      catch (InterruptedException ex)
      {
        // do nothing
      }

      // 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?

Well this is a very simple idea: Our circle has a x - and a y - position. If we were to add 1 to the x - position everytime the thread is executed, the ball whould move 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:

public void paint (Graphics g)
{
    // set color
    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:

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:

public void run ()
{
...
    while (true)
    {
      // changing the x - position of the ball/circle
      x_pos ++;

      ...
    }
}

If you add this applet to an HTML document as seen in the previous chapter, a red ball should be moving across the applet one time!

Sourcecode download
Take a look at the applet

Next chapter

Double buffering

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

XML error: undefined entity at line 19
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Linux Vendors Head to the Cloud in Search of Cash
iPhone 3GS: Overheating Fears, OS Update Nears
PostgreSQL 8.4 Revs Up Database Admin, Security
PHP 5.3 Accelerates PHP
Sun Releases NetBeans 6.7 IDE for Java, PHP
Why Firefox Doesn't Take Google Chrome Features
First Major PHP Update in Years Coming Soon
Red Hat CEO Calls on Oracle to Keep Java Open
Google Widens AdSense for iPhone, Android Apps
Eclipse Galileo Releases 33 Open Source Projects

A Taste of JavaFX for the Uninitiated
A Guide to Caching and Compression for High Performance Web Applications
How User-Centered Design Can Put User Stories in Proper Context
Explore C# 4's New Dynamic Types and Named/Optional Parameters
Enterprise Architecture: The Journey Begins Here, Part 2
Create a Syslog Sender/Receiver Using the MS Winsock Control
AMD CodeAnalyst Helps Developers Optimize and Tune Applications
Securing Microsoft's Cloud Infrastructure
Introducing the Azure Services Platform
An Introduction to Microsoft .NET Services for Developers

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs