Preface

"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!

What this book covers

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

Get a head start

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:

  • Transformation: Rotating, scaling, and moving 3D objects
  • Projection: Automatic conversion of 3D scene data to 2D images on the screen
  • Rendering: State-of the-art shading and lighting of object surfaces

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:

  • A 3D scene graph: A data structure that is optimized to store objects of a 3D scene
  • A main event loop: A modular component that controls game mechanics and interactions
  • Support for loading and displaying multimedia assets
  • Support for handling user input and graphical user interfaces
  • An intuitive camera object that marks the point of view of the player
  • Physics simulation, special effects, multiplayer networking, and more

jMonkeyEngine gives you a head start, so you have more time for coding the parts that make your game unique.

Who this book is for

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:

  • The Cartesian coordinate system: You use coordinates every time you position a character or building into the scene.
  • Vectors: You use vectors to specify angles and directions every time you make a computer-controlled enemy turn around. You use vectors when calculating distances and speeds every time an enemy follows a player character.

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.

Getting things 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.

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.

  • You attach 3D objects to the scene to make them appear, and detach them to make them disappear. Examples include terrains, buildings, players, enemies, cars, obstacles, traps, and so on.
  • You transform 3D objects. Transformation means that you make the game engine translate (position), rotate (turn), or scale (resize) objects in the scene.
  • You modify physical properties of 3D objects. Examples include lighting and shading, materials and colors, mass, speed, bounciness, or solidity.
  • You detect user input from the keyboard, the mouse, or a joystick, and respond to it. For example, the player clicks to shoot.
  • You specify a rule how the game acts and causes state changes for the player. This includes automatic game mechanics such as intelligent computer-controlled enemies who attack when the player approaches their secret lair.
  • You specify a rule how the game reacts to state changes. You repeatedly get and set object properties (such as current location, direction, or points) and use them in specific conditions. This includes game mechanics such as "if health equals zero, then game over" or "if distance between player and enemy is less than one meter, then attack".
  • You play audio, video, animations, and special effects. These are only decorations, but they add a lot to the immersion, if used right.

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.

Listening to the heartbeat of your game

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.

  • Initialize: The game loads objects and brings them in their starting positions. The loop starts:
    • Listen: The engine detects user input and responds according to your input handlers
    • Update: Your game code polls and updates its state, and acts and reacts according to your game mechanics
    • Render: The engine draws the scene to the screen
  • End: The player has won, lost, paused, or quit the game. The loop ends.

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.

Putting the pieces together

Our example is of two fighters in an arena. In simple terms, you can break this scene down as follows:

  1. Initialization: You load the landscape, player, and enemy models, attach them to the scene, and position them. The loop starts.
  2. Listen: The game listens for keyboard input in case the player moves his character. The game listens for mouse input in case the player clicks to attack the enemy.
  3. Update: The game checks for obstacles between the two opponents, and rotates the computer-controlled enemy to approach the player's location. If certain conditions are met, the enemy attacks the player and plays a sound. The game polls location, armor, and health of the opponents, and calculates the outcome of every attack. The game updates location, armor, and health values according to the outcome.
  4. Render: The game draws the updated state to the screen and the loop repeats.
  5. End: A test checks if one of the fighters has reached zero health points. If yes, then the loop ends and a winner is declared.

Looks more manageable now, doesn't it?

Sources of information

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:

Conventions

In this book, you will find several headings appearing frequently.

To give clear instructions on how to complete a procedure or task, we use:

Time for action – heading

  1. Action 1
  2. Action 2
  3. Action 3

Instructions often need some extra explanation so that they make sense, so they are followed with:

What just happened?

This heading explains the working of tasks or instructions that you have just completed.

You will also find some other learning aids in the book, including:

Pop quiz – heading

These are short multiple choice questions intended to help you test your own understanding.

Have a go hero – heading

These set practical challenges and give you ideas for experimenting with what you have learned.

You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "Browse to the jMonkeyProjects/BasicGame/dist/ folder in your user home."

A block of code is set as follows:

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.RenderManager;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

SceneGraphVisitorAdapter myEmitterVisitor = 
                         new SceneGraphVisitorAdapter() {
 @Override
  public void visit(Geometry geom) {
    super.visit(geom);
 searchForEmitter(geom); // trigger custom test
  }
 @Override
  public void visit(Node node) {
    super.visit(node);

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "If you still need to install the JDK, click on the Download JDK button."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

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 , 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.

Customer support

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.

Downloading the example code

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.

Downloading the color images of this book

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.

Errata

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 errata submission form 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

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 with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.