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

Randomize the movement direction of the two balls

As I said in the second chapter, we will move our ball in this game not only in the x - direction but in the y - direction, too. To do this we have to add a y_speed vector to the applet as well as the x_speed vector you already know. Our ball will have an x_pos variable which will be changed with every call of move() by adding the value of x_speed to it; (remenber: x_speed can be negative), and our ball will also have a y_pos variable which will be changed by adding y_speed. In our game the value of y_speed will not be changing. The first ball will be moving up (y_speed = -1) and the other ball will be movind down (y_speed = 1). Be careful, in Jave the y - coordinates get bigger when moving down!! The value of x_speed will be chosen at random everytime a ball left the applet.

Random number generator

First of all we need a random generator in Java. We have to import the class java.util.*; into the class Ball and declare the following instance variable afterwards:

    Random rnd = new Random ();

Now we can generate a random integer number by calling rnd.nextInt(). Because we want to have values between -3 and +3 in our game, we have to calculate this random number mod 4 afterwards.

Now we can randomize the movement direction of the ball. We have to set the value of x_speed to a new random value, everytime the ball is hit or the ball leaves the applet area.

The move() - method of the ball object

First of all we have to declare four instance variables (x_speed, y_speed, x_pos, y_pos) and initialize them in the constructor of our ball object. Everytime move() is called we add the value of x_speed to the x_pos variable and the value of y_speed to the y_pos variable. Everytime the ball is hit or has left the applet, we initialize x_speed with a random generated value, y_speed will be constant. Here comes the code:

    public void move()
    {
      // Add values of y and x_speed to x and y position
      pos_x += x_speed;
      pos_y += y_speed;

      /* Call isOut() and test if ball is still within the applet area */
      isOut();
    }
The method isOut()

This method tests if a ball has left the applet. If one of the four if - statements is true, the position of the ball will be reset, an audio file will be played, the player loses one life and x_speed will get a new value (per random).

The tests of this method are quite the same as in chapter 2c, but there are four borders we have to test rather than two. But the technique stays the same and you should try to understand this method by yourself; with help of chapter 2c this should be no problem for you.

How to hit a ball

This game was the first one I'd ever programmed and the problem of how to hit a ball by clicking on it caused me a lot of headaches. Now I will try to explain my solution to you: Our ball has an x and a y position. The mouseDown - method in the main class, which calls userHit (int x_mouse, int y_mouse) gives the coordinates, where the user clicked on the applet, to the method userHit(). Now, our method has to decide if a ball has been hit or not. But how can we do this?

It is not enough to test if the x and y position of the ball is exactly the same as the position where the player clicked on the applet! This would mean that the player has to hit exactly in the middle of our ball, something that is almost impossible when the ball is moving!

Ok, second idea: We accept all mouseDown coordinates as a hit that are in a certain range around the exact position of our ball. Of course the x and the y position have to be in this range at the same time (&& - test). That way we would test if the player hit into a rectangle around the ball (for example if the ball has the radius 10, this rectangle should be 20 pixles each side). This was the first idea I tried to implement but it didn't work out as well as I thought it would. The whole thing worked sometimes and sometimes not, even if I hit the ball exactly! I don't even have the slightest idea why it didn't work .

Well, alright, third idea: I think, everyone has heard of vectors. In our game we have two vectors: one is the x and y position of the ball and the other one is the x and y position of the mouse click. If we calculate the length of the connection vector of these two vectors and if the length of this connection vector is smaller than the radius of the ball, the player has hit the ball.

First of all we have to calculate the connection vector:

    // Calculate connection vector
    double x = maus_x - pos_x;
    double y = maus_y - pos_y;

Now we use Pythagoras (c = Math.sqrt a² + b²) to get the length of this vector, which is the distance between the mouse click and the position of the ball:

    // Calculate distance
    double distance = Math.sqrt ((x*x) + (y*y));

