Вы находитесь на странице: 1из 87

version 4.

...the smart can give you solutions, ...the intelligent can give you answers, ...but, alas, the wise can only give you questions.

Table of Contents
About the author.........................................................................................................................................5 About this document...................................................................................................................................6

License........................................................................................................................................................6 Design.........................................................................................................................................................6
Acknowledgments......................................................................................................................................7 Introduction.................................................................................................................................................8 Source code...............................................................................................................................................9 Chapter 1: Theory.....................................................................................................................................10

What is a game?.........................................................................................................................................10 So what are video games then?..................................................................................................................10 How a videogame is created......................................................................................................................10 2D graphic design......................................................................................................................................12 3D graphic design......................................................................................................................................13 Audio design..............................................................................................................................................14 So many tools and so little time!................................................................................................................14 Game programming...................................................................................................................................15 The most important component to include in your video game: FUN!......................................................16
Chapter 2: Decision time..........................................................................................................................17

What programming language should I use for my game?..........................................................................17 Game engines............................................................................................................................................18 DirectX (Direct3D) versus OpenGL..........................................................................................................21 Final recommendations..............................................................................................................................22 My (very) own personal decision .............................................................................................................22
Chapter 3: Making a 2D game.................................................................................................................24

Computer game flow.................................................................................................................................24 Setting up the development environment...................................................................................................25 Making a puzzle game with GTGE............................................................................................................25
Chapter 4: Making a 2D multiplayer game...............................................................................................33

Networking basics.....................................................................................................................................33 Game server...............................................................................................................................................35 Puzzle game - multiplayer version.............................................................................................................35


Chapter 5: 3D games...............................................................................................................................39

3D basics...................................................................................................................................................39
Chapter 6: Making a 3D game.................................................................................................................43

Step 1: Prepare an empty screen................................................................................................................45 Step 2: Loading a map...............................................................................................................................46 Step 3: Moving around the map.................................................................................................................47 Step 4: Checking collisions........................................................................................................................47 Step 5: Adding the apple............................................................................................................................48 Step 6: Game Loop....................................................................................................................................48 Step 7: Final version of the game..............................................................................................................50
Chapter 7: Making a 2D multiplayer game - version 2.............................................................................53

A better network library.............................................................................................................................53 Why UDP?................................................................................................................................................54 Adding the ummi network library to the puzzle game...............................................................................54
Chapter 8: Making a 3D multiplayer game...............................................................................................58

Apple Chase - multiplayer design..............................................................................................................58 Making some improvements to our 3D game............................................................................................58 Adding server-side game logic..................................................................................................................59 Updating the game client...........................................................................................................................60
What's next?.............................................................................................................................................65 Appendix A: Extra Resources...................................................................................................................66

Library.......................................................................................................................................................66 Resources..................................................................................................................................................69
Appendix B: How to setup Slick framework with Eclipse.........................................................................71 Appendix C: How to setup GTGE inside Eclipse IDE..............................................................................79 Appendix D: How to setup Xith3D inside Eclipse IDE..............................................................................82

Installing the support libraries...................................................................................................................82 Adding Xith3Ds own files........................................................................................................................83 Adding the native libraries.........................................................................................................................84 Making sure Xith3D is installed correctly.................................................................................................86
Appendix E: Xith3D scenegraph..............................................................................................................87

Lucu guide for creating videogames page 4

About the author


Henry Tong (a.k.a. Taksan) is a software architect, who, as part of his job has used different computer technologies (not all of them voluntarily) in different software development projects. When he is not creating software for a bank or an enterprise he is creating (mostly playing actually) video games or learning what real games are made of from his 4-year-old daughter Dharma. He can be contacted at: taksantong@yahoo.com

Lucu guide for creating videogames page 5

About this document


License
Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_US

( In plain simple words: you are free to copy and share this document as long as you always say who the original author is and as long as you do not use it for commercial purposes. )

Design
The cover art is a homage to one of the author's favorite games: Jumpman This document was created with LibreOffice and uses free fonts from these places: DaFont fonts collection: www.dafont.com Liberation fonts collection: https://www.redhat.com/promo/fonts

Lucu guide for creating videogames page 6

Acknowledgments
Thanks to my dad for buying me a Commodore64 computer when I was a kid. (Even though his intention was not for me to program games on it!) Thanks to Adolfo for the extra hardware for game developing and testing. It really came in handy! Thanks to Marvin Frhlich (from the Xith3D forum) for helping me understand how the Xith3D engine works. Thanks to any friend not included in this page but that understands my crazy mind sometimes flies away too much and I may forget to put a name here.

Lucu guide for creating videogames page 7

Introduction
Welcome to the lucu guide! I hope you will find here the information you need to start your journey on making your own videogames. Creating games is a challenge, but maybe with a little help from this guide at least starting to create games can be as fun as playing them. In Indonesian (bahasa) language lucu means fun/funny. And thats the key word in this guide. No matter what kind of game (table game, board games, computer game) you are trying to create, your ultimate goal is to allow people to have fun. Happy gaming!

Lucu guide for creating videogames page 8

Source code
You can find the source code of the examples presented in this guide here: http://code.google.com/p/lucu

Lucu guide for creating videogames page 9

