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

Bounce a ball

Well Ok we are now able to move a ball across the applet without any flickering of the screen. This means that we know the two most important steps to program a game with animated objects. In this chapter I want to tell you how to change the movement direction of the ball. This is the first time that we can't solve a problem by a "standard" technique, as we could do in the chapters before (Double buffering...). But I'm sure if you understand the solution, you will have your own ideas once you are in a similar situation. In our last two applets, the ball is moving across the applet area just one time. But now we want to avoid, that the ball is leaving the applet area, instead the ball should bounce in the opposite direction if it hits a wall. What shall we do? It would be good, if you would stop reading now and try to find a solution by yourself. In the following chapter you'll get to know my solution (which is not the only one!). Please use the "Ball" - applet with double buffering as the basic code for this chapter!

How to move a ball in different x - directions

First of all we have to think of the technique we used to move the ball in the second chapter. What did we do? Well, we increased the x - position of the ball every time the thread was executed and and repainted the ball at the new position. Maybe you didn't realize it, but we used a "speed vector" for the x - direction of the ball, everytime we changed the x - position of the ball by calling x_pos ++ in the run - method. That means that we can also define a variable called x_speed that stores the value which will be added to x_pos by calling now x_pos += x_speed. Imagine, x_speed has the value 1, this means, that the ball is moving from the left to the right hand side (same direction as in the chapter before), because x_pos will be increased by one everytime the run - method is executed. Now it is really easy to change the direction of the ball. We only have to set the value of x_speed to -1! This means, that everytime we call x_pos += x_speed -1 is "added" to the x - position of the ball. That way the value of x_pos is decreased by one and the ball is moving from the right to the left hand side!

Now we are able to change the direction of the ball! And there is just one "problem" left! How can we (the computer) decide, when to change the direction? Well, we have to test everytime we execute the run method, at what x - position our ball is. The code to do this looks like this:

// Ball is bounced if its x - position reaches the right border of the applet
if (x_pos > appletsize_x - radius)
{

    // Change direction of ball movement
    x_speed = -1;
}
// Ball is bounced if its x - position reaches the left border of the applet
else if (x_pos < radius)
{
    // Change direction of ball movement
    x_speed = +1;
}

Everytime we execute the run - method we test if the ball has reached one of the borders (left or right). If this is the case, we change the value of x_speed and that way we are able to change the direction of the ball movement.

You might be asking why I use the radius of the ball in the code above. The x - position of the ball is its middle point, which means that the left or the right border of the ball is its x - position plus or less the radius. To make us believe that the ball would be bouncing when it hits the wall, we have to add or substract the radius to / from the the value of x_pos.

How to "beam" the ball

Once you understand the technique of how to test where the ball is, you can implement many other things. Imagine we want to let the ball appear on the other side of the applet once the ball has left the applet area. That's very easy to do, we have to test again, where the ball is and then we have to set a new x - position for the ball instead of changing the value of x_speed.

// Test if ball has left applet area if (x_pos > appletsize_x + radius)
{
    // Set a new x_pos value for the ball
    x_pos = -20;
}

Later, in chapter 5, I will talk about how to move a ball not only in a one dimensional way but in a two dimensional area (which means in x and y direction). That is really easy to do. You will have not only one vector (x_speed) but two (x_speed, y_speed), and a y_pos and a x_pos. If one changes both values everytime run() is called the ball will be moving over the whole area. But of course we have to test 4 different possibilities, where the ball could leave the applet. If you want to, you can program an applet where the ball can move in different directions (2D) and is bouncing from every border of the applet (would be a good practice ;-). Ok, that's it, take a look at the applets and download the code!

SourceCode BallReverse download
SourceCode BallBeamen download
Applet Ball Reverse ansehen
Applet Ball Beamen ansehen

Nächstes Kapitel

Using sounds in applets

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