★ wanayoo — archive 1999 http://javaboutique.webdeveloper.com/tutorials/Java_Game_Programming/DasErsteSpielEng2.htmlNouvelle recherche | Portail wanayoo
Computer Digital Expo

Find the lowest price for a variety of products:


Featured Categories:
Computers
Digital Cameras
Home Theatre
Video Games
Laptops
Software
Electronics
PDA's


Find a Web Host With:
CGI Access
DB Support
NT Servers
UNIX Servers
Telnet Access

advanced search
Internet News
Internet Investing
IT
Windows Technology
Linux/Open Source
Developer
Interactive Marketing
xSP Resources
Small Business
Wireless Internet
Downloads
Internet Resources
Internet Lists
International
EarthWeb
Career Resources

Search internet.com
Advertise
Corporate Info
Newsletters
E-mail Offers
Be a Commerce Partner
Register Domains
Shop For Computers
Business Search
Tech Magazines - FREE
Web Hosting
Promote Your Website
Business Search
FREE Credit Report
Build an Online Store
Software Store
FlashKit
Gif.com
HierMenusCentral
JavaBoutique
JavaScript.com
JavaScriptSource
WebDev Jobs
JustSMIL
ScriptSearch
StreamingMediaWorld
Web Hosts
WebDevelopersJournal WDVL
WebDeveloper.com
WebReference.com
XMLFiles.com
CGI
HTML
Java
JavaScript
Web Design and Promotion
Web Site Development
E-mail Address:


Can you receive
HTML e-mail?

Yes   No

Zip Code:


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


Applet Index
(sorted alphabetically)

A B C D E F G H I J K
L M N O P Q R S T U
V W X Y Z #s
The Java Source
(applets w/source code)

A B C D E F G H I J K
L M N O P Q R S T U
V W X Y Z

How to Add Java Applets to Your Site

New on the Java Boutique:

New Article:
A Barebones Guide to Usability Testing
At first glance, usability testing may seem like unnecessary, or additional work. In todays budget slashed world, it is not uncommon for projects not to have the luxury of this valuable phase. This is a dangerous path to tread. Let's look at how we can incorporate usability testing into our design process.
... [more articles]

New Tutorial:
Java Certification Path API
Certificate based security forms the basis for SSL (Secure socket layer) transactions? Every year billions of transactions involving trillions of dollars are done safely using the SSL protocol. This week we'll look at the role of the Java certification path API and see how it provides a mechanism to implement certification path functionality.
... [more Tutorials]

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.

internet.com logo






Developer News

Apache Updates Popular HTTP Server

Is Adobe Targeting Microsoft's InfoPath?

Oracle Takes on Collaboration Market



Database Journal Launched!
Jupiter Media has announced the launch of Database Journal. DBJ offers SQL courses and other database related resources for beginner to expert developers.



Scrolling Text
This is a suite of three applets that displays scrolling text using an array of images. The detailed description of array of each applet is provided.
Download of the Week
DS PageFlipText
This applet displays a page-flip effect between texts. Over the animation you can also insert an image and a scroll-text.

JB User Poll
Which version of Java do you use the most?
The JavaBoutique Top 15:
1. ChompText
2. PulseText
3. DJPopMenu
4. NavBar
5. RushHour
6. PingPong
7. 3DMaze
8. AScroll2
9. Viewer
10. AnimLetters_anim
11. Encyclo
12. Distorter
13. BMI
14. MusicKeyboard
15. AdvPano
Want more? Check out our Top 100!

Refer-It
Affiliate Program and Referral Directory.
New on internet.com
Cisco Exploit Is Active
Security researchers have increased the threat level on a vulnerability affecting Cisco routers and switches after an exploit was posted to a popular mailing list.

The 3G Tokyo Time Machine
What will a 3G wireless future be like? Step into DoCoMo's time machine and find out.

SBA's Whistling Dixie
Small businesses throughout the South are extended the opportunity to meet one-on-one with government agencies and large corporations to obtain near-term contract opportunities for their products and services.


The Event for Search Engine Marketing & Optimization

Jupitermedia is publisher of the internet.com and EarthWeb.com networks.
Copyright 2003 Jupitermedia Corporation All Rights Reserved.

Legal Notices,  Licensing, Reprints, & Permissions,  Privacy Policy.
http://www.earthweb.com/
http://www.internet.com/