In the last step of the method we are testing if the distance we calculated in the step before is smaller than a certain value, (for example the radius of the ball). I have choosen 15 as a good value although our ball has only the radius 10. But that has no special reason, it just seemed to fit best!

    // If distance is smaller than 15, player has hit the ball
    if (distance < 15)
    {
      player.addScore (10* Math.abs(x_speed) + 10);
      return true;
    }
    else return false;

Now we are able to hit the ball by clicking on it with the mouse pointer.

The player- object: Count score and lose lives

To count the score and lose lives, we added the methods looseLife() and addScore (int plus) to our player class. Everytime a ball leaves the applet, isOut() calles player.looseLife(), that way the player loses one life. If the player hits a ball, the method userHit() calls player.addScore (10* Math.abs(x_speed) + 10) and adds the score to the score in the player object (the faster the ball has been, the more points the player gets). The methods addScore and looseLife are really simple.

But there is one important point: The player object is initialized in the Main class! This means that the reference to the player object has to be initialized in the ball object too, to make it possible that the ball object calls methods of the player object!!
This is a very important technique because it happens quite often that more than one class needs a reference to a special object. But it means one has to initialize the object in one class, (I'm using the Main class to manage all game objects), and has to give the reference to this object, which is needed in more classes, to the other classes!

Change the mouse pointer to a crosshair cursor

In this game it would look much better to have a crosshair mouse pointer than a normal mouse pointer. To get such a cursor, we have to add three lines of code to the Main class of our applet:

First of all a instance variable of the class cursor:

    // Crosshair cursor
    Cursor c;

Now we add the following lines to the init() method:

    // generate a Crosshair cursor
    c = new Cursor (Cursor.CROSSHAIR_CURSOR);
    // set this cursor as the standard cursor of the applet
    this.setCursor (c);

You can find other mouse pointers in the Java API

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.

 Avaya DevConnect Center
 Service Component Architecture/Service Data Objects Solution Center
 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 53
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%.

Latest Linux Hits Networking Flaws
Metasploit 3.2 Offers More 'Evil Deeds'
'Thank You Apple. Seriously.'
The Buzz: BlackBerry App Store Seen Next
Is .NET on Linux Finally Ready?
Red Hat Takes on HPC Market, Microsoft
Python's New Release Bridges the Gap
No Flash Seen on iPhone Horizon
Apple Yields to Complaints Over iPhone NDA
Microsoft Shows Some Ankle With Visual Studio

Use Explicit Conversion Functions to Avert Reckless Implicit Conversions
Polyglot Programming: Building Solutions by Composing Languages
Automated testing for .NET by Ben Hall
"Supply Chain" SOA with SKOS
Service Component Architecture in Real Life
C++Ox: The Dawning of a New Standard
Getting Started with Virtualization
Master Complex Builds with MSBuild
eCryptfs: Single-File Encryption in Linux
CCXML in Action: A CCXML Auto Attendant

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



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
Avaya Article: Call Control XML - Powerful, Standards-Based Call Control
Tripwire Whitepaper: Seven Practical Steps to Mitigate Virtualization Security Risks
Internet.com eBook: The Pros and Cons of Outsourcing
Go Parallel Article: Scalable Parallelism with Intel(R) Threading Building Blocks
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Go Parallel Video: Intel(R) Threading Building Blocks: A New Method for Threading in C++
HP Video: Is Your Data Center Ready for a Real World Disaster?
Microsoft Partner Portal Video: Microsoft Gold Certified Partners Build Successful Practices
HP On Demand Webcast: Virtualization in Action
Go Parallel Video: Performance and Threading Tools for Game Developers
Rackspace Hosting Center: Customer Videos
Intel vPro Developer Virtual Bootcamp
HP Disaster-Proof Solutions eSeminar
HP On Demand Webcast: Discover the Benefits of Virtualization
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Microsoft Download: Silverlight 2 Software Development Kit Beta 2
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt
Iron Speed Designer Application Generator
Microsoft Download: Silverlight 2 Beta 2 Runtime
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
IBM IT Innovation Article: Green Servers Provide a Competitive Advantage
Microsoft Article: Expression Web 2 for PHP Developers--Simplify Your PHP Applications
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES