39,59 €
jMonkeyEngine 3.0 is a powerful set of free Java libraries that allows you to unlock your imagination, create 3D games and stunning graphics. Using jMonkeyEngine's library of time-tested methods, this book will allow you to unlock its potential and make the creation of beautiful interactive 3D environments a breeze."jMonkeyEngine 3.0 Beginner's Guide" teaches aspiring game developers how to build modern 3D games with Java. This primer on 3D programming is packed with best practices, tips and tricks and loads of example code. Progressing from elementary concepts to advanced effects, budding game developers will have their first game up and running by the end of this book.From basic concepts and project creation to building a complex 3D Game, you will learn to layout 3D scenes, make them interactive and add various multi-media effects.You will find answers to common questions including best practices and approaches, how game characters can act and interact, how to simulate solid walls and physical forces, how to take it online to play over a network and much more.From Zero to Hero, start your journey to make your game idea a reality.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 471
Veröffentlichungsjahr: 2013
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2013
Production Reference: 1180613
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84951-646-4
www.packtpub.com
Cover Image by Girish Suryawanshi (<[email protected]>)
Author
Ruth Kusterer
Reviewers
Peter Backx
T. Joseph Duchesne
Jens Hohmuth
Dany Rioux
Glauco Márdano
Acquisition Editor
Antony Lowe
Lead Technical Editor
Mayur Hule
Technical Editors
Prasad Dalvi
Pushpak Poddar
Kirti Pujari
Project Coordinator
Michelle Quadros
Proofreaders
Aaron Nash
Jonathan Todd
Indexer
Tejal Soni
Production Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
Ruth Kusterer became intrigued by Java and open source software while completing her degree in computational linguistics. In 2005, she joined Sun Microsystems, Inc. as a technical writer for netbeans.org where she wrote 100 NetBeans IDE Tips & Tricks. Since 2010, she has been working for CA Technologies, Inc. where she's a senior technical writer for security software. In her spare time, she hangs out on jMonkeyEngine.org and strives eternally to write the ultimate Java game.
I would like to thank the jMonkeyEngine core team for answering a BigInteger of newbie questions and helping out with non-trivial code samples. I would also like to thank all the jMonkeys posting inspiring videos of completed games, and a big shout-out to the NetBeans community whose NetBeans platform is the base of the jMonkeyEngine SDK.
Peter Backx is a software developer and architect. He has used Java for more than a decade to shape unique user experiences and build rock-solid scalable software. He received a PhD in Computer Sciences from Ghent University, Belgium. Peter maintains a technical blog at http://www.streamhead.com.
T. Joseph Duchesne holds a Computer Engineering degree from Dalhousie University and works in software-as-a-service web applications, primarily in backend infrastructure using a wide variety of technologies. In his free time, he enjoys video game development and has competed in open source/independent game development competitions.
Joseph is currently Sr. Infrastructure and Software Engineer at SimplyCast (www.simplycast.com), an online software-as-a-service marketing platform.
Jens Hohmuth graduated in Computer Science in 1998 from the University of Applied Sciences of Zwickau, Germany. Jens has been working for more than 10 years as a professional Software Developer. At his day job at a German company, he works for banks and financial services providers applying e-banking solutions on a wide range of different platforms. Jens has expertise in analysis, design, implementation, and support of software projects from small to large scale. He is an gile software development follower and a natural born problem solver.
Jens has outstanding training and presentation skills, and created a popular Intel Protected Mode and MMX Tutorial series as his internship back in college. This tutorial is still one of the top references for Intel Protected Mode today.
At night time, he is a wannabe game developer and the founder of the open source Java GUI Framework "Nifty GUI". Besides "Nifty GUI" he has contributed to many other open source projects. When he's not coding he enjoys creating 2D and 3D art as well as playing his guitar and piano. In the summertime, you can find him outside on his mountain bike (probably with his Macbook Air in the backpack).
I'd like to thank all the jMonkeyEngine core members for being extremely friendly and a great joy to work with. And of course all the "Nifty GUI" users (and critics) in the world for their continuing support.
Dany Rioux received his programmer/analyst diploma more than 15 years ago at the Herzing College in Montreal, Canada.
Although he left the programming side of things for numerous years to work in user support, he has come back to his first love and has been actively working on Disenthral, an RPG space game, based on the jMonkeyEngine3, for the past two years.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
If you have an account with Packt Publishing at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
"You, my brave hero, are about to embark on an adventure full of challenges and risks, but the reward at the end of your journey will be plentiful and will restore peace on earth. Are you ready?"
You have probably played many games before reading this book, and gladly accepted challenges such as this one! Now you will face a new adventure. You will create your own video game. There too will be challenges, but jMonkeyEngine gives you the tools to overcome them. This book introduces Java developers to 3D game development and shows how jMonkeyEngine can make a game developer's life easier.
Note that this book does not cover 3D model or sound design, nor the creative process of coming up with an original game concept—read the appendix for some related resources. By the end of this book, you will be ready to develop a 3D game, and have fun doing it!
Chapter 1, Installing jMonkeyEngine, helps you install the software and run a sample application.
Chapter 2, Creating Your First 3D Scene, teaches you how to add objects and transform them.
Chapter 3, Interacting with the User, reveals how to control game mechanics in the main loop.
Chapter 4, Adding Character to Your Game, shows how to load and convert models.
Chapter 5, Creating Materials, demonstrates how to manipulate the surface of objects.
Chapter 6, Having Fun with Physics, teaches you how to make objects act solid or heavy.
Chapter 7, Adding Spark to the Game, shows basic types of decorative effects.
Chapter 8, Creating Landscapes, introduces terrains and environmental effects.
Chapter 9, Making Yourself Heard, teaches how to integrate sounds and music.
Chapter 10, Showing Your Game to the World, shows how to save, load, build, and distribute games.
Appendix A, What's Next?, reveals how to make your games fun and challenging.
Appendix B, Additional Resources for Fellow jMonkeys, introduces you to more advanced user interfaces.
Free Download Chapter, Playing on the Network, explains network communication in multiplayer games. This chapter is available as a free download chapter at http://www.packtpub.com/sites/default/files/downloads/6464OS_Free_Download_Chapter_Playing_on_the_Network.pdf
Game development involves a wide range of abilities. Mathematics, software programming, graphic design, musical arts, and writing skills. Like a member of a World of Warcraft guild, you need a firm grasp of the tools of your trade before you set out for your quest. Intermediate or advanced Java skills are a must, as is a basic grasp of multimedia design and 3D modeling.
Thanks to 3D engines, however, you do not have to reinvent the mathematical wheel for every 3D game that you write. 3D engines such as jMonkeyEngine handle the following tasks for you:
The sunlit ocean bay in this screenshot is just one of many examples of what can be achieved when a collection of advanced 3D rendering techniques come together:
In addition to transformation, projection, and rendering, there is a lot of internal functionality that is the same in every 3D game. By reusing proven implementations, you spare yourself the need to handcode standard algorithms. jMonkeyEngine includes many features that are otherwise only found in commercial game engines:
jMonkeyEngine gives you a head start, so you have more time for coding the parts that make your game unique.
To set expectations right, jMonkeyEngine is not one of these drag-and-drop tools that mass-produces games with just a few clicks. To create a truly original game, you have to be able to write Java code. Let's have a look at an example:
This screenshot shows a scene from Hostile Sector, a browser-based multiplayer strategy game created with the jMonkeyEngine (http://www.mindemia.com/hostilesector/). In this game, two armed teams fight each other in an abandoned town. To be able to create such a basic game scene, you need to be familiar with the following mathematical concepts:
This book will walk you through these mathematical concepts where necessary, and introduce you to the appropriate built-in methods and classes that get these tasks done.
It is often that successful games such as Minecraft that inspire players to become game developers themselves. An example of a game that was inspired by Minecraft is Mythruna (http://mythruna.com/), an open-world game developed with the jMonkeyEngine.
For its creator, Mythruna was not the first game he ever wrote. Successful developers achieved their level of skill by starting small. Begin your developer career by creating a portfolio of solid mini-games to gain experience. Equipped with this knowledge, you can work your way up to the "MMORPG of your dreams".
The key to success is to stick to one idea and dare to strip off everything unnecessary. Don't aimlessly attempt to top every best-selling game of the last decade in your first release. And don't water down your game by adding tons of distracting effects just because everyone else is doing it.
Everyone else can start a game, but you want to finish it, too. A good feasibility test is to sum up your concept in one line. An example catchline for a Minecraft-like idea could be, "Build by day, survive by night". If you can't convey your idea in one straightforward line, it's too complicated to implement. Start with a clearly cut-out idea, and soon you will have something cool to show.
Do you already have a game idea? Let's have a quick look at the process of breaking down a complex idea into the building blocks of game development.
Let's say you are creating something similar to Hostile Sector, basically an arena with two fighters. One is a player-controlled character, the other a hostile non-player character (NPC).
How does the computer-controlled NPC "see" where the player is? How does the enemy approach the player without stupidly bumping into walls? At first, any game concept may seem like an undertaking of real-life complexity. But when you think about it for a minute, you notice that even a complex game scene is composed of only a handful of basic actions.
Now that you are aware of the basic atoms, a seemingly intricate scene turns into a manageable pattern of smaller pieces. Just like building blocks, you can use these elements in any order or number that fulfills your game's purpose. The only limits are the capabilities of your PC.
How do you apply what you just learned in context? Let's look at the overall structure of computer games. Obviously, you will have to write code to initialize the scene, and also to shut down the game cleanly. Between the beginning and the end, every interactive 3D application constantly loops through three stages: listen, update, and render.
In each stage of the game loop, you can make use of all basic elements described here. Let's look at an example of how to put the pieces together.
Our example is of two fighters in an arena. In simple terms, you can break this scene down as follows:
Looks more manageable now, doesn't it?
In the preceding example, you saw how a game scene comes together. As you read on, your understanding of the application structure will improve. The book includes a lot of hands-on sample code and fun challenges, because writing code and trying it out is the best (and most interesting) way to learn.
As additional sources, you should bookmark the following two pages:
In this book, you will find several headings appearing frequently.
To give clear instructions on how to complete a procedure or task, we use:
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title through the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We also provide you a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from http://www.packtpub.com/sites/default/files/downloads/6464OS_ColoredImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
When a group of heroes set out on a quest, they grab their armor and weapons—when you set out on a game development adventure, you grab the jMonkeyEngine SDK.
The jMonkeyEngine Software Development Kit (SDK) contains everything that you need to get started quickly: the jMonkeyEngine libraries, Javadoc, sample code, and lots of nifty game development utilities. This bundle also includes all necessary native libraries, such as LightWeight Java Game Library (LWJGL). This means there is no second installation step, neither for the development team, nor for users of the games that we create.
In this chapter you will learn:
At the time of printing, the jMonkeyEngine SDK needs 40 MB of memory, plus enough memory to load the particular game's assets. Your computer should have a minimum of 1 GHz CPU, and your graphic card must support OpenGL 2.0, or better. Suitable graphic cards include ATI Radeon 9500, NVIDIA GeForce 5 FX, Intel GMA 4500, and all newer ones.
You can use the jMonkeyEngine SDK on all operating systems that support the Java Development Kit 6 (JDK 6) or better. Currently this includes Windows XP/Windows Vista/Windows 7 or better, Mac OS X 10.5 or better, and Linux kernel 2.6 or better.
Enter the following command in your terminal to check whether you have the required Java Development Kit (JDK) installed:
If this command returns javac 1.6.x or better, then your Java installation is set to go. If you still need to install the JDK, click on the Download JDK button at http://www.oracle.com/technetwork/java/javase/downloads/index.html and follow the installation instructions there.
The jMonkey team devised the jMonkeyEngine SDK to make the installation process as smooth as possible:
It's time for your first test run:
When the SDK opens, you will see the following application screen:
The Projects window, on the top left-hand side, is where you will browse Java files and manage Java packages, among other things. The SDK also contains an editor window for Java files, not visible here, that we will look at in a minute. At the bottom right-hand side of the screen, you see the Output - Application window; this is where build messages, runtime exceptions, warnings, and println() appear.
In the center, you see the OpenGL Window. We will use it later to preview the 3D scenes that we created using the Properties, SceneExplorer, and SceneComposer windows, not visible here.
The other two windows you can ignore for now. Later you may use the FilterExplorer window to configure special effects, and the AssetPackBrowser window to bundle up collections of 3D models.
Congrats, your tools are ready, and you have accomplished your first mission. Let's take a closer look at the jMonkeyEngine SDK.
The jMonkeyEngine SDK is your graphical user interface for the jMonkeyEngine library. The jMonkey team devised this integrated development environment (IDE) especially for 3D game development with Java. The jMonkeyEngine SDK assists you from start to end, whether you write code, integrate game assets, lay out scenes, or deploy the finished application.
Creating your Java game projects with jMonkeyEngine SDK has the added value that they are already preconfigured:
At the same time, there is nothing proprietary about the projects that the SDK creates: you are looking at standard Java SE projects. The SDK's clean, build, and run actions are automated using standard Ant build scripts. The Apache Ant build tool is already included when you install the SDK.
Did you know?
jMonkeyEngine SDK is built on top of the NetBeans Platform. This means that you can install all kinds of NetBeans IDE plugins. The NetBeans plugins prepackaged in the jMonkeyEngine SDK include version control tools and a Java debugger. Open the jMonkeyEngine SDK and choose Tools | Plugins from the menu, then click on Available Plugins to browse and install other cool add-ons for free, such as a Java profiler.
Although this book will repeatedly tell you how awesome the jMonkeyEngine SDK is, you are not forced to use it for coding. The jMonkeyEngine library is open source software: If you download the latest binary bundle from http://www.jmonkeyengine.com/nightly/, you can manually add the JAR files from the lib directory to your CLASSPATH, just like any other Java library. You can link these libraries in your favorite Java IDE, or do your Java development in a text editor on the command line if that's how you roll.
For now, let's continue using the SDK because it will get you started more swiftly. This book strives to keep code samples IDE-independent. If a shortcut or workflow only applies to the jMonkeyEngine SDK, it will be clearly pointed out as such.
Nonetheless you should give the jMonkeyEngine SDK a try. It contains many plugins that you will not find in generic IDEs: an asset pack manager and file converters for 3D models, a scene viewer and scene composer, a terrain editor, a procedural texture generator, a code snippet palette, and much more. Try it! If you are not convinced by the end of this book, you will find setup instructions for other IDEs in the appendix. Deal?
In order to test whether everything was installed correctly, let's run a few demos. A set of demos comes bundled with the jMonkeyEngine SDK as one of the project templates.
The SDK unpacks the bundled demos and makes copies of the demo sources. The new JME3 Tests project appears in the Projects window.
To run a demo:
Type walking into the filter box to find it more quickly.
Now that you know how to use the TestChooser, run some demos to see what is possible with jMonkeyEngine.
It's good to know that, during the development process, you can always return to the JME3 Tests demos for inspiration. Browse the demo's Source Package if you are looking for code samples that showcase particular features. Feel free to modify your copy of the code samples and experiment. In the unlikely case that you break the project, you can always recreate the JME3 Tests template from the New Project menu.
Restoring the demos is as easy as creating a fresh game project, which is what we will do next.
The jMonkeyEngine SDK provides you with a preconfigured project template that gets you started at lightning speed.
This is how you create a new project:
A new Java project named BasicGame appears in the Projects window, next to the JME3 Tests project.
The BasicGame project contains a simple Main.java template. Let's try to run this Java application:
As you can see, it's easy to create and run fully preconfigured game projects in the jMonkeyEngine SDK.
Let's open the BasicGame folder in the Projects window and look at the project structure that the SDK has just created for you.
You can see that the Projects window gives you access to three important areas: Project Assets, Source Packages, and Libraries, as well as the build script.
The Projects window shows the logical structure of a jMonkeyEngine project. This view only displays files that you need during development, and it filters out build folders and configuration files. For comparison, have a look at the project's physical structure, which lets you browse the actual files on your hard drive; choose Window | Files from the menu to open the Files window. Click the triangles to open the subsections and compare the two views, as shown in the previous screenshot.
Browse the Libraries section in the Projects window. You can see that it lists all the JAR files that are preconfigured on this project's CLASSPATH. Compare this to the physical dist/lib directory in the Files window.
If you know about Ant build scripts, you may want to open the Important Files node in the Projects window and browse the preconfigured Ant targets. Compare this to the physical build file, build.xml in the Files window.
You will see that a jMonkeyEngine-based application is a standard Java project made up of the following files and folders:
Project folder
Usage
JMonkeyProjects/BasicGame/assets
You store multimedia assets here
jMonkeyProjects/BasicGame/build/
The SDK generates build classes here
jMonkeyProjects/BasicGame/build.xml
You customize the Ant build script here
jMonkeyProjects/BasicGame/dist/
The SDK generates executables here
jMonkeyProjects/BasicGame/nbproject/
The SDK stores the default build script and metadata here
jMonkeyProjects/BasicGame/src/
You store source code here
jMonkeyProjects/BasicGame/test/
You store JUnit test classes here (optional)
Certain files and folders are automatically created and maintained by the jMonkeyEngine SDK such as build, dist, and nbproject. The SDK recreates these files and folders when you build the application, so do not edit them.
The other folders, highlighted in yellow, contain your sources and assets. Using the test folder is optional; for now, just ignore it. As in any Java project, you have full control over the project's build.xml file, and your two main folders, assets and src.
Switch back to the Projects window. You see that the Project Assets folder corresponds to jMonkeyProjects/BasicGame/assets/, and the Source Packages folder corresponds to jMonkeyProjects/BasicGame/src/. You are free to set up subfolders and packages inside these two folders, as your project requires.
Your Java classes obviously go into Source Packages, but what does the Project Assets folder contain? Open the Project Assets folder and look inside: you will see subfolders for Sounds, Textures, and Models. This folder is where you store your multimedia content.
Every 3D game requires some multimedia assets, whether it's 3D models, image files, sound clips, video clips, or music. This book focuses on the development aspect—how to tie assets and code together and deploy the game. Being able to write source code only takes you halfway there: to develop games, you also need to go through the art pipeline.
By art pipeline we mean the creative process of creating 3D models, composing background music, and so on. The art pipeline runs in stages parallel to your coding milestones:
Including sounds and images in your game means that you either need access to a multimedia library, or you need to create your assets using external tools.
The jMonkeyEngine SDK does not include any multimedia editors. This is because a game engine should not prescribe the artist's choice of design software. You are free to create assets in any third-party tools that you fancy and have access to. Just make certain that you can export the artwork in formats that jMonkeyEngine supports.
The following external file types are supported by jMonkeyEngine:
Supported File Type
Usage
.mesh.xml, .material,
.skeleton.xml, .scene
Ogre Mesh XML (3D models)
Ogre DotScene (3D scenes)
.obj, .mtl
Wavefront objects (3D models)
.blend
Blender files (3D models)
.jpg, .png, .tga, .gif,
.dds, .hdr, .pfm
Images and textures
.fnt
Bitmap fonts
.wav, .ogg
Wave and OGG Vorbis audio
If you have not chosen your multimedia tools yet, the following are some suggestions of popular editors that support the formats mentioned earlier:
All of these are examples of software that is available for Windows, Mac OS, and Linux; all three are open source, and you can download and use them for free.
There are many more free and paid design tools available if you do a search. Whichever software you choose to create your assets, consult the respective manuals for details on how to use them. 3D modeling in particular is not a trivial task, but it's definitely worth learning.
Now that you have the design and development tools installed, you have everything you need to create your game.
But what do your users install to play your game?
During the development phase, you typically build and run your game right from the jMonkeyEngine SDK. Your users, however, neither have nor want the SDK. They expect to run the game by, for instance, executing a desktop application that runs on their Java Virtual Machine.
Switch to the Files window, and look into the dist folder. Every time you Build this project, the SDK generates an executable JAR file here. When you right-click on the project and choose Clean, the dist folder is deleted—so remember never to move any unique files there.
Let's go through the basic deployment process together:
Look into the Output window to follow the build process.
When the build is finished, switch to your operating system's file explorer:
This exercise shows you that the SDK generates distributable builds of your BasicGame project that runs fine on your desktop, outside the jMonkeyEngine SDK.
Impressive—you have just built a basic 3D application that runs on the three most widely used operating systems. Notice how you didn't have to configure any CLASSPATH or library paths.
Yes, the jMonkeyEngine SDK is a free open source software released under the BSD license. To answer the most common questions right away:
All that is required from you is that you adhere to the BSD license, and keep the license together with the jMonkeyEngine libraries included in your distribution. Simply copy the license from the jMonkeyHomepage. Don't worry, it's nice and short and can be found at http://jMonkeyEngine.org/wiki/doku.php/bsd_license.
In this chapter you learned how to install the jMonkeyEngine SDK and run sample applications. You saw that it is easy to get started with game development using the jMonkeyEngine SDK, and how easy it is to distribute a game using the jMonkeyEngine SDK.
Come on over to the next chapter, where we write some actual code!
Now that you have installed the engine and understood the physical file structure of a project, we will take a look inside to understand the flow of a jMonkeyEngine game.
In this chapter, you will learn:
It's time to look at some code.
From the previous chapter, you'll remember that we executed the BasicGame template to test whether the installation was successful. This project template demonstrates the structure of a typical jMonkeyEngine main class that initializes the scene and starts the application.