Chapter 1: Theory
What is a game?
Games have been created and played for thousands of years. Take for example this very old board game: Senet ( http://en.wikipedia.org/wiki/Senet ) One can almost say that games exist because there is life, because not only humans play, animals do too. So, what is a game? One very basic definition is that a game is a fun activity, but thats not enough because then we need to ask why we want to have fun? My own theory is: because we are, by nature, social and curious beings. We have a natural instinct for it. As babies we play a lot and have fun a lot, and that happens not just because babies are playful, but also because they need to learn about their environment (objects and humans around) and guess what is the best way to learn?... playing of course! Having fun while learning something new is the best way to ensure we learn for good. And this applies during all our life, no matter how young or old we are. Now, if you add some rules while playing (even if it is a simple rule like my turn first, then yours) and put a name on it (even if is as simple as guess-a-number) then you have a game!

So what are video games then?


If done right they are just games in a digital platform: cellphones, computers, game consoles, .etc. If done wrong they are just products in a store waiting for someone to buy them. But since they are matter of our study, they deserve a more glorious definition: video games are a form of entertainment, alone or in a group, through digital and/or electronic platforms. With this definition we can cover from a single person playing tetris in his cellphone all the way up to a group of people enjoying a multi-player game at once while they are physically in different parts of the world. The word entertainment has a whole background just by itself. With this word we can even compare the video games and movies, they are both a form of entertainment and they are both lucrative also, in fact, the video game industry may very well in the future be as big (and maybe bigger) than the movie industry. And entertainment can also involve magic, fantasy, illusion, fun, music, and interesting challenges! and to combine all them requires not only technique, but also art. To create a video game you will also need assets like images, videos, sounds, and stories. This document attempts to guide you in your first steps on creating a video game. But one single guide cannot cover all these aspects so be sure to check the appendix Library later in this guide for a light on other topics related to video game creation. One more advice: Try to play as many games as you can. From different platforms (xbox, ps2, ps3, PC, Wii, GameBoy... )... try different types (action, rpg, sports....)... this will give you a lot of experience and ideas on what works and what does not. Plus it will be fun! And you do not have to waste money on this, you can just try the demos. Even if you can not try the demos, look at videos of trials, intros, or other people playing, there are some websites that let you do that, like GameSpot or GameTrailers ( GameSpot.com, GameTrailers.com )

How a videogame is created


We start with the idea of a video game (I want a game about a spaceship that can transform into a robot and then...) and based on it we start to develop the rules, the graphical and audio resources, and then we package them together and produce software, which is our game. This high level overview is described in
Lucu guide for creating videogames page 10

the following diagram:

Game Idea

Design game logic (combination of events, story, drama, characters, rules...)

Create sound and music assets

Create 2D graphical assets (images, backgrounds, sprites...)

Create 3D graphical assets (characters, objects, scenery, lights, maps, levels, monsters...)

Develop/Programming (produce software)

Package the software as a final product (to be delivered by web, DVD, CD...)

Illustration 1: video game production pipeline

Be sure to notice one important point: the flow of the production process does not just goes from top to bottom, but it can actually go back again to the design level and between processes also, this is because: Your game design may require to put the main character of the game in a fight with 10 dragons, but once you reach programming time you realize your technical skills/resources can allow you display only one dragon at a time on the screen. (just like any software development process) Testings and prototypes can show a flaw or aspect of the game that needs to be re-designed. It is always a good practice to test your game with (digital or not) prototypes. ( Here is when your beta testers help ) It could also happen that you create a wonderful 2D image that requires just a little 3D touch to make it more realistic. This is a good example of how an asset can move from 2D process to 3D process.

All this is great! Just as if we were creating a digital interactive movie. Now we go for more detail about this process.

Lucu guide for creating videogames page 11

2D graphic design
Not all games have to be 3D. And, even 3D games need some 2D graphics (like textures) to support them. Some games may not even have graphics (like text-based games). So it is always good to know how to manage 2D graphics. Be aware that some 3D games are just 2D with perspective (AKA isometric games). Here are some popular examples of 2D tools you can use:

Tools Adobe Photoshop http://www.adobe.com/products/photoshop Adobe Illustrator http://www.adobe.com/products/illustrator Inkscape http://www.inkscape.org GIMP http://www.gimp.org Adobe Flash http://www.adobe.com/products/flash Corel Draw http://www.corel.com

License Commercial

Notes Probably the most popular in this category Vector graphics manipulation

Commercial

Free

Vector graphics manipulation

Free

Commercial

Not just a 2D graphics tool, but a complete environment for 2D applications. New versions are starting to have some basic 3D capabilities Can handle vector and bitmap

Commercial

To help you decide which tool to use you can also see on-line tutorials of each one and download the software (or trial editions). Do not try to master any particular tool, you may discover later that you need to know a little of each one. In general, people that have a designer background prefer Adobe software because its interface is more easy to use by designers (and in general they used Adobe software while they had their design-classes at school) In general, people that have a more technical/programming background (like me) tend to prefer software that is easy to customize and to extend with plugins (or lets you create/program your own plugins) and that is why this kind of people may choose Inkscape, GIMP or Corel Draw. Dont forget to learn a Vector tool AND a BITMAP tool, both will be handy.

There are some extra 2D tools you may or not need depending on the kind of game you want to create, here is a list of some of them in case you need one:

Tools GraphicsGale http://www.humanbalance.net/gale/us/ MTPaint

License Commercial

Notes Great for doing sprites/animations

Free

Bitmap/Sprite image manipulation

Lucu guide for creating videogames page 12

http://mtpaint.sourceforge.net/ Particle Illusion http://www.wondertouch.com/ Tile Studio http://tilestudio.sourceforge.net/ Free Image editor for game resources, can also create map (tiles) for your game levels Commercial Create wonderful effects!

3D graphic design
3D modeling and rendering helps to add realism and great visual effects to our games. Keep in mind that doing 3D graphics for movies, architecture, animations or games are different topics so some 3D tools are better in one area than another. One very important feature you need to consider when selecting a 3D tools is the import/export capabilities it has, there is no point in creating a fantastic 3D figure if you can not export it in an appropriate file format that your game can use. Here are some popular examples of 3D tools you can use:

Tools Autodesk Maya http://www.autodesk.com

License

Notes

Commercial Excellent for animations (like the ones you have seen in animated movies) Special comment here: Please do not think that just because you buy Maya you can now create an animated movie like the ones created by Pixar. Anything good requires patience and training (regardless of the tool), and sometimes, the right plugin (which can be an extra cost aside from the software) Commercial Best all-around general-purpose commercial 3D tool. This is the best choice if you dont know what 3D tool to use (and if you can pay the price) Free Best free-3D general-purpose tool. It is interesting to note that it includes the Blender Game Engine which is a tool for creating 3D games. Very important note: many people consider Blender to have a not-friendly-easy user interface and give up on using it... but starting with version 2.5 this software comes with a TOTALLY NEW user interface so I highly recommend you give it a try.

Autodesk 3ds Max http://www.autodesk.com Blender http://www.blender.org

Truescape http://www.caligari.com GMAX http://www.turbosquid.com/gmax AC3D http://www.inivis.com/ Milkshape

Free

Very good 3D tool that used to be commercial. It has one minor issue: it is unclear if new version will be released. It is old but it is good to keep around for its import/export capabilities

Free

Commercial

Commercial This tool offers an interesting list of import/export features used by many video games, some people have a primary 3d software for the main work and secondary tools like this one just for http://chumbalum.swissquake.ch importing/exporting from/to multiple file types.

Lucu guide for creating videogames page 13

Modo 401 http://www.luxology.com/ Cinema 4D http://www.maxxon.net

Commercial

Commercial

Choosing a 3D tool is usually not easy because of the great amount of features and options each package has to offer and beginning game developers usually do not know 3d terminology like nurbs, zbuffers, shaders, etc. So here are some tips to help you on your selection: The most popular in the gaming industry are: 3ds Max and Maya. 3ds max is best as an overall 3d tool (it can to many things) while Maya is best used when you already know your basics and want to specialize in character animation. If you go with the free option, then Blender is probably your best choice

Here is one interesting link that compares some 3d tools: second lifes mini guide to 3d tools ( http://wiki.secondlife.com/wiki/Sculpted_Prims:_3d_Software_Guide ).

Audio design
One important advice for sound in video games is: keep it small. This is because audio is just another resource and it is used often (example: in a typical game one sound effect may be repeated every time you press a button), so it is not enough to know about audio, but also to know about audio compression techniques (mp3/ogg) and to understand that sometimes a music background can be just a simple instrumental music (MIDI format) and not necessarily a full recorded song (like mp3 format). Here are some popular examples of audio tools you can use:

Tools Adobe Audition http://www.adobe.com/products/audition Audacity http://audacity.sourceforge.net

License Commercial

Notes

Free

So many tools and so little time!


Nobody has the luxury/time to learn all the tools, at some point you need to decide one tool over the other as a favorite or preferred tool. And if you are going to pay for the tool, the decision becomes even harder. So here are some general tips for choosing a tool: There is no best tool of all, try different options and find the one that works for you, not the one that works for company X or guy Z. Do not think that just because a software is free it is of lower quality than a commercial tool. Free software usually gets updated more often (more new versions and upgrades per year) and of course you can them easily. Inside one category, try to learn one tool and at least know the basics of the others. (or at the
Lucu guide for creating videogames page 14

very-least know the features available in the other tools). Commercial software usually has more books/manuals and tutorials/videos available. And I mean good professional documentation, not just some amateur tutorial of tool X created by a crazy guy that names his website lucu :) One good guide to choose a tool is to verify how many books about that tool are available in bookstores like Amazon.com, that gives an idea of how popular the tool is. Commercial software offers the best options for certification, this is useful if you later on plan to use your skills to apply for a job. Read some video games magazines (look at the Resources appendix later in this guide) and check out what are the popular tools used in the video game industry. Ask and solve these questions for the tool: what plugins are available? cost of the plugins? Can I create my own plugin?

Game programming
Here is where you join and mix all ideas, designs and graphical resources and produce software. Often the beginner game programmer is tempted to code his first game with the programming language he knows best. My advice is to explore other programming languages first, here are some options:

Language Actionscript

Notes Pros Create games that can be easily embedded in a web page. You may have already noticed that the Internet is flooded with mini-games you can play on-line. We can easily say 99% of those games were created with Flash. Flash player (the run-time the game needs to play) is installed in more than 90% internet browsers and if not installed it is very easy to install by the final user (the player). Lots of books available for creating games with ActionScript/Flash

Cons

Limited 3D capabilities. Programming tool (Flash IDE) has its focus into art design, not into code programming. Limited multiplayer capabilities. You can use TCP, but UDP is not available (yet) as an option. This means you can create a multiplayer game for approx 5 to 20 users, but scalability is uncertain.

Python

Pros Very easy high-level language to learn. Very good sites for creating games with Python, for example: PyGame ( www.pygame.org ), Panda3D ( www.panda3d.org ), Blender Game Engine ( www.blender.org )

Cons Programming syntax is a little bit awkward, you either like it or not. Programming IDEs are abundant, but they are not very user friendly. Recent version of

Lucu guide for creating videogames page 15

Netbeans and Eclipse PyDev plugins are changing this though. C++ Pros Cons Learning curve is high. If you are beginning to create video games I recommend you stay away from C++, unless you are already familiar with the language. If you insist in using the language then I recommend buying a commercial game engine like GameStudio ( www.conitec.com ) to help you in the process. Offers features and power to create very complex games with high level of graphical detail and fast performance. Top commercial games are usually created in C++. Huge amount of books and documentation about C++ and game creation with C++.

Java

Pros Easy to learn language Lots of books available for creating games with Java Many tools for developing (IDEs), profiling, testing, editing, compiling, etc. Many sites with info on how to create games with java, for example: LWJGL ( http://lwjgl.org ) , Slick (http://slick.cokeandcode.com ) , JPCT ( http://www.jpct.net ), jMonkeyEngine ( http://www.jmonkeyengine.com )

Cons Lots of options and libraries sometimes create confusion on beginners that do not understand where to start. This is applies not just to game development but to java development in general. This guide will focus on java development in later chapters so more detail about java game development will be covered then.

The most important component to include in your video game: FUN!


No matter what technology you use to create your video game, without the fun element it will not be a good game. So, it is important to understand what fun is. The best definition of fun can be found in the book Theory of fun (see the library section of this guide for details). It is a must-read for anybody trying to make a video game. Ill try to give a little definition of what fun (applied to games) is: A fun game is the one that offers an interesting challenge to the player and makes him want to play the game until the challenge is conquered. But, the trick is to make the challenge not too hard (it will cause frustration) or too easy (it will cause boredom), so that the player can keep on playing. Try to make funny games, and the same time, have fun while doing them! Here are some tips to help you better understand the concept of fun: Remember the games you played when you were a kid. (Better yet, find some kids and play with them!). Play games that require social interaction between people (like board games or Dungeons and Dragons or Role Playing games) and look what works and what does not work in them.

Lucu guide for creating videogames page 16

Chapter 2: Decision time


What programming language should I use for my game?
This is usually the first question a beginner makes and sadly, is the wrong question to start with. Just like when we develop any other kind of software, programming languages are tools, not objectives. And as such we need to first think and design what kind of game we will create, then find the best programming language for the job. One way to solve this starting dilemma, and at the same time prepare a foundation for the design of the game, is to think about the features our game requires to run and to be available for our intended target of players. We can think of it like a Platform for our game. So here are some common Game Platforms, try to select the best fit to support your game.

Gaming Platform

Notes

Recommended language to use

The mobile AKA: the player is always connected, platform anywhere. The best example of this platform is games for cellphones.

If you aim at classic cellphones you can use Java J2ME to create games that work on many cellphones. Be aware that programming for different devices can sometimes be a pain due to different hardware implementations. Also be aware that Gamers: almost everybody has or will have a cellphone. And more and more people will start cellphones are evolving into smart phones (iPhone/Android powered phones) where J2ME is no to get advanced smart phones and leave longer the best option. behind classic phones. Gamers are mostly casual gamers that want to play simple 10 In the specific case of iPhone, the most common dollar-games choice is the objective-C programming language, but recently more tools are available that allow you to program for iPhone in other languages like C++ or Lua (or just using web programming targeting the iOS web browser). Forgetting the technical details for a moment, this platform has a very promising future as a market. Trend reports that in the future more and more people will play on their phones. Using the C/C++ language you will probably get the most of the limited hardware of this devices. Be aware that, you can use Flash on some mobile devices, but that of course will limit the features and performance you can get for your games.

The console platform

XBOX, Playstation, Nintendo Wii Gamers: this is a though market, usually people that owns a game console has higher expectations, after all they will be paying 50+ dollars per game and want to make the best use of their consoles. Computer PC Gamers: wide range! from teenagers looking for the greatest action game to housewives or business men looking for casual games.

Microsofts C# is the recommended option for XBOX. For the other consoles C/++ is a safe bet since you will usually want performance and portability. Java, Python and Flash are not recommended (not even valid in some cases) options. For casual quick web games that you can embed in almost any website: Flash. This will immediate access to many people to your game. But, there is a technical limit on what kind of games you can create with Flash.

The PC platform

Lucu guide for creating videogames page 17

One interesting point to notice is that, PC games are expected to have higher levels of complexity than other platforms, basically because a PC has more features (mouse, keyboard, and joystick) and also because people that use a PC usually do it for hours, so there is more room for details in a game.

To quickly start making 2D or 3D games: java or python To go deeply and seriously about high performance games that use the latest and greatest graphics and hardware: C / C++. But this also means you have the time and resources to invest in making a game with C or C++.

Game engines
Just like any other software development, when creating video games you should always try to re-use components instead of creating everything from zero. This is a good software practice, that is why we have libraries, frameworks, and in the case of video games, we have Game Engines that are software components that already provide functionality for video games and we can just re-use and concentrate more on our game logic. We will explore what are these common functionalities most video games have, but here is a brief list: Graphics components for displaying 2D/3D graphics. Networking functions (for multi-player games) Audio functions Physics modules Animation frameworks Maps management (for multi-level games)

Using a game engine is recommended since it will help you create games faster and easier since many of the functionalities described above will be ready for you to use. Be aware that sometimes game engines support a primary programming language and secondary programming languages, often referred as scripting options. This is because some engines offer core functionality with a lower level (and more powerful) programming language and delegate some task management or game logic management to a higher (and more easy to use) programming language. The reasoning behind this is: provide power features for your game and at the same time an easy to use language to control it. A very good example of this situation is the Panda3d engine: it uses C++ for its core high-performance demanding features, but can be easily controlled with the Python language. Here is a list of some popular game engines available:

Game Engine

License Free

Language Java

Comments

Java Monkey Engine


http://www.jmonkeyengine.com

(+) Great for 3D games (+) Very complete game engine (version 2, version 3 is still in beta but final will be released on 2011) (+) Very active development (+) Supports a variety of 3d model formats

Blender Game Engine


http://wiki.blender.org/index.php/Ga me_Engine

Free

Python

(+) Very easy to use, you can even create games without programming (+) Create 3D games easily

Lucu guide for creating videogames page 18

(-) It is not clear how to program advanced features like: networking (-) Unable to use it for commercial games Irrlitch
http://irrlitch.sourceforge.net Free Free C++ Python

(+) Great features/options (like world editor) (+) Great for 3D games (+) Very complete game engine (+) Very active development (+) Very good documentation (+) Cool feature: the latest version allows you to deploy web games (like flash)

Panda3D http://www.panda3d.org/

Away3D http://away3d.com/

Free

ActionScript

(+) Great for doing 3D games in Flash (-) 3D performance is not very good in Flash. Dont expect to create a DOOM close with Flash 3D

PyGame http://www.pygame.org

Free

Python

(+) Great for 2D games (+) Very good documentation

GameStudio http://www.conitec.com

Commercial

C++

(+) Great for commercial games (+) Great introductory price (+) Has a lite version free and easy to use for beginners

Microsoft XNA http://www.microsoft.com

Commercial

C#

(+) Excellent option if you plan to make DirectX games for PC and or XBOX (+) Very easy to learn for beginners. LOTs of documentation and tutorials available. (+) Can create 2D and 3D games.

LWJGL http://lwjgl.org/

Free

Java

(+) Great for 2D games (+) Can be used for 3D games also because it is an implementation of OpenGL, but hard to use since it only provides plain OpenGL, with no scenegraph or extra functionality. (-) Not very good documentation (-) Not recommended for beginners (-) Not easy support for 2D animations (animations like animated GIFs for example)

JPCT http://www.jpct.net

Free

Java

(+) Great for 3D games ( -) Not open source

3DzzD http://dzzd.net/

Free

Java

(+) Great for quick 3D web games (-) Not very good documentation (-) Does not support 3D animations (models like MD2 for example) easily

Slick
http://slick.cokeandcode.com/

Free

Java

(+) Great for 2D games

Lucu guide for creating videogames page 19

(+) Supports 2D animations (+) Does not hide OpenGL from the developer (-) Documentation is work in progress Java FX http://javafx.com/
Free Java

(+) Great for 2D games (-) Still in early versions, but very promising for the future

GTGE http://goldenstudios.or.id/p roducts/GTGE/

Free

Java

(+) Good for 2D games (+) Supports 2D animations (+) Does not hide OpenGL from the developer (-) Initially you create basic games that use AWT/Swing technology (which does not take advantage of hardware acceleration) but after you study the engine you can later add OpenGL or LWJGL or JOGL (with add-ons) to improve your visuals.

Game maker http://www.yoyogames.co m/gamemaker/

Commercial (with free option)

Propietary language

(+) Great for 2D games (+) Can be enhanced with custom DLLs (+) Good documentation available (+) Recommended for beginner game creators

Unity 3D http://unity3d.com/

Commercial (with free option)

JavaScript C# Python-like script

(+) Great for 2D games (+) Can be deployed as a web game (+) Good documentation available (+) Can be used for iPhone and Android development also (with a paid optional module)

Xith3D http://Xith3D.org

Free

Java

(+) Great for 3D games (+) Easy to extend/build games upon the base components. (+) Good documentation available inside the framework download. (+) Lots of examples provided with the framework download. (+) Supports a variety of 3d model formats. (+) Integrated physics engine. (+) Input system. (+) HUD support. (+) Can be used for 2D games also (I have not tested this feature myself yet, but will do when I get a chance) (-) New versions are not released frequently, but you can always download directly from the source repository.

SHIVA www.stonetrip.com

Commercial (with free option) Free

Lua

(+) Great for 3D games (+) Allows deployment on iPhone/Android/Wii/Web

LVE love2.org

Lua

(+) Great for 2D games (+) Another easy to use game engine recommended for beginners

Lucu guide for creating videogames page 20

(although the lve team prefers to call it game framework)

An extensive list of game engines can be found at: Devmaster game engine database ( http://www.devmaster.net/engines )

DirectX (Direct3D) versus OpenGL


Some people might say this is the classic Microsoft versus the world debate, but this topic is more than just that. Preferences and bands aside, let us concentrate on the facts: sooner or later you, as a game developer, will be faced with the choice of using DirectX or OpenGL for your game. Those two are software libraries that help you create your games. Usually some engines are just interfaces between your game code and the graphics library supported by your hardware (DirectX or OpenGL). Nowadays almost all modern hardware (that is, graphics video cards, CPUs, processors, mainboards) supports both libraries very well. And, technically speaking, both libraries are great to use and offer a wide arrange of features. In most cases, you do not need to worry about this topic. It is better to worry about choosing the right game engine for you and let the engine handle whatever graphics library it needs. There are even some engines that can handle both (like Irrlicht game engine). So why we need to worry about this? Both libraries are good and you can find a huge amount of info about them (including comparisons) on google and using one over the other does not guarantee your game will be better. But it is important that you know about them as a reference. Here are some things you need to consider about them: DirectX usually offers more eye candy features before OpenGL does. For example: DirectX version 10 (current version as of Nov2009) is out there and the games that use it (not a lot do) show impressive graphics and realistic effects. Google for directx10 games to get a list. But sometimes this just means that many famous/commercial games use DirectX and more known/popular. To use DirectX10 you need at least Windows Vista and very modern graphics card. (Remember Im writing this in 2009, things might change in the future) so your development options must be focused on that. OpenGL on the other hand, is supported by many platforms. Again, later versions of OpenGL of course are only supported on modern graphics cards, but is available for many platforms. One can rush and say that OpenGL then is better because it is multi-platform, but that sentence can easily be countered with a simple question: how big is the market for gamers in platforms other than Windows? You will get of course different answers depending on who you ask, but regardless how much you love (or hate) Windows, you need to focus on what gaming market you want to address (and possibly specialize into). There are some that say that OpenGL is better because it can be used by many different languages. A good example about this is that the NEHE web page ( http://nehe.gamedev.net/ ) offers different ways to use OpenGL with different languages. But Microsoft can surely say the same thing about DirectX because the .NET framework and the Visual Studio tools can support a long list of programming languages, including ones that are not Visual Studio classics like Visual Basic and C++, but also others like Python. Beginner game developers tend to think that they need to learn DirectX or OpenGL to make games. There are even some books available with titles such as How to do games with DirectX/OpenGL. My advice for beginners is, again, to better concentrate on choosing a good game engine.
Lucu guide for creating videogames page 21

I recommend you first start with a good game engine/framework and worry about directX versus OpenGL later, but dont forget that you will eventually have to deal with DirectX/OpenGL libraries as you advance in your game developer path, usually when you want more performance, extra features or custom functionality.

Final recommendations
If you wan to create games as fast as possible without programming: Try GameMaker Try Blender Game Engine Try any authoring software (lets you build applications without coding) If you wan to create games as fast as possible (and are not afraid to program a little): Try GameMaker Try Flash Try PyGame You want to be in the cutting edge of gaming and use the very latest technology possible : Dont make games, stop making software, try to be a poet or artist instead (or create the art for a game) :) Seriously: stop thinking like that if you want to create software (good software that is). Try Flash Try the Unity 3D game engine or the SHIVA game engine Try any game engine that lets users play your game inside a browser Try making games for iPhone/Android/whatever mobile device is popular. Try Java, C#, XNA or C++ If you want to go deeper into the gaming world, you need to find tools, libraries, books on different gaming topics and you MUST learn to program. You will find that C++, XNA, C# and Java have an incredible amount of information about gaming topics so you can choose any of them.

You want to do a web that most people can see and/or play. This is a very good option, specially if you are new in the business and what to gain some fame or make a name in the gaming world You want to make games but are also interested in study, research and apply game-related topics, like virtual worlds, social interaction, multiplayer, artificial intelligence, etc and want to go beyond simple mini-games... and probably make games as a career or long-term proyect.

My (very) own personal decision


In this section I will put a little story of how I took my decision on what tool to use for my games. You still need to make your own decision, but Im putting this here just as a reference with the hope that it may be useful information for someone trying to do the same, so here it goes: It all started in 1984 when I got a Commodore 64 home computer and programmed a game in Basic language... and.... (...ok... lets move the story a little forward...) I know java so as a natural option that was my first choice, but decided to explore other languages first. I dont want to make simple mini-games, I want to be able to do medium/big games. (of course I will make little games at the beginning). Flash/Action script was my first topic to review. I was able to create games quickly and easily. I am basically a tech guy (not an artist guy) so I had a hard time with the Flash IDE.
Lucu guide for creating videogames page 22

I then tried another ActionScript IDE (FlashDevelop) and also tried another actionscript frameworks (Flixel, Away3D) with very good results. I was happy. Then dropped action script when I realized that multiplayer capabilities are very limited. TCP is available but I needed UDP connections. I found some Flash multiplayer games on internet, but they had very low performance when more than 5 users where connected at the same time. I want to create a multiplayer game, that is a very important goal for me, it is more important than showing very nice/high detailed graphics. So then I tried python. The Blender game engine got my attention, but currently (August 2010) the whole engine is being redesigned. Maybe I will have to wait for the new version to be available. I dont want to make my game with any beta or alpha tool. My next option was Panda3D game engine. I did some experiments and got good results. Very nice game engine and tutorials available. But I was never able to find a good Python IDE. Since I am a tech guy I dont need just a basic IDE for writing code and compile, I demand a very high-quality IDE with many features like debugging, profiling, .etc. As a programmer I have been spoiled with IDEs like Visual Studio and Eclipse and I wanted something at least close to them. I found some commercial Python IDEs that were very good, but were out of my budget :( I then discovered IronPython, which lets you code Python inside Visual Studio!.... but then found that Panda3D is not compatible with IronPython :( Also found out that Python lacks (or have but are limited for my goals) some extra tools I need, like: obfuscators, more profiling tools, installer generators. So I then turned to Unity 3D. Unity 3D is a very good game engine. But I discarded it because in order to run a multiplayer game you need a server component that runs a Windows server (or Mono over linux). My game project only has a plain linux (without mono) server so I had to discard this option. So, I returned to java. I was NOT going to code a game from ZERO, I had to choose an engine or framework. My first option was to use the Java Monkey Engine. But I found the documentation hard to understand and I believed its better if I do some little game first... but... the Monkey Engine is for 3D games... so I decided to start with something more easy and just 2D. I then looked at GameMaker. Very good/easy/little framework for small 2D games. Liked it from the beginning... but discarded later because the multiplayer options would need to be coded as an extra DLL in C, Delphi or C++ ..... I know those languages but not much as to write a network communications module with them. Returning to java... I found two very nice 2D game engines: Slick and GTGE. I tried both and did some little games with them.... they are both good but finally I decided for GTGE because I liked it more (easier documentation for me, more examples available). I dont think one is better than the other, its just that GTGE works best for me. So, for 2D games, I will go with GTGE. Now, for 3D games I found the Xith3D framework, which has easy documentation, lots of examples and I tried it a little bit and the demos work fine on my computer. I will make a 3D with this one in the future and expand this guide. So, the rest of this book is about how to make a small 2D game with java and later, how to make a 3D one. One more thing: while I was doing all of this, I was looking at every book/review/magazine/conference about gaming I could find... if you look at Appendix A of this document you will find some of them.
Lucu guide for creating videogames page 23

Chapter 3: Making a 2D game


Computer game flow
Before we start to get our hands into actual code, there is one more piece of theory you need: the computer game flow. Whenever you play a game in a computer, this is basically what happens:

START

Load resources into memory (sounds, images, maps, libraries, .etc)

Show initial menu/options. Example: -Start -Options -Credits -Exit

Render objects/graphics in screen.

Receive INPUT from user (keybard, mouse, joystick, .etc) (User is playing!) Do internal game logic (if player is hit with a bullet reduce life by 5 points...etc). Decide what sounds/images to take/put/move from the screen based on logic and input.

Repeat until game ends or user exits from game

Re-paint objects, play sounds. Redraw game scenario.

END

Lucu guide for creating videogames page 24

You need to keep this in mind while developing a game; it is important to make a good design and will also let you know important topics like: Loading resources (images, sounds, .etc) takes time and memory, so try to do it only ONCE at the beginning of the game. The complete game is re-drawn and re-displayed many times per second in the screen. After your game logic was executed, so try to make your game logic small and efficient to guarantee your game will run smooth and easy on the hardware. This is one of the reasons why many highquality games (with very nice 3D graphics) are usually done in languages like C or C++ because they are very fast. But, at the same time hardware is getting faster and faster everyday (and other programming languages too) And most importantly: no game (or software) can be saved from a bad programmer :)

Setting up the development environment


We will be using JAVA, the Eclipse IDE and the GTGE framework. If you want to use the SLICK framework I left in Appendix B (slick+eclipse) of this document a little help on how to set it up. This document cant teach you how to program in java, there are already many books available for that. If you do not know java stop reading this book, go learn java first (at least the basic steps), then come back. This document cant teach you how to use Eclipse IDE, there are already many books/tutorials available for that but even if you never used Eclipse before continue reading because it is very easy to learn. So, go to Appendix C (gtge+eclipse) of this document and prepare your PC.

Making a puzzle game with GTGE


By now I assume you already have your development environment ready and you read the GTGE basic tutorial and ran an example game that comes with it. And be sure to have the GTGE API DOC near and handy, you will need it as a reference. In this section, I will guide you though the steps of making a small puzzle game with GTGE. You will not become a master in GTGE (or in gaming), but it will give you a guide so then you can create your own games. The program for this game is a single java file. But we will go step by step so I will present you many versions of the same program, from the bare basics up to the full game. If you are in a hurry rush and read the last version of the program... if you want to learn read it each version one by one. You can find each version (java program) of the puzzle where you got this document from, along with the graphics. Before we start, create a source folder called puzzle (if you have not done so already). Puzzle version 0: Why a puzzle? Design a puzzle. First, why a puzzle as a first example?. Well, because it is easy to code, it has no moving parts (animations) and requires few resources (any graphic will do) About the design, we also have an advantage here: anybody knows how a puzzle works (you have a lot of pieces, now try to put them together to form a full image) so there is not thinking here left to do. We will be creating a puzzle of 8 x 8 (64 pieces). The player just needs to put each piece in the correct
Lucu guide for creating videogames page 25

place to form the final picture. Puzzle version 1: just display a background Inside the puzzle folder, create a program called PuzzleGame inside a puzzle package and put the graphics inside a resource folder. Something like this:

Copy version 1 of the puzzle and run it, you should see a background on the screen:

The 8 rows by 8 columns grid to the left will help the player understand where the final position of the pieces will be. Notice that this is a complete image, the grid is not generated by the code. Use any imaging software to create a background and add the grid on it. Notice also that the background has the same resolution (600x500 pixels) as the declared window for the game, in this line: game.setup(new PuzzleGame(), new Dimension(600, 500), false); Also notice that we have the basic game flow in place already, we have a initial place to load resources here (and it will be executed ONLY ONCE by the computer):
public void initResources() {
background = new ImageBackground(getImage(resource/background_forest.jpg));

Lucu guide for creating videogames page 26

We have a place for your game logic here: public void update(long elapsedTime) (...

And a place were everything is re-displayed (rendered on screen) again: public void render(Graphics2D g) (... So far nothing great is happening in our game, we are just displaying the background image... and displaying it again... and again... and again... many times per second. The GTGE engine takes care of that. Puzzle version 2: lets put the puzzle pieces on the screen Now put version 2 in the project and run it, you will see the pieces now:

What we are doing is reading an image that has the complete image (completedPuzzle.jpg) then cutting that image into pieces (64 pieces) with the splitImages() method: BufferedImage[] biarray = ImageUtil.splitImages(bi, 8, 8); That generates an array of BufferedImage objects (which are just images created from the original image) Then we create a sprite with each image and also put them like a deck/stack to the right of the screen with this code:
for (int i = 0; i < biarray.length; i++) { puzzlePieces[i] = new Sprite(biarray[i]); puzzlePieces[i].setBackground(background);

puzzlePieces[i].setLocation(initX, initY);

Lucu guide for creating videogames page 27

We create a sprite with each image because then it will be easier to manage (do operations like show, hide, move, rotate, .etc). Also notice that we added in the render() and update() methods the necessary code so that the sprites get displayed and updated on the screen. Puzzle version 3: adding mouse functionality Now put version 3 on the project and run it... you will notice now that you can pick a puzzle piece and move it around. If you click again the mouse pointer will drop the piece and you can now pick another piece and mouse it around, it will just follow your mouse. How to accomplish this? Here is how: First, we need to let the program know that we want to listen to mouse events (clicking and moving) by implementing a listener: public class PuzzleGame extends Game implements MouseListener Adding the necessary methods to capture the events: public void mouseClicked(MouseEvent arg0)... public void mouseMoved(MouseEvent arg0)... You only need to implement the methods for the events you are interested in. You will notice that in this game we only care when the player clicked a mouse button... so.... only the mouseClicked event has code inside. Then, you need to register the program as a valid one for listening to events, here is the code to do that:
public void initResources() { // do this to listen for mouse events

((AWTInput) bsInput).getComponent().addMouseListener(this);

Very important note: the GTGE engine already has some methods you can re-use for listening for keyboard and/or mouse events. You can just re-use them instead, but, I am showing you this alternate method because it has one advantage: your game can respond to a mouse click ANYTIME. By that I mean that the method mouseClicked() will be executed any time the user clicks a button while the game is running so your game can immediately react to that and you as a programmer can have better control of your game and your game flow/design will go smoothly because the other alternative is to constantly ask the computer if a button was clicked (not very useful)... by using this method we go the other way: the computer will let us know when a button was clicked. The next important piece of code in this version you need to notice is the one that checks what piece (sprite) was clicked (if any). To do that we use the function checkPosMouse() whenever we click the mouse:
public void mouseClicked(MouseEvent arg0) { if (selectedPiece >= 0)

Lucu guide for creating videogames page 28

{ selectedPiece = -1; return; } // else, check if the mouse was clicked over one of the pieces for (int i = 0; i < puzzlePieces.length; i++) { if (checkPosMouse(puzzlePieces[i], false)) {

selectedPiece = i; And... on the game logic section of the code, we make sure that selected piece is displayed where the mouse is. We use two functions (getMouseX/getMouseY) provided by GTGE to know the current mouse position for that:
public void update(long elapsedTime) { ... if (selectedPiece >= 0)

puzzlePieces[selectedPiece].setLocation(getMouseX(), getMouseY()); And thats how we can pick/drop/more the pieces around. But it is missing two little details that we will check on versions 4 and 5 coming next. I call them human touches because they make the game more human friendly (and when you do games this is a very important goal to achieve). Puzzle version 4: adding a little human touch Our little puzzle example here already has the functionality of a basic puzzle (move pieces around to try to form the complete figure), but you may have already noticed that is not easy to aim the pieces on the grid. It would be great if the pieces just snap into the grid, right? like in real life puzzles, right?, well, with a little math and a little code added you have that functionality in version 4 of the puzzle. Copy it to the project and run it, you will now notice two things: 1. The piece follows the mouse, but it is not centered to the cursor (simulates your real life hand grabbing a real life piece) 2. When you drop a piece it snaps to the closest cell (simulates a real life piece when it snaps to the rest of the puzzle) Isnt that nice? here are the two pieces of code that was enhanced from version 3 to accomplish this: puzzlePieces[selectedPiece].setLocation(getMouseX() - 25, getMouseY() - 25); The -25 offset just moves the piece to the center (because the pieces is 50x50 pixels) public void mouseClicked(MouseEvent arg0)
Lucu guide for creating videogames page 29

{ int theSelectedPiece; if (selectedPiece >= 0) { theSelectedPiece = selectedPiece; // if a piece is already selected, just unselect and return selectedPiece = -1; // before we drop the piece, we will auto-move it a little more // just so it snaps into one of the cells of the grid if (getMouseX() >= 3 && getMouseX() <= 403 && getMouseY() >= 3 && getMouseY() <= 403) In this section of code, we just ask if the mouse is inside the grid boundaries, then search for the nearest cell and position the recently dropped piece there. One thing to notice is that we are using an extra variable here called theSelectedPiece. You may consider it unnecessary since the variable selectedPiece already has that value and you can be right, but I placed it for one reason: safety. You need to remember that the method mouseClicked can be executed and ANY time so I recommend you free the variable selectedPiece as soon as possible and just use a copy of it during the rest of the logic. When your game gets more complex you may have for example another method that rotates the selected piece when a key was pressed and you can bet that other method can also be executed at ANY time. Puzzle version 5: adding a button Our puzzle game needs one more extra feature before we can call it complete (for a basic game that is). Every puzzle (in real life puzzles that is) comes with a complete picture (in the box where the pieces came in) that shows you how the completed puzzle looks like. We will add that feature to your little java puzzle game. We will add a button that displays an image with the completed picture. Before we continue, download the GUI add on for GTGE and run the example it comes with to get familiar with that plugin for GTGE. You can just put the add on source next to the GTGE code, they have different package names so they will not mix with one another. If you get an error like file not found or image or resource not found when you run the GUI add on you may be missing the icon files, just put them here:

Lucu guide for creating videogames page 30

So, copy version 5 into the project and run... you will notice now there is a button that when pressed, shows the complete figure. If you click anywhere on the screen you return to the puzzle window and can continue playing. Here is the code to make it happen: Code to add a new sprite (the complete picture) and notice that later on we do not display it immediately, but only the a flag is turned on:
fullPicture = new Sprite(getImage(img/full.jpg)); fullPicture.setBackground(background);

fullPicture.setLocation(0, 0); Code to add a button to the screen:


TButton button1 = new TButton(show picture, 440, 280, 100, 40) { public void doAction() { showFullPicture = true; } }; frame = new FrameWork(bsInput, getWidth(), getHeight());

frame.add(button1); Notice that it just turns on (true) the flag to display the full picture, later on the render() method will take care of actually displaying it on screen. And the render part is here (we show the fullPicture sprite if the flag is on, we do not render anything else on screen otherwise and just return):
public void render(Graphics2D g)
Lucu guide for creating videogames page 31

{ background.render(g);

if (showFullPicture) { fullPicture.render(g); return;

Lucu guide for creating videogames page 32

Chapter 4: Making a 2D multiplayer game


Some games can be played by more than one person at the same time and this creates a multiplayer game where many people compete (or collaborate) inside it. In this chapter we will explore the basics of how to achieve this. Multiplayer games are harder to create but if done well it is possible to create virtual worlds or massively multiplayer online games (MMO) were thousands of players can share a wonderful experience playing together.

And dont forget that games are fun, but multiplayer games are even more fun!

Networking basics
A network is a group of computers interconnected together in a way they can share resources (like printers, spaces, files). For our case they will share a common application: a game. When trying to achieve a multiplayer game there are different ways to connect these computers, but the two more popular are: Client/server method: This is probably the most used connection type for multiplayer games and is basically one (or many) computers working as servers and the players (clients) connect to one or many servers. One key thing to notice is: all information related to the game is controlled by one or more servers. If a player wants to send information to another player it must go though the server.

client-server connections

Peer-to-peer method (also known as P2P): In this type of connection may or not have one or more servers, but the difference here is that players can connect to other players without the need of a server. Sharing software like kazaa, emule, napter made this type of connection very popular.

Lucu guide for creating videogames page 33

peer to peer connections

Connection type comparison: to understand them better and decide which one to use for your game, lets compare them both.

Client-Server Security Speed Deployment


Easier to secure because the server can manage/control all data traffic between players. Slower because data MUST travel through the server first before reaching the final destination. Allows a better distribution of the game because many central pieces of the game can just remain in the server and player only get client pieces of the game.

P2P
Hard to secure because players are free to share data without server supervision. Faster because direct point to point connections can be established. Complexity grows as the numbers of players increases. Game logic needs to be managed in all places the game is installed.

As a recommendation it is a good idea to start with client-server games and only if you really need to use P2P then go for it. Many game design books even consider P2P as evil and that should never be used, but dont go to extremes and keep your mind open, its good to know the tools in case you need them, for example here is a good use of P2P: imagine a multiplayer game where some players need to exchange data frequently and that data is not relevant for the game logic, for example they need to talk (exchange audio) to each other while they play, in this case the game could be client-server but may open a direct communication between some players for them to talk freely. Protocols: TCP or UDP The next decision to make is to use TCP or UDP as a protocol to transfer the information. TCP is slower but reliable (data is guaranteed to arrive at destination) while UDP is faster but unreliable (data may be lost). A quick look may discard UDP immediately but again it is important to know both options and use each one when needed. Here is a comparison to understand them: TCP communication protocol UDP communication protocol
Faster, but unreliable. This is useful to send data that is not very critical for the game and that changes very frequently. Example: chat between players.

Speed

Slower, but reliable. Useful to send critical data for the game like events and game logic data.

Also useful to send big amounts of data where a little loss of data is harmless. The best example of this is video. If there is one or two frames missing in the video transmission are not a big deal.

Lucu guide for creating videogames page 34

Game server
The next step is to create a game server, which is the game logic that will control the game data traffic. Remember we discussed about game engines before? Many game engines offer networking/multiplayer capabilities out of the box so you dont have to worry about them. In this guide what we will do is use an existing networking software library called MINA to help us build a game server. So go ahead and download MINA ( http://mina.apache.org ) and install it and run the example called chat server which is perfect as an example of a basic client/server application, then read its documentation to get familiar with the technology used by MINA.

Puzzle game - multiplayer version


Now lets re-design our puzzle game and turn it into a multiplayer puzzle. Here are the design considerations: The game will allow the player to type his name so that other player will know who entered the game session. The game will enforce collaboration, so, all players will work together to complete the puzzle. For this to happen, every time a player puts a piece on the board the game will notify other players about this event an update the screen to reflect the change. The final effect is as if all players are looking at the same table where a puzzle is being assembled (like in real life).

Using the MINA libraries I created the multiplayer version of our little puzzle game we did before. The result is in the project puzzle_multi, import it into Eclipse IDE and you should see something like this:

Lucu guide for creating videogames page 35

The server-network-logic of the game is inside the package server. The client-network-logic of the game is inside the package client. And the puzzle package contains our usual game, but is an enhanced version that uses the MINA libraries to communicate with the server. The programs used to handle communication logic have been taken from the chat example that comes with MINA, we just re-used them to allow our game logic to chat its logic. What this means in practice is that our puzzle game now has these features: Connect to a central server. Send information about the player (name and pieces moved) Receive information about other players (sent by other players and broadcasted by the game server) Communication will be done using standard sockets and TCP.

Puzzle - Connection to a central server: This is achieved by using the MINA library to connect to a client. This logic is encapsulated inside the NetworkClient.java class, so from our game (PuzzleGame.java) we just establish the connection here:
// try to connect to the network try {

Lucu guide for creating videogames page 36

networkClient = new NetworkClient(); connectedToNetwork = networkClient.connect((Callback) PuzzleGame.this, localhost:4444, userName); } catch (Exception e) { messageReceived(*network connection to server not available*); networkClient = null; e.printStackTrace(); }

We send the IP and port (socket) of the server we want to connect to (in this example the game server is in our local computer and the port is 4444). Notice that if for some reason there is no connection, we just log the error and allow the player to continue playing the game in single-mode. The connectedToNetwork flag is very important because it will become true only if we are connected and we use it every time we place a piece on the board (method mouseClicked()) in this logic:
if (connectedToNetwork) { // also, notify any other players (in the network) that we // placed // one piece into the grid StringBuffer sb = new StringBuffer(); sb.append(moved_a_piece).append(,).append(theSelectedPiece).append(,); sb.append(to x).append(,).append(myPositionX).append(,); sb.append(to y).append(,).append(myPositionY); networkClient.broadcast(sb.toString()); }

What we are doing in the previous piece of code is: When a user drops a piece on the grid... ...capture the piece number (id) and its position (x and y coordinates).... and... ...send them to the server using the broadcast option... this means that we want to send this information to all players connected to the game. The server logic for this scenario is very simple: just receive this information and re-send (broadcast) it to all other players. In our game (PuzzleGame.java) class you will notice an new method that will listen for incoming network messages, its job is to receive information from other players and update the screen putting the piece in the coordinates sent by other player(s):
public void messageReceived(String message) { // in this game, when we receive a message it could be that another user

Lucu guide for creating videogames page 37

// is playing and we receive the information of the // piece he/she moved // verify if it is a piece movement if (message.indexOf(moved_a_piece) >= 0) { // another user moved a piece, lets move that piece in our own grid // also String[] data = convertLineIntoArray(message, ,); puzzlePieces[Integer.parseInt(data[1])].setX(Integer.parseInt(data[3])); puzzlePieces[Integer.parseInt(data[1])].setY(Integer.parseInt(data[5])); }

To make this game a simple example, the message that players exchange is just a simple String. You will notice that when a network message is related to a player move it contains the text moved_a_piece. It is important to notice this because there are other network messages as well with different information (example: player connected, player disconnected, number of players connected, .etc) so your game logic needs to understand them and do some logic based on them. For our humble puzzle game we just display any network message in a textbox at the bottom of the screen. After this overview, go ahead and run the multiplayer version of the puzzle. First run the game server (server.Main.java) then two or more clients and see it in action. Make sure you use the same port in both the server and the client and that you put the correct server IP address in the client code. Here is a screenshot of the game running in multiplayer mode:

Lucu guide for creating videogames page 38

Chapter 5: 3D games
Making a 3D game adds extra an extra dimension to our game creation process, not just in the sense of coordinates in space but in extra considerations and designs to apply. Here is a comparison of topics you need to think about: Making a 2D game
No need to worry much, just maybe the quantity of sprites on the screen, but todays hardware can handle pretty complex designs.

Making a 3D game
Always consider performance as a constraint. And keep in mind that not everybody will have enough hardware to display the pretty 3D graphics you created.

Performance

Usually the best 3D games are created using more lower level languages like C++ to gain extra performance.

Visual effects

You can create great visual effects easily (compared to 3D).

Harder to create great visual effects but when done right the result can create impressive virtual 3D worlds/games. For 3D you will need 3D graphical resources that are more complex to create and require 3D software like 3ds max or Blender.

Assets

2D graphical resources are vector or bitmap images like .jpg, .svg, .png... The scenarios, maps or levels of your games may also need to be created with special 3D software or 3D terrain software.

And dont forget that games are fun, but multiplayer games are even more fun!If you are new to 3D creation (games or in general) It is strongly recommended that you first use a 3D engine like Shiva or Unity or DX studio or Blender Game Engine to help you in the process and avoid programming. This is because you first need to understand and think in 3D before you can program in 3D. This means you need to first get comfortable with topics like: 3D coordinates, Vectors, Spaces, Volumes, .etc.

In this chapter we will create a 3D game with the help of the Xith3D engine, so first please go to Appendix D to learn how to setup Xith3D in your development environment and make sure you run the examples that come with the engine and look at the code to get familiar with it.

3D basics
Before we do our game we need to get familiar with some 3D concepts first. 3D objects: This can be any resource created by special 3D software (like 3ds max/Blender) and usually have the extensions: 3ds, max, obj, etc. They can represent game characters and in those cases they are often animated and have the extension: md2, dae, etc. The obj 3d file format is very popular and almost all 3D software is able to read/write it.

Lucu guide for creating videogames page 39

Example of 3D objects you can use in your game

The md2 file format is very popular for animated characters. The game Quake made it very popular and you can find many websites that allow you to download md2 files for fun/free. But keep in mind that this format is old and the animation it provides is keyframed/predefined animations and not skeletal animation so it is a good format to start but I recommend you study more advanced formats like md3 or .X format for game characters.

Example of an MD2 game character. Notice the list of pre-defined animations on the right. You can activate any of them during the game depending on what you want the character to do.

Skeletal animation and why you should care: We will use md2 (keyframe animation) files in this guide
Lucu guide for creating videogames page 40

because they are easy to find and use, but, as soon as you can try to learn about 3d game character formats that support skeletal animations (like collada DAE, .X format, etc) because they are better and allow you to move independent movement of the game character parts (arms, legs, head, etc) and help to create more realistic in-game animations. 3D levels: The scenario your game will work on can be just another 3d object like .obj or .dae or .3ds, but there are special tools for building more complex scenarios and create levels like Quake map (.bsp files) or terrain files like the ones created with L3DT ( http://www.bundysoft.com/L3DT ). Scenegraph: To manage and display all the 3d objects of your game, the engine will provide us a scenegraph, which basically is the stage or 3d space where we will put our objects. These objects do not float freely around but will follow a hierarchy for easier management and also because some objects actually depend on other objects, just like in real life 3d. Here is an example to illustrate this: A car has wheels. Wheels are objects that belong to a parent object called car. If your game has a car and you move it around it is expected that the wheels will be moved as wheel to a new position accordingly. When the car is moving forward the wheels need to rotate, but always in a position relative to the car. Please look at appendix E (Xith3D Scenegraph) later in this document for a diagram of Xith3Ds scenegraph. 3d objects (also called 3d shapes) are in the lower part of the chain. They can be grouped together. In the previous example the car may be composed of four 3d shapes (the wheels) and a big 3d shape (the car itself). This grouping affects not just position of objects but also to other attributes like: rotation, light, etc. So objects belonging to the same group (also called Transformation group) are affected by the same attributes. All objects (grouped or not) are then attached to a RendererPass who keeps and manages a sub graph, which is processed and rendered by the Renderer. It also implicitly defines the rendering order. This is important because on 3d games you dont just render all objects in the screen, the engine must first calculate which objects are visible to the player and only render those. There are some tricky mathematics involved to calculate this but luckily the engine (in our case Xith3D) will take care of those details. There is a special object called view which represents what the player can see or view according to his/her position in the 3d world of the game. This view object has its own coordinates (x,y,z) and a direction represented by a vector in the 3d world. Also, the view needs a third vector to be fully defined, the up vector, plus a screen scale, which is better known as the vertical field of view (FOV). Usually the player view is also used as a holder for the HUD (heads up display) which is nothing but a semi-transparent 2d window that shows useful information to the player during the game. Data like points of life and game score are common to be displayed in the HUD. Now we are going to put all these concepts together in an actual game so you can better understand how they are applied, look at the following in-game screenshot:

Lucu guide for creating videogames page 41

In-game screenshot showing a 3d object (MD2 file) attached to a bigger 3d object (the BSP map) rendered all together in a Xith3D environment that also has a player view object attached, and everything nicely managed by the Xith3D engine:

Chapter 6: Making a 3D game


The previous chapter was an introduction to 3D and Xith3D, now we will start to code our 3d game. The design is going to be simple because our main objective here is to learn about games, not creating a new hit. Design of the game: The player is inside a 3D maze and needs to find apples. To motivate the player to do this there will be a timer (players energy) that will decrease with time. To stay alive the player must find apples and eat them. To eat and apple the player needs to find one in the maze and click on it. The name of the game is Apple Chase.
When designing your game always put a little challenge for the player, that creates fun and emotion.

Go ahead and play the game, its the program AppleChase.java inside the apple_chase java project. Play it a couple of time to get the feel of what we will build. Here is an screenshot of the game:

In-game screenshot of the finished version of Apple Chase, the game we will be learning to do in this chapter. Notice the apple floating around and crosshair trying to catch it.

So, lets get started. We will cover the process step by step (step ZERO was of course the design). The final version of the java code is included by default in the package, so after you are done playing with the finished version, erase the code and replace it with the source code that is inside the folders appe_steps/step_x, depending on the step described next. In each step I will show you the key java code you need to add to the previous step to build your game. At any time you can use any software to compare any step with the previous step to get the full detail of what was changed.

Lucu guide for creating videogames page 43

Use any software tool to compare source code, like Araxis, WinDiff, KDiff, etc.

WARNING BEFORE WE BEGIN: Dont forget to read the previous chapter and also Xith3Ds own documentation before going forward. I will assume you already did that.

Lucu guide for creating videogames page 44

Step 1: Prepare an empty screen


Our main java class AppleChase.java is born! The basic configuration topics you need to create a game with Xith3D are: Our game is a simple example, so for now make it extend InputAdapterRenderLoop, this will provide you access to a rendering framework and access to the input (keyboard) system plus other engine internals. But on a later chapter of this guide we will see that for real games you should actually make your game extend from RenderLoop only. The main method is main() and it just creates and instance of the game and calls the very important method begin():

public static void main(String[] args) { try { // Read parameters from configuration file float maxFramesPerSecond = Parameters.getInstance().getMaxFPS();

// Load and Initialize the game AppleChase game = new AppleChase(maxFramesPerSecond);

// Start the game! game.begin();

The begin() method of course starts the game and also the very important game render loop where your game needs to do its logic and decide what to show/hide or do (remember the computer game flow from chapter 3?) You will notice that we setup video modes/resolution and register the program to listen for keyboard and mouse events in the constructor method:

public AppleChase(float framesPerSecond) throws Exception { super(framesPerSecond);

int wx, wy; // setup visual 3D environment Xith3D3DEnvironment env = new Xith3D3DEnvironment(this); ...

... canvas = Canvas3DFactory.createWindowed(wx, wy, Apple Chase); ... // register the game in the Input System to be able // to responde to keyboard events InputSystem.getInstance().registerNewKeyboardAndMouse(canvas.getPeer());

Lucu guide for creating videogames page 45

Our game will listen to keyboard and mouse events. The very first event we need to capture is that if the user presses ESC the game will end:

public void onKeyPressed(KeyPressedEvent e, Key key) { switch (key.getKeyID()) { case ESCAPE: this.end();

You will notice there is a game_config.properties file. It is an optional (but nice) thing to have because players like to choose screen modes/resolutions (among other things) so it is a little extra thing I added for your consideration. The Parameters.java class already takes care of reading that file and providing the parameters to our game logic. If you execute this code you will just get an empty screen that does nothing. And you can close it by pressing ESC.

Step 2: Loading a map


Now replace the code with the one from the folder step_2. The new feature here is that we now have a level or map or 3d scenario, however you want to call it. In 3d games usually maps are created with a 3d software (3ds max, Blender, terrain generators, etc) and in our game we just reuse an existing bsp map used in games like quake. You can easily find many bsp map files on the internet. You will also find tutorials and software on how to create them. Xith3D provides a BSP loader so we just invoke it to load our map:

private void loadLevel(SceneGraph sceneGraph) throws Exception

Model scene = ModelLoader.getInstance().loadModel(resLoc.getResource(map/tall/tallrazz.bsp));

Notice that it is important to also set the initial point of view for the player in space, you do this with two values, one for the point of view itself and another to define the vector (direction to look at):

// set the view position and focus env.getView().lookAlong(-13.3f, 3.5f, -2f, 1f, 0f, 0f);

One nice detail about BSP map files is that you can set up starting places where the player can start, in our case we will just start in position 2, but feel free to experiment other positions:
sceneGraph.getView().getTransform().set( scene.getSpawnTransform( 2 ) );

Run the code so far and you should see something like this:

Lucu guide for creating videogames page 46

BSP 3d map file loaded into our game.

Step 3: Moving around the map


Xith3D provides a helper class to easily create a first person view experience:
FirstPersonInputHandler firstPersonHandler = new FirstPersonInputHandler( env.getView(), canvas, 1.0f, 1.0f, mouseYInverted, 1.0f );

Notice that every time we add a new feature (the map, this firstpersonhandler object...) to our game we attach it to the environment object env. The default keys to move around are WSAD, run the code and move around the map. The mouse has been also activated so you can change direction with the mouse. This is a good time to realize how easy is to travel inside a 3d virtual world if you use an engine like Xith3D, it is not a good idea to start from ZERO to make a game. You will notice that you can walk through walls. Thats because we have not yet added any validation about collisions.

Step 4: Checking collisions


To handle collisions we need a physics engine. Xith3D comes with the JOODE for that:
// now activate collisions. We need a physics engine to manage that. PhysicsEngine physEngine = new JoodePhysicsEngine(); env.setPhysicsEngine(physEngine); collEngine = physEngine.getCollisionEngine();

Dont forget to notice the gravity applied as a force pulling the player down (negative Y axis):

world.setGravity(0f, -9.81f, 0f); // gRAVITy is a negative for in the Y axis

The 3d map we loaded is converted into a group of collideable objects, then the firstPersonHandler object will check if it is touching any of those objects:

//activate collisions of player versus the world //notice how the MAP is transformed into a group of objects we can collide with (collideableGroup) CollideableGroup levelCollGroup = ( clusterManager != null ) ? clusterManager.getCollideableGroup() : null;firstPersonHandler.getPhysicsObject().setSlidingColliderCheckCallback( physEngine.getCollisionEngine(), levelCollGroup );

Run the game now, and you will notice you no longer can walk through walls.
Lucu guide for creating videogames page 47

Step 5: Adding the apple


Now we will add a 3d object into the scenery. It is a .obj 3d object that you can create with any 3d software (3ds max, Blender, etc...) or you can buy it. The .obj format was chosen because Xith3D provides a loader for it and also because that format is very popular and is supported by almost any 3d software. This is the relevant code for this:
Model apple = ModelLoader.getInstance().loadModel(resLoc.getResource(apple2.obj));

Now, we need to add the apple to the MAP, we do not add it to the scene/environment. This is because, during rendering, the apple needs to be inside the map, not outside of it. Notice also that we use a helper class called Transform. This is very important because that will allow us to move, rotate or resize the apple later on in the game:
Transform appleT = new Transform(); appleT.addChild(apple); appleT.addScale(0.9f); // re-size the apple. appleT.addChild(new AmbientLight(Colorf.WHITE));// attach a light on the StaticTransform.translate(appleT, 0f, 60f, 0f);

... scene.addChild(appleT);

We are following Xith3Ds scenegraph laws here: we attach a 3d object to a Transform, then we attach the Transform (appleT) to another 3d object (the map) then that map is attached to the main scenery, which is the Xith3D environment. If you run the code you will just see an apple added to the map:

3d object (apple) added to the scene.

Important note: In the previous section of code we used the StaticTransform class in an incorrect way because we are using two classes (Transform and StaticTransform) when only one should be used. We did this just for testing purposes. You will notice that the final version of the game only uses Transform to manage rotations, position and scale.

Step 6: Game Loop


We will now start to make things more interesting. We will make the apple move around the map
Lucu guide for creating videogames page 48

by using the very important game loop Xith3D provides. The goal is this: change the position of the apple in time, by changing its position in space (x,y,z). To achieve this, we override the method prepareNextFrame() in our game. This method is constantly being called inside the game loop so it is a valid place to place game logic or prepare 3d objects just before they will be rendered on screen. In our case, what we do is re-calculate the position of the apple every 5000 microseconds, this will give the appearance that the apple is moving (basic animation procedure). Here is the important piece of code for this:


@Override

protected void prepareNextFrame(long gameTime, long frameTime, TimingMode timingMode) { super.prepareNextFrame(gameTime, frameTime, timingMode);

micros = timingMode.getMicroSeconds(gameTime);

// change the animation every 5000 microseconds if ((micros - animTime) >= 5000L) { animTime = micros;

// lets rotate the apple // appleT.addRotationY(0.01f); appleT.addRotationZ(0.04f);

// lets make it move across the map appleY = appleY + 0.03f; if (appleY >= 60f) appleY = 0f; appleX = FastMath.sin(appleY) * 10 + 7; appleT.setPosition(appleX, appleY, 0f); } }

The FastMath.sin() function is used to make the apple move doing curves. Review your basic trigonometry books to understand this.

Lucu guide for creating videogames page 49

Making a game (specially a 3d game) requires skills beyond just programming so make sure you learn your basic physics, trigonometry, modeling, arts, and pretty much a little bit of everything you can to get your mind better prepared for the challenge. Now, to help you a little with the sin() function used in this game, here is a graphic what will remind you (because you already knew this from high school, right?) what happens when you draw a line in 2D using the sin() function:

Notice that we rotate and move the Transform class, which has the apple object inside. Run the program and you will see the apple moving doing curves in space and traveling from the bottom of the map all the way to the top. Another feature we added in this step is a HUD with just a crosshair (which is a JPG):
HUD hud = new HUD(canvas, 800f); hud.setCrosshair(CrosshairWhite.png); env.addHUD(hud);

// add a HUD with a crosshair

If you are wondering how I came up with the values: 0.03f or 0.04f or 5000 microseconds to move and rotate the apple, the answer is: pure experimentation and fun! I just tested/played the game with different settings until I found one that is playable (not too easy + not too hard = fun!).

Another option to manage your game logic(instead of overriding the prepareNestFrame method) is to implement the Updatable interface. This is more useful as your game gets bigger and you need to add more code.

Step 7: Final version of the game


Now we will add details to make this more like a real game. We will add these features: Use intervals to do game logic every x seconds. Add the feature to pick objects in 3D space (needed to pick the apples) Add info to the HUD: apple count and energy (as per the game design) Make the apples harder to catch by tweaking the way the move in the map (to make the game more challenging) To review the final version of the game, just restore the code that came originally in the apple_chase project folder.
Lucu guide for creating videogames page 50

First, you will notice that the prepareNextFrame() is gone. This is just to show you another way of making your game do things every x time (intervals). But dont forget the prepareNextFrame() method because it is another tool for you available to use. To work with intervals, we add the IntervalListener interface. We will be adding Picks to the game so we also add the interface PickListener:

public class AppleChase extends InputAdapterRenderLoop implements PickListener, IntervalListener

Two intervals are needed, one to move the apple, another to reduce the energy level of the player. Then the method onIntervalHit is added to tell Xith3D what to every time the time interval is reached:

this.getOperationScheduler().addInterval(new Interval(20000L, energyInterval));

// add an interval to move the apple this.getOperationScheduler().addInterval(new Interval(7000L, appleInterval)); this.getOperationScheduler().addIntervalListener(this);

..... public void onIntervalHit(Interval arg0, long arg1, long arg2, TimingMode arg3)

The picking part is done like this: the engine casts a ray , which doesnt have a width and checks for intersection with shapes, in our case, if it intersects with any of the shapes of the apple 3d .obj object we loaded. The final effect looks like if the game is checking if the apple object is inside the players crosshair (HUD). This validation is triggered when the pickNearest method is invoked after the player pressed the mouse button. If that condition is met, then the method onObjectPicked will be triggered by the Xith3D engine and you can do the game logic required (like adding +1 to the appleCount):

@Override public void onMouseButtonPressed(MouseButtonPressedEvent e, MouseButton button) { if (button == MouseButtons.LEFT_BUTTON) { // note: we pick here the appleT object because that is the only // object we are // interesting in checking for picking pickScheder.pickNearest(appleT, e.getButton(), canvas.getWidth() / 2, canvas.getHeight() / 2, } }

....

public void onObjectPicked(PickResult arg0, Object arg1, long arg2) { // you just picked an apple! appleCount++;

Lucu guide for creating videogames page 51

The picking is obtained by checking if the apple object was inside the players crosshair (HUD) using the pickNearest method when the mouse button was pressed. If that condition is met, then the method onObjectPicked will be triggered by the Xith3D engine and you can do the game logic required (like adding +1 to the appleCount): Every time the player picks and apple, the energy counter is restored to 1000 points again. If energy goes below ZERO the game ends. This will push the player to keep on looking for apples otherwise the game will end:

public void onObjectPicked(PickResult arg0, Object arg1, long arg2) { // you just picked an apple! appleCount++; scoreLabel.setText(Apples : + appleCount); //update HUD display

// energy is restored! energy = 1000;

....
public void onIntervalHit(Interval arg0, long arg1, long arg2, TimingMode arg3) { if (arg0.getName().equals(energyInterval)) { energy--; // if energy is too low the game ends if (energy <= 0) { System.out.println(game over!, you got : +appleCount+ apples); this.end();

And thats it! Run and have fun with this little example game. Hope you learned the basics of creating a 3d game with the Xith3D engine that will allow you to experiment and create your own. The basic concepts used here (scenegraph, vectors, views, loaders) are often used by many 3D game engines so even if you dont want to use java or Xith3D you should be able to use these concepts with another language or engine.

Another way to use Intervals is to simply extend the onIntervalHit() method in an Interval extension instead of using the listener approach.

In the next chapters we will learn how to add multiplayer to this game.

Lucu guide for creating videogames page 52

Chapter 7: Making a 2D multiplayer game - version 2


An old expression says: the tiger retreats only with the intention to jump higher. And now it is our turn to go a few steps back for a moment, but for good reasons as you will see. Before we start coding our 3D multiplayer game we need to revisit our little 2D puzzle game we created in a previous chapter because there is one topic we have not covered yet: UDP. Also, this will give us the opportunity to better understand the network layer required for multiplayer. If done correctly later adding multiplayer capabilities to our 3D apple chase game (or any game) will be much easier. So lets get started.

A better network library


Our first step is to replace MINA version 1.7 with the improved MINA version 2 that is now ready to use. Our friends at Apache have created a link with information of what changed between the new and the old version ( http://mina.apache.org/changes-between-2x-and-1x.html ), but for our own purposes the key difference is: the new version has better performance. We will also enhance our network layer design so it is more reusable in any game you want, not just the games of this document. We will call this layer the ummi layer (just to give it a name) and here is the new design:

Your game UDP messages TCP messages

ummi network library MINA

Network
Your game can use the ummi library ( which in turns uses MINA ) to send/receive TCP/UDP messages to the network.

The key point here is: Using MINA is great, but we need a layer that hides/encapsulates MINAs own complexities in a way that we can easily add multiplayer capabilities to any game. So the ummi library is born.

The MINA library is very powerful, be sure to check its website ( http://mina.apache.org ) to read about real uses of it to get an idea of what it can do. Just to add more good examples of MINA in real life: there are some commercial gaming network libraries ( like ElectroServer ) that use MINA internally.

Lucu guide for creating videogames page 53

Why UDP?
We will change two things to our puzzle game, the fist one is do an upgrade to MINA v2 (with the help of the ummi API) and the other one is add the ability to send UDP network messages. As you may recall from a previous chapter, UDP messages are fast but not guaranteed to arrive at the destination, this type of message suits perfect in our puzzle game to add one extra game feature: make the pieces move in real time on the players screen at the same time another players are moving that piece on their own computers. The current version of the puzzle just puts the piece at whatever place the other players dropped it. Adding this movement of the piece will add an extra human touch to the game, to make it more realistic and a little more fun to play. UDP messages are used for scenarios like these because: 1. Moving a piece (or a player) around the game generates a lot of info (many coordinates changing frequently as the piece or the player moves) during a lot of time ( players move constantly ). This means we need to send a lot of data (and fast!) across the network to update other players of the changes the others players are doing. 2. It is not critical if one movement gets lost in network traffic because the player (or piece) keeps moving and will send a new updated coordinate again, so new data is always coming to update the old one, or replace the missing one. This is of course not the only case, it is up to you to decide when you need to use TCP or UDP while designing your game, so it is good to have them both available as options.

Just to make the learning process easier in this guide, we will use simple text messages with UDP, but to increase performance you may want to try binary (or any smaller type) messages with UDP. Check MINAs documentation on how to do this.

Adding the ummi network library to the puzzle game


Inside the source code you will notice the java project ummi_network. It provides a set of classes that will allow us to send/receive network messages (TCP or UDP). From your game client code you use the class ClientConnection.java for this. And from your game server code you use the class GameServer.java. We will show how to use them by adding them into our puzzle game. The game server side Look at the source code of the project puzzle_multi_v2_server Notice the file server.properties, it has properties where you can enable/disable TCP or UDP communications and what port you want to use for them. Now look at the file Server.java, it is used just to start the game server (provided by the ummi library) in three simple steps: create a new instance of the game server, start the TCP listener, and start the UDP listener:
GameServer gs = new GameServer(); gs.startTCPServer();

Lucu guide for creating videogames page 54

gs.startUDPServer(); If you run the server you will this output showing your game server is ready:
2010-11-03 12:10:08,343 INFO [main] org.ummi.network.server.GameServer_startTCPServer: starting TCP server 2010-11-03 12:10:08,484 INFO [main] org.ummi.network.server.GameServer_startTCPServer: TCP server Listening on port 5555 2010-11-03 12:10:08,484 INFO [main] org.ummi.network.server.GameServer_startUDPServer: starting UDP server 2010-11-03 12:10:08,500 INFO [main] org.ummi.network.server.GameServer_startUDPServer: UDP server Listening on port 8888

The game client side Now look at the source code of the project puzzle_multi_v2_client This is the new version of the game, now with UDP and the ummi library. Notice the ummi_network_client.jar added to the classpath of the project. Now lets study the PuzzleGame.java class to understand the necessary changes. First, notice how the class now implements two interfaces, these is needed so that the game can listen for incoming TCP or UDP messages: public class PuzzleGame extends Game implements MouseListener, MouseMotionListener, TCPConnector, UDPConnector Also notice that we added the MouseMotionListener interface, this is needed so that the game can detect when the mouse is moving. We then need to register the game as a listener for mouse moving events: // do this to listen for mouse events ((AWTInput) bsInput).getComponent().addMouseListener(this); ((AWTInput) bsInput).getComponent().addMouseMotionListener(this); Now the connection to the game server is established by calling two methods (one for TCP, another for UDP):
public void initResources() { ... // try to connect to the TCP network connectedToNetwork = networkClient.connectTCP(PuzzleGame.this, localhost:5555, userName); ... // try to connect to the UDP network connectedToNetworkUDP = networkClient.connectUDP(PuzzleGame.this, localhost:8888, userName);

You must, of course, use the same ports where the game server is listening to incoming connections. Ports 5555 for TCP and 8888 for UDP in our example. Now we will add the game logic, in the mouseMoved() method, to send our mouse pointer coordinates to the other players, as we move around a puzzle piece over the screen:
Lucu guide for creating videogames page 55

public void mouseMoved(MouseEvent e) { if (selectedPiece >= 0) { if (connectedToNetworkUDP) { // also, notify any other players (in the network) that we // are moving a piece StringBuffer sb = new StringBuffer(); sb.append(moved_a_piece).append(,).append(selectedPiece).append(,); sb.append(to x).append(,).append(getMouseX()).append(,); sb.append(to y).append(,).append(getMouseY()); networkClient.broadcastUDP(sb.toString()); } } } One more piece of coding is needed, the one that receives incoming UDP messages from other players and updates the position of the pieces in the screen: public void messageReceivedUDP(String message) { // in this game, when we receive a message it could be that another user // is playing and we receive the information of the // piece he/she moved // verify if it is a piece movement if (message.indexOf(moved_a_piece) >= 0) { // another user moved a piece, lets move that piece in our own grid // also String[] data = convertLineIntoArray(message, ,); puzzlePieces[Integer.parseInt(data[1])].setX(Integer.parseInt(data[3])); puzzlePieces[Integer.parseInt(data[1])].setY(Integer.parseInt(data[5])); } }
Lucu guide for creating videogames page 56

And thats it! you can run the example and you will notice that when another player moves a piece you will get an update in real time as he moves the piece around. Now you can reuse this technology (even better: improve it!) to add multiplayer features to your own games. The flexibility of MINA There is one more thing you need to notice: the ummi library provides you two interfaces (TCPConnector.java and UDPConnector.java) for you to use depending on your gaming needs, if you are curious enough (and you should) to look at their source codes, you will notice that they are almost identical, in fact, if you review the TCP and UDP handler programs also (TCPCommunicationsHandlerAdapter.java and UDPCommunicationsHandlerAdapter.java) they will also look nearly identical. So what is the difference? Well, thanks to MINA it is easy to use one or the other, just by changing the type of network connection we use, and you can see in this next section of code in ClientConnection.java: public class ClientConnection implements CommunicationConstants { ... // TCP communications private NioSocketConnector connectorTCP = null; ... // UDP communications private NioDatagramConnector connectorUDP = null; ... public boolean connectUDP(UDPConnector udpConnector, String host, String userName) { connectorUDP = new NioDatagramConnector(); ... public boolean connectTCP(TCPConnector tcpConnector, String host, String userName) { connectorTCP = new NioSocketConnector();

Once again, this document is showing you just a little example of what MINA can do, be sure to study more about MINA, and if you use more of its functionality try to encapsulate it inside a layer (like the ummi layer) so that you can reuse and reuse all those features in many games easily.

With this section complete, now lets add multiplayer abilities to our 3D game (apple chase) in the next chapter.

Lucu guide for creating videogames page 57

Chapter 8: Making a 3D multiplayer game


Apple Chase - multiplayer design
Since we already covered topic like network, TCP, UDP, MINA in previous chapters, we can concentrate our attention in more details of our game. We will propose new design considerations for the game apple chase multiplayer edition: The game is competitive. Players must find apples to survive. Only one apple is available at a given time, the player who catches it first gets its energy refilled. To reduce network bandwidth, all files and maps will be already installed on the player computers. To reduce network bandwidth, the game server will only send the apple initial position and projected travel path to the game clients, which in turn will render and display the apples with local computations. No need to constantly send the apple coordinates to all players. The position of the players changes constantly and will be sent using UDP to all game clients so they can update locally the display. This is the only communication that will use UDP, all other game information will travel using TCP. Players can enter/exit the game at any time. The score is based on the number of apples a player can catch, the higher the better. The score will be displayed for all players to watch.

Making some improvements to our 3D game


First, we will remove the PickScheduler object and instead use PickingLibrary. When we are validating the picking we are already inside the Xith3D rendering thread so it makes more sense to use the PickingLibrary for a direct test instead of scheduling a test. The change is applied in this section:
public void onMouseButtonPressed(MouseButtonPressedEvent e, MouseButton button) { ..... PickingLibrary.pickNearest(appleT, canvas, e.getButton(), canvas.getWidth() / 2, canvas.getHeight() / 2, this);

Second, we will separate the input logic in another package (org.applechase.input) to organize better our game code. As your game grows bigger it is best to separate its logic into different classes/packages. If you look at that new package ( org.applechase.input ) you will notice we added two classes there to manage keyboard and mouse input. The logic inside those classes is the same that previously was inside the main AppleChase.java class. Next we need to change the class we extend from. You may remember that in the first version of the apple chase game we extended our main class from InputAdapterRenderLoop, but extending from that class is recommended only for testings/demos. Now we are going to extend from RenderLoop: public class AppleChase extends RenderLoop ...

Lucu guide for creating videogames page 58

Then we need to register the new input managers inside AppleChase.java: //register our keyboard input manager ListenKeyboard lk = new ListenKeyboard(this); InputSystem.getInstance().getKeyboard().addKeyboardListener( lk ); //register our mouse input manager ListenMouse lm = new ListenMouse(canvas, appleT, this); InputSystem.getInstance().getMouse().addMouseListener(lm); As your game grows consider delegating functions (input, rendering, picking, etc) in different classes so it becomes easier to maintain.

Adding server-side game logic


For out little puzzle game, our server-side game logic was basically just managing logins, logouts and broadcast messages, which are functions that are handled by the default implementation called DefaultProtocalHandler.java. But for our apple chase game we need to add some logic to the game server: Set the initial coordinates of the apple, and then broadcast to all players. Keep and broadcast all players score in a central place.

To do this, we create GameProtocolHandler, which extendes the basic game server functionality, but adds custom game logic: public class GameProtocolHandler extends DefaultProtocolHandler { .......... @Override public void customGameLogic(String user, String message) { .... The game logic we put in the server is very simple: now the server calculates the new apple position and sends it to the players. You may remember that in the single version of the game this was calculated in the game client: private synchronized void issueNewApple() { int randomX = FastMath.randomInt(20); int randomZ = FastMath.randomInt(20); StringBuffer sb = new StringBuffer();
Lucu guide for creating videogames page 59

sb.append(newApple); sb.append(,); sb.append(randomX); sb.append(,); sb.append(randomZ); broadcast(sb.toString()); }

Updating the game client


First, we added a GUI frame so we can ask the player to enter his name. This is managed by the InputFrame.java class. The game will first show that frame, ask the information, and when pressed the continue button the game will start:

Frame for asking the name of the player

Notice this code that will be executed when you press the button: public class InputFrame extends Frame implements ButtonListener { ... public void onButtonClicked(AbstractButton arg0, Object arg1) { try { ... game.startGame(); Next, on the AppleChase.java game we add the ummi client components needed to connect to the game server: public class AppleChase extends RenderLoop implements PickListener, IntervalListener,
Lucu guide for creating videogames page 60

TCPConnector, UDPConnector { ..... private ClientConnection networkClient = null; Using TCP messages, the server will notify the clients a new apple position, here is the code that takes care of that: public void messageReceivedTCP(String arg0) { if (arg0.startsWith(newApple)) { // lets change the position of the apple according to what the game // server decided String[] message = convertLineIntoArray(arg0, ,); // notice how the following logic is very similar to the method // setApplePath() //these values came from the game server: randomX = Integer.parseInt(message[1]); randomZ = Integer.parseInt(message[2]); ... The next change is: inside the prepareNext method we capture our avatar coordinates in the game, and use UDP to notify the game server, we do this so that our own avatar is displayed in the other game clients: protected void prepareNextFrame(long gameTime, long frameTime, TimingMode timingMode) { .... // capture the players coordinates (x,y,z) sb.append(firstPersonHandler.getView().getPosition().getX()); sb.append(,); sb.append(firstPersonHandler.getView().getPosition().getY()); sb.append(,); sb.append(firstPersonHandler.getView().getPosition().getZ()); // capture the players facing direction float xx = firstPersonHandler.getView().getFacingDirection().getX(); float yy = firstPersonHandler.getView().getFacingDirection().getZ();

Lucu guide for creating videogames page 61

double angle = Math.atan(yy / xx); sb.append(,).append(angle); networkClient.broadcastUDP(sb.toString()); The angle value is calculated using a little trigonometry function. As you play the game you will notice it is not perfect, but for our little game demo here it will be enough. The goal here is: your current position and facing direction are broadcasted to other players so they can know where you are. This information will be constantly sent to the game server so it can be broadcasted to the other players. Since we are using UDP it will travel fast enough to give the illusion that all our movements are reflected in real time in the other game clients. Next, we add code in our game client to update the position of a 3D model in the screen (that represents another player) every time we get a new position by UDP: public void messageReceivedUDP(String arg0) { .... //parse coordinates float x = Float.parseFloat(message[2]); float y = Float.parseFloat(message[3]); float z = Float.parseFloat(message[4]); //parse rotation angle (facing direction) float angle = Float.parseFloat(message[5]); ... // update the position of the other player on the screen avatarTG.setRotationY(angle); avatarTG.setPosition(x, y, z); avatarTG.updateTransform(); } The game client will show many 3D models (using the model tris.md2 that comes with Xith3D) to display on the screen the position of other player(s). The result when multiple players are playing is like this:

Lucu guide for creating videogames page 62

Apple chase multiplayer edition.

There are some details worth mentioning about the the 3d model. It is loaded and then stored inside a Transform object so that it can easily be moved and rotated around the 3d world. Also, we attached the name of the player (notice the blue text floating over each character) so that you can identify what other players are playing with you. The following piece of code shows these topics: Transform avatarTG = (Transform) players.get(otherPlayerName); ... // load a model and associate it with this player URL modelResource = resLoc.getResource(tris.md2); String skin = marvin.pcx; Model model = ModelLoader.getInstance().loadModel(modelResource, skin, 0.08f); avatarTG = new Transform(); avatarTG.addChild(model); avatarTG.addChild(new AmbientLight(Colorf.GRAY10)); // put the other players name in a label next to the model Rectangle textRect; textRect = TextBillboard.createFixedWidth(1.0f, otherPlayerName, new Colorf(0f, 1.0f, 0.8f), new Font(Arial, Font.BOLD, 18), TextRectangle.TEXT_ALIGNMENT_HORIZONTAL_CENTER);
Lucu guide for creating videogames page 63

//the following transformation is to put the text over the head of the 3D character Transform tt = new Transform(textRect).setTranslation(0.1f, 2f, 0.1f).addScale(0.8f); avatarTG.addChild(tt); model.setCurrentAnimation(run);

scene.addChild(avatarTG); And there you have it, the Apple Chase game, multiplayer edition. Be sure to run the server and the game clients in a network and have fun with your friends. Try to find ways to improve the game and experiment with the code to learn more. I hope you enjoyed this guide and wish you luck in creating your own games.

Lucu guide for creating videogames page 64

What's next?
Now that you have the basic foundation, go make videogames! Try to make little demos and games with different engines and programming languages to explore your options and see which one fits your needs. Here are a few cool topics to also watch for: jMonkeyEngine version 3 Currently alpha. To be released in 2011 with new features like support for Android WildPockets Currently beta. Is a web-based 3D game programming platform iOS and Android games They are getting better with each new release of their platform

Lucu guide for creating videogames page 65

Appendix A: Extra Resources


Library
Creating a video game requires a combination of different skills: programming, graphics design, story telling, music composing, etc. So it usually requires a team of people to complete. Here is a list of useful books to read (At least check their table of contents!) so you can better understand the whole process: Books about game design: Book Tittle: Game design workshop Author: Tracy Fullerton Notes: game design, prototyping, game industry, quality testing... Book cover (if available)

Tittle: Game Architecture and Design: A New Edition (New Riders Publishing) Authors: Andrew Rollings, Dave Morris Notes: game design, development, gaming concepts... Tittle: Game DesignTheory & Practice Author: Richard Rouse III Notes: game design, game categories, level designs, story telling for video games, interviews with renowned game developers...

Lucu guide for creating videogames page 66

Tittle: software engineering for game developers Author: John P. Flynt Notes: AI, video game development planning, quality control, patterns...

Tittle: Character.Development. and Storytelling.for.Games Author: Lee Sheldon Notes: designing characters for games, creating stories and fantasies, arguments...

Tittle: A theory of fun for game design Author: Raph Koster Notes: A must-read book to understand the theory of fun applied to games.

Lucu guide for creating videogames page 67

Books about video game programming: Book Tittle: Beginning Game Programming Author: Jonathan Harbour Notes: DirectX, 3d programming, sprites... Book cover (if available)

Tittle: Killer Game Programming in Java Author: Andrew Davison Tittle: Pro java 6 3d Game Development Author: Andrew Davison

Tittle: Physics for Game Programmers Author: Grant Palmer Notes: The cover says: A one-stop resource for building physics-based realism into your games. This book is great, it explain how you can add physic laws in your game programming, but I must add that it is also important to note there are some physics libraries that you can also use in your games, like: bullet and ODE.

Lucu guide for creating videogames page 68

Books about graphic design: Book Tittle: Game character development Author: Antony Ward Book cover (if available)

Tittle: Game character modeling and animation with 3ds max Author: Yancey Clinton

Resources
Interesting places to get information/files/tutorials/graphics/sounds/etc about video games: Site Devmaster http://www.devmaster.net/engines/ Notes Game engines and review about them. Information about the gaming industry.

Gamedev http://www.gamedev.net/reference/

Gaming info. I strongly recommend you read the coverage they do about gaming conferences here:
http://www.gamedev.net/reference/list.asp?categoryid=335

Lucu guide for creating videogames page 69

You will find real-life histories and cases from game developers around the world. (better yet: try to go to one of those conferences!) http://www.freeprogrammingresources.com/gamelib More game engines. .html http://www.cokeandcode.com/ http://www.pygame.org/wiki/resources Game Deverloper Magazine http://www.gdmag.com/homepage.htm
http://freegamedev.net/wiki/index.php/Free,_cross-platform_game_engines http://freegamedev.net/wiki/index.php/Free_game_libraries http://www.twilightsembrace.com/personal/gamelibs.php http://www.yoyogames.com/make/resources http://www.pygame.org/wiki/resources http://www.ebonyfortress.com/blog/free-game-development-libraries/ http://freegamedev.net/wiki/index.php/Free_3D_and_2D_art_and_audio_resour ces http://www.ambrosine.com/resource.php http://www.costik.com/articles.html http://www.ruthless.zathras.de/facts/apps/polygonesia/game_design.php http://www.scottkim.com/thinkinggames/index.html http://www.stratos-ad.com/ http://www.noshysoft.com.ar

Gaming, games, resources... Tutorials, fonts, clipart, music, sounds library... Subscribe when you can to know more about games and the video game industry.

Resources (music, sound effects, images, fonts, sprites, libraries, tutorials....)

Lucu guide for creating videogames page 70

Appendix B: How to setup Slick framework with Eclipse


Install java 1.6 or greater. For this guide I will install it in c:\jdk16 Install Eclipse IDE 3.2 or greater. For this guide I will use Eclipse 3.2 in d:\eclipse. Start Eclipse and make sure you are using that java 1.6 jdk you just installed. Now download the latest version of slick from http://slick.cokeandcode.com, be sure to the full distribution, the complete link is: http://slick.cokeandcode.com/downloads/slick.zip. Next, unzip the file in a temporary folder. We will be taking some files from it, from the folders src and lib so take a quick look at them, we will use them later. Notice that slick depends on a library called lwjgl (http://lwjgl.org/download.php ) . It is recommended that you also download the latest version of that library. For this guide I downloaded LWJGL 2.3 In Eclipse, create a java project, lets call it slick. Inside it create three folders: src_prod, src_test and lib. Make src_prod and src_test java source folders. Inside lib we will put the necessary jar files. So far you should have something similar to this:

Now, put the slick source code (with the exception of the tests package) in the src_prod folder. And put only the tests package in the src_test folder. The reason to separate this is just a good practice for java programs: always have your test and real-life-production source codes separate, for practical reasons this also means that when you deploy or deliver your final game to the users, you can easily filter out anything inside the src_test folder, and it also means that when you create a game it will be in its own src_game1 folder. You will understand this better as we code games later on. Now we will put the slick jar files in the lib folder. But we are not going to put all jars that come with slick, not because we do not need them, because we will put them as we need them. This way is better because you will learn what jars you will need when you do certain things with the framework, and also we will let us start with the basics first. The first jars we will put are: ibxm.jar jinput.jar jnlp.jar
Lucu guide for creating videogames page 71

jogg-0.0.7.jar jorbis-0.0.15.jar lwjgl-debug.jar ( you can find this jar inside the lwjgl distribution you downloaded )

Slick distribution comes with lwjgl.jar, but I recommend you use lwjgl-debug.jar instead while developing your games to get more information while you test your games. You can later deploy your game with lwjgl.jar

So copy those jars to the lib folder and then change the project settings in Eclipse so that they are included in the build path. Do a refresh in Eclipse to make sure everything is in order and nothing is missing. If you did everything so far, now you have the source code of slick installed in Eclipse and without any compilation errors (do not worry about the warning messages now). You should have now something like this picture:

Lucu guide for creating videogames page 72

Now, we need to add the native libraries in our environment. These are the needed DLLs ( in MS Windows environment ) or .SO (for linux). They are inside the jars that come with slick and are called: natives-linux.jar, natives-mac.jar, and natives-win32.jar. Since this guide is made for a MS Windows box, we will unzip the file natives-win32.jar in a folder we will call d:\dev\xian\natives, like this:

Lucu guide for creating videogames page 73

The easy way to use DLLs files in a windows box is just to put them in WINDOWS_FOLDER\System32 or any other place where the path or the general classpath can find them. But, I dont recommend you to do that for two reasons: 1.- It is better to assume the DLLs are NOT in the computer your game will run or to assum that you can easily put them in the destination PC just anywhere you want. 2.- It is better to put these files in a folder where they can be easily found/replaced later.

Note: If you will use lwjgl.jar that came with your slick distribution, then the previous step is just fine, but if you are going to use lwjgl.jar or lwjgl-debug.jar from the lwjgl distribution then you need to get these native libraries from LWJGL, since I will be using lwjgl-debug.jar then I will get these files from the lwjgl-2.3.zip file here:

Now lets do a little hello world basic program to test our slick installation. Create HelloWorld.java in the tests folder and make it like this:

package org.newdawn.slick.tests;

Lucu guide for creating videogames page 74

import org.newdawn.slick.BasicGame; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.AppGameContainer;

public class HelloWorld extends BasicGame {

public HelloWorld() { super(HelloWorld); }

@Override public void init(GameContainer container) throws SlickException {}

@Override public void update(GameContainer container, int delta) throws SlickException {}

@Override public void render(GameContainer container, Graphics g) throws SlickException { g.drawString(Hello world from slick, 0, 100); }

public static void main(String[] args) { try { AppGameContainer app = new AppGameContainer(new HelloWorld()); app.start(); } catch (SlickException e) { e.printStackTrace(); } }

} To run this program you do need to tell java where to find the native libraries, if you dont it will show an error like this:

Exception in thread main java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path

Lucu guide for creating videogames page 75

at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1709) at java.lang.Runtime.loadLibrary0(Runtime.java:823) at java.lang.System.loadLibrary(System.java:1030) at org.lwjgl.Sys$1.run(Sys.java:72) at java.security.AccessController.doPrivileged(Native Method) at org.lwjgl.Sys.doLoadLibrary(Sys.java:65) at org.lwjgl.Sys.loadLibrary(Sys.java:81) at org.lwjgl.Sys.<clinit>(Sys.java:98) at org.lwjgl.opengl.Display.<clinit>(Display.java:132) at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39) at java.security.AccessController.doPrivileged(Native Method) at org.newdawn.slick.AppGameContainer.<clinit>(AppGameContainer.java:36)

at org.newdawn.slick.tests.HelloWorld.main(HelloWorld.java:30) So, go to the run options of Eclipse and open the run dialog window:

Inside that dialog create a new Java Application configuration:

Lucu guide for creating videogames page 76

Select out test class as the Main class:

Now in the tab Arguments you need to tell java where you placed the native libraries, with the parameter -Djava.library.path=d:\dev\xian\natives like this:

Now you can run this Run configuration from the Run menu of Eclipse. If you get an error that says something like jar and library are from different version is probably
Lucu guide for creating videogames page 77

because you are not using the correct version of the native DLLs (slick or lwjgl versions) If everything went OK, you can now run this simple example and see something like this:

A nice game window generated by slick framework, with the message you put in the java code. As a bonus you get the actual frames per second (fps) in the upper left corner.

Lucu guide for creating videogames page 78

Appendix C: How to setup GTGE inside Eclipse IDE


Just one note before starting: you can of course use another java IDE (like Netbeans, Jcreator, etc) instead of Eclipse. Im using it here just because I prefer Eclipse but if you know java you can easily use these same steps to setup GTGE in another java IDE. Install java 1.4.2 or greater. For this guide I will install it in c:\jdk142 Download Eclipse IDE from http://www.eclipse.org/downloads/

The version you need is just the simple Eclipse IDE for Java Developers. You can of course download the Enterprise EE version if you want. I will use my good old Eclipse 3.2 version that only needs java 1.4.2 to run and is the same java requirement as GTGE. You can try a newer Eclipse version but will probably require a newer java version to run. Make your choice. For this guide I will install Eclipse IDE 3.2 (enough for me) in d:\eclipse. Now start Eclipse (which ever version you downloaded) and make sure you have java 1.4.2 as the default runtime option (this is the same jdk you installed in a previous step):

Lucu guide for creating videogames page 79

Now create a java project, I will call it gtge. Optional but highly recommended step: create a source folder called prod inside the gtge project, this will help to separate your code from the engine code, create another source folder called test to put some examples or little testing programs, then create one source folder for each of the games you plan to develop. If you do this your java programs will live in separate folders and will be easier to manage. Please create a separate source folder called puzzle for the game we will create. This also helps when you finished your game and want to create separate deployers/installers for each game. This is how my environment looks so far:

Download GTGE engine from http://goldenstudios.or.id/products/GTGE/ I will be using this version: GTGE_0_2_3_complete.zip Unzip the download file and look for the source code inside, put that java code in the prod folder or the gtge project.
Lucu guide for creating videogames page 80

Now run the tutorial that comes with GTGE, there you will learn the basics of the framework. Dont forget that game resources (images, sound, .etc) go INSIDE the source folder of the game, like this:

I recommend you to try to run the robotic war game (available from the same GTGE site) or any of the other games available there. They are all fun! This will give you and overall view and usability of the framework.

When you copy, erase, delete, or rename files inside your project sometimes Eclipse does not automatically recognize that... and you may get strange File No tFound errors... in those case use the refresh and clean (in that order) options of Eclipse to force Eclipse to re-read the folders/files and to clean any temporal data

Lucu guide for creating videogames page 81

Appendix D: How to setup Xith3D inside Eclipse IDE


If you dont have your Eclipse IDE installed yet, please make sure you read the previous sections of this document to learn how to do it. For the rest of this section I will assume you already have your Eclipse IDE with JDK 1.6 (or greater) up and running already. First, go to Xith3Ds site ( http://Xith3D.org ) and download the latest version. When I did this guide the latest version was 0.9.7-dev-B1831 cooker release of 2010-09-06.

Dont forget to visit Xith3Ds forum to meet the community and people supporting it. You can get advice and learn about XITH3D. Forum: http://Xith3D.org/forum/index.php

Unzip the file you downloaded and inside you will find a document called xin-3rd-edition.pdf. Make sure you read it to learn Xith3Ds basics. Inside that zip you will also find the Xith3D libraries, third-party libraries, native libraries, source, examples and resources. We will put them inside Eclipse to create a development environment.

Installing the support libraries


Inside Eclipse create a java project called Xith3D, associate it with jdk16 and add the following basic libraries to the classpath:

Looking at these libraries is a good moment to remember the importance of using an engine to build your game. As you can see Xith3D already provides you a lot of functionality that otherwise you should have to work on adding yourself. Lets do a quick overview of what these libraries provide (and that you can use in your game):
Lucu guide for creating videogames page 82

jagatoo: input (keyboard, mouse) management jogl: 3D graphics joode: physics (gravity, collisions, etc) lwjgl: 3D graphics joal: sound vorbis: sound/music

Notice that swt.jar (that came with Xith3D distribution) has not been added. You can add it if you plan to use SWT to create Eclipse plugins. Note: I have been given this tip on the Xith3D forum: On the Mac platform just having the jar in the classpath causes some problems.

Dont forget to always refresh the workspace in Eclipse to make sure all files you just copied are available to use inside the Eclipse IDE.

Adding Xith3Ds own files


To add Xith3D itself to your project, you have two options, choose the one you like best. Option 2 requires less files/space is more organized and is probably the fastest and more command option. Option 1 usually is used only if you want to constantly look inside Xith3D source code and even change it to experiment a little. (I am very curious so I use option 1). Option 1 (put Xith3D as source files in Eclipse): Inside the java project create three source folders called prod, test and test-resources. We will put the engines files in the prod folder, our tests, games in the test folder and game resources (graphics, textures, sound, etc) will be placed in the test-resources one. Also add a folder called lib to hold the engines library jar files. Locate the file Xith3D-source.jar from the downloaded XITH3D distribution and extract the source code from inside and put it in the prod folder of our project. Locate the file Xith3D-test-source.jar from the downloaded XITH3D distribution and extract the source code from inside and put it in the test folder of our project. Locate the file Xith3D-testres.jar from the downloaded XITH3D distribution and extract the source code from inside and put it in the test-resources folder of our project. If you followed this option you should now see something like this:

The error (red x) is because we didnt add the swt.jar. Just erase the file CanvasPeerImplSWT to clean the compilation error.
Lucu guide for creating videogames page 83

Option 2 (put Xith3D as a jar in Eclipse): Add xith3d.jar to the classpath. Go to the propertied of xith3d.jar and add xith3d-source.jar as source attachment to it. Add xith-test.jar to the classpath. Add xith-testres.jar to the classpath.

Adding the native libraries


The next step is the setup of the native libraries. These are special files (DLLs for Windows platform, SO for linux... depending on your platform...) that are used by some of the jar libraries to access the operating systems resources. They are located inside folders called natives in the third party libraries of Xith3D. There are three options to link them to your Xith3D java project. Option 1 is the classic option and works with any IDE. I dont think anybody uses this option anymore for development, but it is good to know because very likely you will use this option to create installers for your games on the client machine. Option 2 is the quick and dirty option if you dont want to think too much and just want to make games and play them. Option 3 is the recommended option because it is more clean and organized.

Choose the option that you like better. Here is the description of each option: Option 1: Copy the native libraries to any folder and add the -D parameter (referencing that folder) in java every time to call Xith3D. This is the standard/best option and is recommended always. Check javas documentation on how to do this. Here is a small example:
java -cp .;jar\Xith3D.jar;jar\mygame.jar -Djava.library.path=native\windows package.super.MyGame

Option 2: This is the quick and dirty option and the one I will use in this guide is to just copy those native libraries to an existing system path where java can always find them. In Windows XP that folder is WINDOWS\SYSTEM32, so in my development environment I just copied these files there:

Option 2 is liked because during testing/development one usually does/runs a lot of programs and adding the -D parameter every time you run something just makes development slower. Option 3 (recommended option): I just learned this one and will use it. What you have to do is just copy the native libraries somewhere. I put them where the normal jar files are, but they can be in another folder also:
Lucu guide for creating videogames page 84

Then go to each jar that needs to reference them and add it as a native library option so that it can be located during runtime. Here is screenshot of how its done:

You need to do that operation for the following jars: lwjgl.jar


Lucu guide for creating videogames page 85

gluegen-rt.jar joal.jar jogl.jar swt.jar (if included)

Making sure Xith3D is installed correctly


Assuming you did everything correctly you can now run Xith3Ds own examples. Be sure to do that because you can learn a lot from watching them and inspecting their java code. To run the examples execute this program: org.Xith3D3d.test.Xith3D3DTestLauncher. Xith3D has plenty of examples, but the ones I recommend you first concentrate on are: BSPLoaderTest: it loads a Quake MAP level and allows you to move inside it, very useful to learn about maps. MD2LoaderTest: loads a game character from a MD2 file. FirstPersonInputHandlerTest: loads a game character and lets you control it in from a third person perspective.

They will give you a nice overview of the engines capabilities.

Lucu guide for creating videogames page 86

Appendix E: Xith3D scenegraph


Taken from the Xith3D documentation:

Lucu guide for creating videogames page 87

Вам также может понравиться