title: Creating an abstract Animation class

text:
# Question
Title: Creating an abstract Animation class
I'm creating a simple 2d game with c++ and SFML, and I've got a simple framework going for animating a sprite using a "SpriteSheet" image (an big image containing all the "frames" of an animation)

I've got it working fairly well, I've attempted to copy the concept from another engine i'm familar with (Starling for Flash).. in which they use a "Juggler" which updates a sprite's properties based on a timeline, independant of the sprite...

I've got the animation working for swapping frames using a class i created called Tween... it calls a function update(float gameTime); which updates the sprites subRect to the correct frame...

I'd like to make this a more rebust solition, allowing the Tween class to do more than just frame animations.. I've been trying to use polymorphism to create Children to Tween such as "Anim", "Move", "Rotate", and "Scale" which all have a update() function which updates the sprite accordingly... The idea being a list of a number of these classes (for instance, a Scale and Rotate) can be added to a vector list and then each can call their update function, each updating their specific functions.. the problem seems to be that if i create a list of Tweens, then call update, it uses Tweens implementation of Tween.update() and not it's inherited children, I don't know how/if it's possible to allow this...

# Answer
> 4 votes
> The problem seems to be that if i create a list of Tweens, then call update, it uses Tweens implementation of Tween.update() and not it's inherited children, I don't know how/if it's possible to allow this...

Of course it's possible, that's the whole idea of polymorphism. You just need to ensure two things:

1) Mark the `Update` method as **virtual** in your `Tween` base class:

```
class Tween
{
public:
    virtual void Update(float elapsed) {}
    virtual ~Tween() {}
}

```

> Note #1: It's really important that you make your destructor virtual too whenever you intend to use polymorphism. This is needed so that you can *delete* the objects correctly through a pointer to the base class.

2) Make sure that you create your list so that it holds **pointers** to `Tween` instead of `Tween` objects directly:

```
std::vector<Tween*> tweens;

```

Afterwards all you have to do is the fill the list with objects of any type that inherits from `Tween` and when calling `Update` on them the program will **automatically** choose the right version for each object. No extra code needed:

```
tweens.push_back(new Anim(parameters));
tweens.push_back(new Move(parameters));
tweens.push_back(new Rotate(parameters));

for(int i=0; i!=tweens.size(); ++i)
{
    // Will call the correct version of Update for each object in the list
    // Because Update is marked as virtual and tweens[i] is a pointer
    tweens[i]->Update();
}

```

> Note #2: And since it doesn't make sense to create a `Tween` object directly, you should also make the class abstract to prevent this behavior explicitally. In C++ this is done by adding one or more pure virtual methods to the class. When all methods are pure virtual and there are no member variables in the class, it's also known as an interface. The above example would become:

```
class Tween
{
public:
    virtual void Update(float elapsed) = 0;
    virtual ~Tween() {}
}

```

---
Tags: c++, sfml, polymorphism, tweening
---


title: Scaling bodies in box2d and libgdx

text:
# Question
Title: Scaling bodies in box2d and libgdx
Is there a way to scale the bodies made from vertexes (like a guitar), i was trying to multiply each vertex point by the scale value but c++ mark an assertion failed, is there a mehtod to do this?

I have done it, but i want to make a mirror body, but i cant do it :/ just multplying it by -1 or 1 it doesnt run :/

# Answer
Section 4.4 of Box2D manual says:

> You must create polygons with a counter clockwise winding (CCW). We must be careful because the notion of CCW is with respect to a right-handed coordinate system with the z-axis pointing out of the plane. This might turn out to be clockwise on your screen, depending on your coordinate system conventions.

If you are taking a shape and mirroring the coordinates you are probably changing the winding and that is the reason it fails. But as you didn't provide an error log (the box2d c/c++ assertion) I can't be sure.

I believe you can perform the mirroring you want if you invert the array of vertices too, before creating the box2d shape. What I mean is, if you have \[v1, v2, v3\] then by inverting the array you will have \[v3, v2, v1\].

Hope it helps.
> 4 votes

---
Tags: box2d, libgdx
---


# Question
Title: How to fake flipping a skeleton in Box2D?
Imagine I have a skeleton — that is a set of bodies held together through various constraints and joints — and I want to flip it. Bodies cannot be flipped in Box2D, so how can I fake that?

Here's an example: I have a humanoid skeleton, made out of different Box2D bodies: the head, torso, upper arm, lower leg, etc. These Box2D bodies are held together by joints. Some of the joints have angle constraints, like the ones between the upper and lower arm, which do not allow the 'elbow' to twist unnaturally.

When I turn my character the other way around, I should flip the skeleton and its joints should be flipped as well. How can I achieve that in Box2D?

# Answer
> 1 votes
At the risk of being a hypocrite, because I hate it when people start an answer to a question with: "I don't know/use/(etc.) (insert object of question) but I think..."

I don't know Box2D (but I'm learning!), but couldn't you just create two skeletons that are mirror images and switch between them when needed?

---
Tags: c++, box2d
---


# Question
Title: Java game engine for android and desktop
I want implement 2d game as desktop application. And after development move it to android platform.

Engine should be have input and network managers.

Help me choose.

# Answer
I would recommend going with libGDX. It is great, I am currently using it a lot. You can build your game in 2D or 3D. It allows you to easily test your game on the desktop and if you want to move it to your Android device then all you have to add is about 5 lines of code.
> 1 votes

# Answer
Try Unity3D, it currently gives Android and iOS basic versions for free until April 8th.
> 0 votes

---
Tags: java, 2d, android
---


# Question
Title: How to use the actions of the actors in libgdx?
I'd like to know if someone has already used Actions in the actors, and how to use them. I don't know how. I want to rotate an Actor.

# Answer
> 2 votes
The API is Actor.action(Action action), that will add an action to the Actor and it will be updated when Actor.act(delta) is called.

Here is an example code to rotate 90 degrees in 5 seconds a window:

```
Window window = new Window(...);
window.action(RotateTo.$(90, 5f));

```

This will automatically works if you have the widget on the Stage and you are calling stage.act(delta) correctly. Otherwise you will have to call Actor.act(delta) by yourself.

Hope it helps.

---
Tags: android, libgdx
---


title: Keyboard shortcuts in RTS game

text:
# Question
Title: Keyboard shortcuts in RTS game
Imagine you have a multiplayer RTS game (e.g. Dune, Age of Empires, Settlers, Warcraft). There are certain commands available from keyboard to command the troops (Stop, Attack, Move) and some more general commands like Pause or Exit. The game is localized into many languages (18+).

I can see two possible ways of using keyboard shortcuts:

A. Use first English letter of said commands ("S", "A", "M", "P", etc.) for every locale.

B. Use first letter of the word on that locale (e.g. Russian shortcuts will be "С", "А", "Д", "П". German will be "H", "A", "S", etc..)

Which of these (or suggest your own) approaches is better when choosing the shortcuts for multiple locales?

P.S. Of course the shortcuts might be customizable by player, but some sane defaults are still needed.

# Answer
I'd say it's a good idea to set the hotkeys around the WASD area. At first it might be more intuitive to associate the command to its first letter, but it becomes a pain after you realize you have to push A and P 120 times a minute while handling mouse commands.

With the hotkeys set from Q to R, A to F and Z to V, we have a series of advantages:

* You never get lost since you always know where the letter F is;
* They are close to each other in a way you never waste time moving your hand across the keyboard (this is specially important in highly competitive games like Starcraft 2), making it confortable at the same time;
* It also keeps your hand close to the numbers, which you'll use all the time to select groups of units.

It's better to ignore the language and stick with hotkeys that become an advantage to the player who gets used to it, instead of the opposite.
> 12 votes

# Answer
If you set your interface up right, the association should be muscle memory, not the letter.

I always like the keystrokes in Diablo II where each bar was just a row of keys, you didn't have to think about what the developer called something, just where you put it on your HUD.

Perhaps the same approach could work in an RTS?
> 7 votes

# Answer
I'd never expect shortcuts to be in my language. Pretty much everyone who plays games knows English, it became a standard, and it's always a good idea to keep up to the standard. So stick with English.
> 5 votes

# Answer
In Natural Selection hotkeys were assigned to positions. If the command panel was something like:

```
 _____
|_|_|_|
|_|_|_|
|_|_|_|

```

Shortcuts would be:

```
 _____
|Q|W|E|
|A|S|D|
|Z|X|C|

```

You could also configure your own shortcuts, but the default was great because you just had to remember positions, not complex combinations of hotkeys. Also, it allowed me to make faster actions since my hand didn't have to travel all around the keyboard: it was just sitting at the left-side of the keyboard and barely moving.
> 3 votes

# Answer
I'd prefer one scheme over all locales, to make cross-language communication easier. Also it saves you a bit of work and eliminates a potential source of bugs.

Most important, for whatever scheme you settle for, is displaying the shortcut in the GUI, so players can quickly check the shortcut for any button they can press. So when you have a button for Move, Attack, etc., always label the button as "Attack (A)", "Move (M)", etc. Your players can then learn the shortcuts much quicker than if you hide them in the rebinding options or even the manual.
> 2 votes

# Answer
Well firstly, I'd say, "don't!" Professional Starcraft2 players regularly switch up their bindings until they're happy with the result. So while "building zerg drones" in the default mapping is 4+s+d it may be totally different on someone else's profile. I think Starcraft 2 even goes so far as to allow users to upload their settings to "the cloud" so that whenever they log in at a tournament everything is setup correctly.

So...what I would suggest is this:

1) Create enums for each command "create worker, built building, etc."

2) in a text file have mappings for keyboard values (w,a,s,d) to certain commands (attack, move, etc.)

3) ???

4) Profit

This way users can setup the mappings how they wish, and later on, you can go back and make a "shortcut editor" in your program that will edit this text file. In general, user input settings should never be hard coded.
> 2 votes

# Answer
**A** is more general and once you have set shortcuts you are sure if they overlap each other or not, witch can happen when you automatically translate orders.

Of course you have to let users to change them. Think about creating some patterns which trusted translators can change.
> 0 votes

---
Tags: keyboard, localization
---


title: MMO Proxy Server

text:
# Question
Title: MMO Proxy Server
I am building an MMO and someone told me I should never have my application interfacing directly with the net, and that I should have a local proxy. This makes sense, with security issues and scaling simplicity (add more servers behind proxy). But I'm not sure of the best way to implement this.

My gameserver is written in java, and I'd like to write my proxy in Python.

These are the methods I can think of to communicate between proxy and server:

A) Game Client \<-\> `UDP Protocol` \<-\> Python Proxy \<-\> `MySql Database` \<-\> Java Server

> I like this because it would force me to constantly save and store game server information (player and npc position, rotation, and health, item's and backpacks...). I would need to do this anyway, but maybe not every time I get a packet. Only issue I can see is performance with making all the database queries on both proxy and server.

B) Client \<-\> `UDP Protocol` \<-\> Python Proxy \<-\> `TCP Protocol` \<-\> Java Server

> I don't want to use UDP locally because UDP has packet loss and it's not worth doing locally `*`. TCP would work and be easy to implement but may have performance issues since TCP has a lot of overhead.
>
> `*` not entirely sure if true.

I plan to go with option `A)` but would like to know what you guys think, and if there are any other viable options to look into. So what do you think A, B or something else?

Thanks in advance.

# Answer
First of all, if you are doing a MMO, do that first and worry about issues you don't need now and you can "bolt on afterwards" later.

But if you insist, here are my 50 cents:

If you want to use MySQL as an interface between a proxy and the game mechanics server written in java then you will have a (very very) high latency between the moment a client asks for something and the time it gets an answer.

Secondly, the java server would probably do some polling scheme which will add further latency.

Third, when an UDP packet gets lost (and that will happen, trust me), you need to have some sort of timer that refires the packet which means even more latency.

This makes the setup clearly out of the range for a real time application (well, that's my opinion anyway).

If you don't want to go with a more simple setup, I'd advice this:

Game Client \<-\> TCP Protocol \<-\> Python Proxy \<-\> Java Server \<-\> MySql Database

or the simpler / better:

Game Client \<-\> TCP Protocol \<-\> Java Server \<-\> MySql Database

UDP is rarely needed nowadays, may it be for latency or bandwith, and as far as I can tell, the only bonus would be to be able to deflect some kind of attacks but for that you'd need even more proxies and a smart scheme to reroute data (you don't need that now though).
> 1 votes

---
Tags: java, mmo, server, python
---


title: Which server platform to choose

text:
# Question
Title: Which server platform to choose
I'm going to write a server for an online multiplayer with these requirements:

* Pretty simple turn based game (think a card game) that is played entirely on the server (security reasons)
* Must be able to run multiple games (tables) with 4 players per table, but no lobby system required (another server takes care of that)
* Can support as many players at once as possible; Might need multiple servers
* Chat between players
* Socket connection to a Flash/AIR client
* Must be able to communicate with other servers (for player accounts and such)

Now, I'm considering two options:

* Smartfox (or equivalent)
* A custom Java solution in something like Tomcat

Why Smartfox?

* It handles multiple rooms and chat natively
* It presumably has solutions for well-known multiplayer gaming issues

Why custom?

* Smartfox has many unneeded functions, bad for performance
* Smartfox communicates with an XML-based format, I could use a more efficient binary one.
* Don't know if running the entire game model on the server is convenient with Smartfox' extension mechanism
* Multiple rooms and chat are easy to reimplement
* Tomcat or a lightweight container is easier to deploy than Smartfox
* Better IDE support for developing on Tomcat (automatic deploy, etc)

What do you think? Are my assumptions correct? Do you have anything to add? What option should I choose (or maybe a different one entirely)?

# Answer
I'd definetely go with a custom solution : even though you might lose some time in the short term, it'll definetely scale better if you need it to, plus the experience you gain will be massively reusable for your next games. BlazeDs sounds like an excellent tool for your needs, but rewriting a Java game server from scratch is not that big of an endeavour, using for instance Netty and Protobuf :)
> 3 votes

# Answer
Regarding your points in support of a custom solution:

> Smartfox has many unneeded functions, bad for performance

Since this is for a "simple, turn based" game, performance is unlikely to be a problem.

> Smartfox communicates with an XML-based format, I could use a more efficient binary one.

Again, for simple turn based games ease of development can easily take priority over format efficiency, so unless you *want* to develop an efficient binary format - don't.

> Multiple rooms and chat are easy to reimplement

This is not a good reason for choosing to implement this functionality on your own. It's just something that's comforting to know, if you decide to follow this path.

> Tomcat or a lightweight container is easier to deploy than Smartfox. Better IDE support for developing on Tomcat (automatic deploy, etc)

You have to weigh how much time you save by developing a custom solution and deploying it fast, versus using an existing solution and possibly doing a longer deployment. Odds are that the development time will offset what little benefits faster/easier deployment gives.

**To sum up - I recommend using an existing solution, if possible.** It is likely to save you a lot of time. As for *which* pre-existing solution, that's up to you.
> 5 votes

# Answer
Having used both SmartFox and ElectroServer quite extensively, I always recommend ElectroServer. It does all the same stuff as SmartFox, but is just a bit more solid, and includes binary support.
> 3 votes

# Answer
I would strongly recommend looking at the Google App Engine project.

Both for hosting and technical reasons. If your game is not fast paced then that should be a good place to get started and up and running, and have the scope to scale.

Code can be in Python or Java.

Neptune's Pride is on Google App Engine. See an interview with the Developer here.
> 2 votes

# Answer
You should really look into Firebase, an open source Java multiplayer game server.

Compared to Smartfox, Firebase uses a binary protocol, is not bloated with features and is high performing.

If you roll your own system, you will have to take care of everything from handling sockets to handling concurrency. With Firebase, you are guaranteed one action at a time, per room.

**Note**: Firebase acquired by Google and it's no longer has open source option.

Check it out: http://www.cubeia.org/
> 2 votes

# Answer
Take a look at the following netty game server. It supports a binary protocol. Note: Written by me! Has TCP and UDP support, uses jetlang for extremly fast in vm messaging.
> 2 votes

---
Tags: networking, multiplayer, server, java
---


# Question
Title: How can I handle inventory in an object-oriented way?
I'm trying to think of the best way to handle player inventory following an object oriented approach.

For example, sword and axe are two different classes, both inheriting from weapon. Weapon and potion are also different classes both inheriting from item.

Ideally, the inventory would be implemented as a container of items, but that can't be done for several reasons. So it has to be a container of item (smart) pointers. Since I don't want to liter my code with calls to new and delete, I'll wrap it in an ItemWrapper class which news/deletes on ctor/dtor.

So the code will look something like this

```
class Sword;
class ItemWrapper;

//Prepare the long sword.
const Sword longSword(...params...);

//Declare the inv
vector<ItemWrapper> inv;

 //Add it to inventory
inv.push_back(longSword);  //compiles if ItemWraper(const Sword&) is defined.

```

This approach was the best I could come up with in terms of code clarity and ease of writing. The problem is that ItemWrapper will need one constructor for each leaf class that inherits from Item (which is a lot).

This is my first attempt at this, so I'd like to know: am I going the right way? or if there's a better way of doing it (perhaps one that avoids so many constructors)?

# Answer
There is something you are doing right now that you may find that you regret later, even though it seems like a logical thing to do.

You are likely to find that making each type of item its own class hard to manage once you have more than about twelve of them.

My own inventory management systems don't have different types for items. Instead, I use a "Descriptor" class, which has a set of properties (Name-Value pairs, stored in an associative container \[in C++ you would likely use std::map\])

The property getter is a template function that casts the property from the map into the appropriate type.

The way I differentiate between item types is to have an ItemType property, usually some sort of enum with entries like WEAPON, ARMOR, etc. Other properties contain damage ranges, references to images to use to render it, name description, etc.

Now, these descriptors aren't for item instances. They describe the item type as a whole. Item instances contains some sort of reference to the descriptor as well as a similar map of properties for values needed for an item instance (like individual durability, for example). In this way, one avoids repeating the same information over and over again. After all, one sword is about the same as another sword, it just might be closer to wearing out.

As far as avoiding constructor calls, I recommend a factory method.
> 9 votes

# Answer
> For example, sword and axe are two different classes, both inheriting from weapon. Weapon and potion are also different classes both inheriting from item.

I wouldn't do things this way; a sword and an axe differ mostly in their data, not their fundamental behaviors as weapons. Likewise with items. I would avoid this overuse of inheritance, starting by restricting yourself to just `Weapon` and `Item` (you could even fold these into a single class, but that's a different discussion). If nothing else this will alleviate the constructor explosion you're seeing in `ItemWrapper`.

> So it has to be a container of item (smart) pointers. Since I don't want to liter my code with calls to new and delete, I'll wrap it in an ItemWrapper class which news/deletes on ctor/dtor.

Consider the Boost smart pointers instead of rolling your own. They're fairly isolated from the rest of Boost (so you don't have a ton of dependencies to pull in if, for some reason, you don't want to take advantage of the rest of Boost's neat stuff), and many of them have been adopted to be part of the new standard library in C++11, so you shouldn't have issues upgrading.

> This is my first attempt at this, so I'd like to know: am I going the right way? or if there's a better way of doing it (perhaps one that avoids so many constructors)?

As above, I would strive to avoid inheritance for this, and consider using established third-party solutions instead of rolling your own. Those steps alone should remove much of the maintenance complexity you're discovering (or will shortly discover).

That said, another approach is to look at it this way: `ItemWrapper` is a band-aid for an implementation detail problem. It itself doesn't represent a real "object" in any typical sense. So think about what might be a better analogy that also solves your problem of having a place to put the automatic `new` and `delete` calls.

Most inventories allow (some) items to stack, do they not?

The "stackability" of an item is a property of that item, but the item itself should not be responsible for maintaining the stack. If you have a class representing an `ItemStack` with methods to query the size of the stack, split the stack, et cetera then you can put your management of the lifetime of the item pointer (which, I should note, may become slightly more complicated with stacks, thus providing another argument to use something like Boost) in the stack class along with the implementation of the rest of its behavior. Items that cannot stack are represented by a stack that always contains a single item, and your inventory itself still deals with homogeneous instances of `ItemStack`.
> 7 votes

---
Tags: c++, objects
---


# Question
Title: Creating pixel art / animation with flash
I have a friend that was the one creating graphics for my games. He left the town for some months (work, *sigh*) and I have tried to get in contact with him but it is impossible right now. Last talk I had with him he explained me that the graphics (2D) he did for my games were all made with flash and also the animations.

I can see why my pal does everything in flash: we develope for several movile platforms with different resolutions and having everything in vector format is nice.

My question is: How is he doing pixel art with flash? I recall he told me he was doing everything with vectors and later exporting to bitmpap, but, is it possible to do this with flash? Can't see how to do the pixel art feeling with vectors. If anyone could help here I would be really greateful.

Thanks in advance.

# Answer
Pixel-art and bitmap-graphics isn't exactly the same. A bitmap (or raster-graphic) doesn't imply anything about the "style" of the image. It's just a bunch of pixels... Exporting from flash (or any vector drawing application) to a bitmap is certainly possible.

Pixel-art on the other hand is a graphical style, usually with a limited palette and also often hand-painted (pixel per pixel). Naturally a piece of pixel-art is stored as a bitmap. Creating pixel-art with a vector-drawing application is counter-intuitive really. Pixel-art is made for a specific amount of available pixels. Scaling these graphics will result in blurry a picture, so there's no benefit in having them as vector-graphics.

A good vector-graphics artist has quite a different skillset from a good pixel-artist. It's not a simple matter of "export as bitmap".
> 3 votes

# Answer
It's possible that your friend is referring to Flash's ability to render out the screen as bitmap data. Sometimes this technique can be used to reduce processing footprint that your app uses, while still technically using vector graphics and working within the Flash IDE.
> 1 votes

---
Tags: 2d, flash, animation
---


title: Game Design Schools

text:
# Question
Title: Game Design Schools
Are there any Colleges/Universities (besides digipen i am aware of that one) that are centred around video game careers? Failing that any that have particularly good video game programs? preferably in Canada but not really necessary.

# Answer
> 1 votes
A simple google search of "top game design schools" offered me a lot of top searches already. This one seems to be from princetonreview is credible because it's known a lot for its rankings of top party schools and other quality-of-life ratings of college.

http://www.princetonreview.com/top-undergraduate-schools-for-video-game-design.aspx

I suggest checking the other links when doing a google search and you'd get more information out of it.

# Answer
> 1 votes
Take a look at the Game Career Guide Digital Counselor. It gives you a bunch of filtering options when it comes to searching for a school related to what your main focus of study would be. From there you could probably narrow it down to a few schools and specifically research them instead of doing this extremely broad research.

# Answer
> 0 votes
Reliable rule of thumb for most colleges: if it has a TV commercial somewhere, it's probably not worth your time. Local community colleges and trade schools that don't fulfill white collar jobs are the exceptions to this rule.

A college that would be worth looking into that's close to Digipen (and also in your country) is Vancouver Film School. Needless to say, this one is also of a high pedigree and you'll probably need ridiculous amounts of talent to be admitted to and keep up.

# Answer
> 0 votes
Since you said you don't need it to be in Canada, There is a nice and very video game centric college here in melbourne (Australia) called QANTM. You can choose a bachelor degree in Games Animation, Games Design or Games Programming.

http://melbourne.qantm.com/en-gb/course/2488/

I have a couple of friends who are attending it and it is quite a full on course. I completed a double degree at Swinburne University which was computer sci/Multimedia(Games and Interactivity) but not enough of the subjects were focussed around video game creation for my liking.

# Answer
> 0 votes
I went to Champlain College in Burlington, VT which is only about 2 hours south of the Canadian border. They have a program for Design, Art, and Programming. I studied design, but learned a fair bit of programming and am currently employed in the game industry so I can't really complain about the education I received.

---
Tags: game-design, education
---


title: How to handle many sprites and update?

text:
# Question
Title: How to handle many sprites and update?
I am making a game, and I just started to think about how I am going to update and render all the sprites on the screen. Should I store all sprites in some type of list (vector or something?) and then call the draw and render method on all those? I'm using SFML and C++ if that helps.

# Answer
The answer to your question is: yes, you will generally have a render list that you draw during the draw phase of the game loop.

After saying that, I must mention something I am seeing in your post... most notably that you are thinking of the sprites(the graphics representing your game object) as the things in the game(the game object themselves). This is a common misconception early on in game development that eventually leads to all manners of woe and gnashing of teeth. I recommend attempting to think separately in terms of game objects (the things represented in the game work with classes and code) and the sprites (the things that get rendered to the screen to give the player the illusion that the game objects exist). While there is certainly a relationship between these two things, they are not the same.
> 8 votes

# Answer
That depends on how many sprites you have in your world at a given time. If it's in the hundreds or low thousands, you should be fine just using a set, and shoving all sprites into that set. (I'd use a set rather than a list because you will probably need to add and remove sprites frequently.)

If you have hundreds of thousands of sprites in your world, and only a few are visible at once, you have more work. Obviously you don't want to render sprites that aren't in the current view.

In that case, keep things simple. Split up your world into chunks based on X-Y coordinates. Identify which chunks are visible in the current view. Only render sprites from those.

You should be able to identify the visible chunks very quickly -- if you have them in a 2d array and they're of fixed size, just divide the viewport rectangle by the chunk size. Otherwise, keep the list of visible chunks in memory; whenever the viewport moves, look at the neighbors for all the currently visible chunks to see if they're now visible and clear the no-longer-visible ones from your list.

Like moving a picture frame over graph paper.
> 1 votes

# Answer
What is your concern, exactly? Performance, or code beauty?

With C#/XNA, a common, simple, practical solution is to have a sprite manager component, which subscribes to the main class (and thus its update/draw methods get called regularly). You can easily duplicate this code without having the actual component API.

Speaking of components, occasionally the question of making every single instance a component comes up. It seems a reasonable enough idea, and it's always mentioned that you shouldn't do it, but I could never figure out why. Anyway, point is, that's an option too.
> 0 votes

---
Tags: c++, sprites, rendering, sfml
---


# Question
Title: How to store "chunks" of tiles or How to make my implementation work
I asked a previous question about the loading and unload of chunk data and people noted that my way of storing chunks is weird and I was wondering how I would go about doing it properly. @Byte56 suggested using a linked list or adjacency list but i have no clue how to do those even after searching google/stackoverflow. Any advice to a person new to xna programming?

Source

Previous Question

# Answer
> 3 votes
I think ClassicThunder is heading in the right direction, but he/she may be at the wrong level. Keeping an adjacency list at the Chunk level is fine, but it's not really the solution you're looking for to manage the loaded chunks at the World level.

If you're keeping the actual data for your chunks in the dictionary structure, all you really need is an array of keys, in your case chunk positions. This is actually fairly simple after I've thought about it more. For knowing which chunks should be loaded, all you really need is the root position of the chunk the camera is currently over. Now, you know what size each chunk is and you can figure out how many chunks you need to be visible at a time. So once you have the root position, it's really just a few loops to give you the positions of all the other chunks needed.

So for example, say you decide that having 9 chunks loaded at a time works well enough. This means the chunk the camera is currently over, plus all chunks that touch it horizontally and diagonally. That would mean the view area is no larger than a single chunk.

```
int range = 1; //This is the number of chunks from the center chunk to load
ChunkPosition rootPos = GetChunkRootAt(Camera.Position.X, Camera.Position.Y);
ChunkPosition[] Positions = new ChunkPosition[9];
int i = 0;
for(int y = rootPos.Y + (ChunkSize.Y * range); y >= rootPos.Y - (ChunkSize.Y * range); y -= ChunkSize.Y){
    for(int x = rootPos.X - (ChunkSize.X * range); x <= rootPos.X + (ChunkSize.X * range); x += ChunkSize.X){
        Positions[i++] = new ChunkPosition(x,y);
    }
}

```

I'm just running this in my head so I'm probably off by one or something, but I believe the above will fill the array with this configuration:

```
[0][1][2]
[3][4][5]
[6][7][8]

```

Now you have a list of chunks that should be loaded. Use that list to update your dictionary.

# Answer
> 2 votes
What we were recommending was treating each chunk as a node in an graph. The modification to your chunk data structure necessary to do this adjacency list. Note the list part doesn't dictate a List necessarily, I suggest a array for performance reasons and their simplicity.

The data structure should contain at least the two below fields.

```
public class Chunk {
    private Point position
    private Tile Tiles[]
    private Chunk AdjacencyArray = new Chunk[8]
}

```

This allow for the below. '@' is the current chunk. 0 is the chunk to the top left of the current chunk. 1 is the chunk above the current chunk. So on and so forth all indexes of the above AdjacencyArray field.

```
[0][1][2]
[7][@][3]
[6][5][4]

```

Now assuming we have multiple chunks 1, 2, and 3 in a grid

```
[ ][ ][ ][ ]
[ ][1][2][ ]
[ ][3][ ][ ]
[ ][ ][ ][ ]

```

The AdjacencyArray for chunk 1 should be

```
AdjacencyArray = { null, null, null, Chunk2, null, Chunk3, null, null }
AdjacencyArray[3] = Chunk2
AdjacencyArray[5] = Chunk3

```

The AdjacencyArray for chunk 2 should be

```
AdjacencyArray = { null, null, null, null, null, null, Chunk3, Chunk1 }
AdjacencyArray[6] = Chunk3
AdjacencyArray[7] = Chunk1

```

The AdjacencyArray for chunk 3 should be

```
AdjacencyArray = { null, Chunk1, Chunk2, null, null, null, null, null }
AdjacencyArray[1] = Chunk1
AdjacencyArray[2] = Chunk2

```

I'm hoping that illustrates that an adjacency array merely stores a reference to the chunk. And the index of that reference describes where referenced chunk is located related compared to the current chunk.

Now lets say the camera is in chunk 2 and moves down. We now have to add 4. We then have to update all old chunks (O) so they and the new chunks (N) point towards each other. There are various ways to do this none of them particularly elegant. In fact I kind of like you idea of the dictionary with the location as a hash. It would allow the linking to happen in what is basically O(8).

```
[ ][ ][ ][ ]    [ ][ ][ ][ ]
[ ][1][2][ ]    [ ][O][O][ ]
[ ][3][4][ ]    [ ][O][N][ ]
[ ][ ][ ][ ]    [ ][ ][ ][ ]

```

---
Tags: xna, c#, xna-4.0, tiles
---


# Question
Title: Problem when animating MD5 model (GPU Skinning)
I'm trying to implement a GPU skinning version of the md5mesh.js by @tojiro (demo with CPU skinning) in WebGL (live demo of the project here, use WASD to move the camera around).

The main concept is as follows: I modified the Vertex buffer object in order to fit the information of bones indices and bone weights, then for every frame of the animation I modify the bone matrix (an array of transformation matrices for each bone) with the appropiate matrix (for each joint I create an identity matrix and multiply it by it's orientation and position, then I multiply the result by the inverse of the bind pose and it's ready to go to the shader).

This works OK when the boneMatrix array is filled with identity matrices (by concept it should render the bindPose and it does). However when I try to load an animation the movements appear messed up and clipped. I discarded a wrong/corrupt version of the md5mesh / md5anim by loading them in an MD5 viewer.

Here there is an example of what happens when the boneMat array is filled with identity matrices:

I think this is the way the model should look, but when I try to animate it...

The general movement of the mesh is correct but some vertices move with an strange direction / orientation which forces a lot of clipping to occur.

Maybe someone experienced in the matter can spot the problem directly from the image, if not I' willing to provide any part of my modifications on the md5Mesh lib.

In order to implement all of this I've followed this tutorial and took a lot of ideas from this implementation.

Any help will be appreciated, I've really hit a wall with this!

Thanks in advance.

# Answer
I know it's a boring suggestion :) but I suggest to go back to the basics. When I was writing my skinning code I started with 1 bone and 1 vertex, then 1 bone affecting 2 vertices, then 2 bones affecting 2 vertices (100% weights), then 2 bones affecting 2 vertices (50/50% weights) and so on.

You can easily manage this amount of data manually so write a set of tests to verify the vertices end up where you want them to. You will want your code to be as similar to a shader code as you can, using the same input/temporaty data structs you would with a shader etc. and essentially simulating your vertex shader on the CPU. By the time you have 3 bones and 5 vertices running fine your code is almost guaranteed to be OK, then it's time to move your code to a shader. If you made sure your code takes the same data format as input as the shader does it should be a straightforward port so any bugs will be easy to spot.

Oh, and:

* remember to test straight bone chains and branches (two bones having the same parent) separately
* not sure about md5 but in other formats you may get not normalised weights so test some crazy weights and make sure it works fine
* again, not sure about md5 but you may need to handle multiple root bones
> 1 votes

---
Tags: shaders, javascript, 3d-meshes, browser-based-games, webgl
---


# Question
Title: How to use Kobold2D/Cocos2D to create a turn-based iOS 5 Game Center game?
I've searched for information on this, but cannot find it, is this not something you can do yet with Kobold2D/Cocos2D? or are there options I've missed?

# Answer
> 3 votes
You can make your game using the Cocos2d framework and GameKit framework combined, there should not be any issue with that.

What you need to do is create the user interface using Cocos2d framework and then handle the turn based events using the classes provided by game kit framework.

Example:

If you are creating a card game (like uno) in Cocos2d, then you will be using the `CCLayers` , `CCSprites`, etc. to display the cards and other components on the screen and for handling the turn based events like when a players turn comes to play a card from the pile in his hand you will have to use GameKit classes to send and receive the data from each player in the session.

---
Tags: ios, cocos2d-iphone
---


# Question
Title: How to manage merging/splitting viewports to create a dynamic splitscreen
I'm making a multiplayer 2D game where each player has an entity that they can move in any direction. This will be local only, so split screen.

Typically the player controlled entities will be in close proximity to each other. **What I would like to do is have the screen get split only when players are far away** \- i.e. when it needs to.

See around mid way through this YouTube clip of Mari0 for an example of what I mean.
See this clip of Super Mario Bros X (sorry, it's a bit of a low FPS) for an example of horizontal & vertical splitting.

There starts off being a single viewport (or maybe 2 rendered to look like one). Then, as the players separate, either vertically or horizontally it splits the screen giving each player is own viewport.

**How would I go about creating this effect?** (managing the viewport merging/splitting etc)
**How about extending it to work for up to 4 players?** (is that even possible?)

# Answer
To create the effect I would go for 2 viewports and masking/clipping.

When players are close to each other there's 1 viewport centered at the point half between players (maybe regarding movement vector). When players start to get apart you need to switch to 2 viewports plan.

Initially, when players are getting apart there should be 2 identical viewports which will get different shortly after. You might add sort of effect to display a border appearing between them in that time. While viewports are changing you also start centering on players, so they are no longer in corners. Optionally moving the viewports so that they take left/right half of the screen (or keep them alted in any direction). You can do the merging same way in reverse order (detect when to merge)

When the viewports are apart the render order will be like so:

1. Set clip area for 1st viewport (either by mask or by clip plane)
2. Render vieport 1
3. Set clip area for 2nd viewport (invert the mask or clip plane)
4. Render vieport 2
5. Release clip mask/plane
6. Render common stuff (border, GUI, etc.)

There's an issue when players move around each other (B player got left part of the screen and moves around so that he is in right of A player). For that case you need to track players positions and change viewports split from vertical to diagonal and horizontal and vertical again with A and B exchanging places (left/right).
> 2 votes

# Answer
The dynamic split screen of Mari0 looks fine because the frame just before the split is identical to the one after the split, plus the split line.

Either you manage such a thing, or you should think really hard about how to make it actually playable.

This won't work if the players might move in both horizontal and vertical directions (unless you plan about a diagonal split, of course...)

One way you could make it work under harsh conditions such as the diagonal split, could be to actually diagonally split it, and then gradually "move" the split line to be vertical again.
> 1 votes

---
Tags: 2d, multiplayer
---


# Question
Title: need to create formulas for stat, level progression etc. What tools will help the not-mathematically-literate?
I want to create some of the fundamental guideline formulas for a game I am working on. I am following on from sirlin's advice in that I am starting with some assumptions and working back from there.

So let's say that I want to have the player do an average of 1000hp damage at level 100 and 10 at level one. Is there a tool that I could use to draw this (a low exponential curve) and it would spit out a formula based on the curve?

There are some similar questions on here but none that I can find with any advice on the specifics of making the formulas for these progress curves.

thanks

# Answer
Since you want an **exponential curve**, maybe you could teach yourself logarithms so that you are comfortable enough to solve your problem by yourself?

There are basically three things to know:

* the reverse operation of `exp` is `log`: `log(exp(a)) = a`
* `exp(a+b) = exp(a) * exp(b)`
* `log(a*b) = log(a) + log(b)`

Let’s see your specific problem. You want a rule such that:

```
damage = A * exp(B * level)

```

Now we just need to find `A` and `B`. Write down your two requirements (damage 1000 at level 100, damage 10 at level 1):

```
1000 = A * exp(B * 100)
10 = A * exp(B * 1)

```

If these are equal, then certainly their logarithms are equal:

```
log(1000) = log(A * exp(B * 100))
log(10) = log(A * exp(B * 1))

```

Use rule 3 to break down `log(a*b)`:

```
log(1000) = log(A) + log(exp(B * 100))
log(10) = log(A) + log(exp(B * 1))

```

Use rule 1 to get rid of `log(exp(…))`:

```
log(1000) = log(A) + B * 100
log(10) = log(A) + B

```

Subtract through:

```
log(1000) - log(10) = B * (100 - 1)

```

This gives the value for `B`:

```
B = (log(1000) - log(10)) / (100 - 1)

```

And from the original equation `10 = A * exp(B * 1)` we get:

```
A = 10 / exp(B * 1)

```

The same method can be used to get a generic formula. You can replace 1, 10, 100 and 1000 with other values of your choice.
> 4 votes

# Answer
This may be controversial but get some graph paper. Draw in the axes and number range you want to cover (100 to 1000hp). Lay down a nice looking curve and read the numbers off to create your data table.

You need zero math; you can create any kind of curve imaginable and even curves with "hell levels" or "easy street" areas that would take a mathematician and a lot of code to mimic.

Plus you can easily take these numbers and hand tweak ranges that don't feel right during game testing without having to do even more corrective math.
> 5 votes

# Answer
Use the Wolfram Alpha Regression to fit array of data into a specific type of function. Given your example, it would be something like `cubic fit {1,10}, {100,1000}`. Try out different models (linear, logarithmic etc.) to get different types of resulting curves

Examples of regression analysis
> 4 votes

---
Tags: mathematics, game-mechanics, rpg, levels, statistics
---


# Question
Title: How can I organize render and transformation data in a scalable fashion?
I am writing for OpenGL 2.0 and in the future porting to OpenGL ES 2.0. I only use VBOs and shaders (no immediate mode, no vertex arrays).

I already have working solutions, they just... feel wrong. All my calls related to OpenGL are tucked away in a separate class called RenderManager (this includes creation of VBOs and IBOs, texture IDs and shader programs) and rendering. I called the creation of OpenGL objects logging in and out, so majority of this action is invoked from the ResourceManager object upon loading of data. However, a lot of geometry (level) is generated dynamically and therefore some RenderManager calls to create the VBOs/IBOs is scattered throughout the level class.

Now, I have a Renderable interface which returns the (single) transformation matrix and a RenderOp object when it is time for rendering. RenderOps is an object that has Vertex/Index Buffer pointers (has actual geom. data which in turn has VBO/IBO indices) and some parameters such as whether to use the index buffer and if the RenderOp needs blending and stuff.

There is also the RenderView object; it has the viewport parameters, projection matrix and view matrix (camera).

The game objects reside in the World class (single-dimension arrays). These game objects are added upon their creation, and are derived from Entity interface. Entity is able to return the number of Renderable-type objects within as well as the actual pointer to a Renderable at a given index.

The magic happens when the main loop traverses the World. First it collects all Light objects visible from within Frustum. Then it collects Entity object that's within Frustum (it gets added to std::vector inside RenderView if it is), and then it checks that same object to see if it is inside any of the visible Light's bounding volumes (and gets added into Light's std::vector).

Then the RenderView is passed onto the RenderManager class, which extracts appropriate Renderables from each Entity, applies Renderable's shader, then applies Renderable's textures, then stores the transforms inside itself and promptly shoves them down the programmable pipeline's throat along with attributes stored inside the RenderOperation (that gets extracted from Renderable as well).

Last note - I have NO way to render debug data, which is extremely annoying.

A lot of what I am doing feels wrong. My question is, how do you organize all your Renderable and Transformation data to facilitate your rendering needs? I am burning out thinking of semi-flexible ways of managing this data and I want to hear your ways. I am not a big fan of scene graphs, and consequently don't really want to implement one as I feel there are no real hierarchies inside the game, but I feel like I'm running myself into a corner.

Please throw me a bone here, how do you manage all this data? And if you suggest an event based rendering system, how would you design it?

# Answer
> 2 votes
I'm not a professional and my answer is not OpenGL-specific, so take things with a grain of salt, please.

That said, what I did in my own little rendering framework was this:

Everything that would qualify as a "GameObject" (in a strict OOP perception model) is called an entity. Entities are represented by just integer keys retrieved from an entity store. Entities can consist of any number of components. Those contain the real functionality and would be Mesh, Material, Transform, CollisionVolume, AudioPlayer, etc. When one wants to attach a component to an entity, they hand the entity key to a store for the wanted component. Behind the scenes, that store creates another component in a linear array of same-type components and remembers that whenever someone wants the retrieve a component with the same entity key, it's the one just created.

That way, if some components can be "updated" in bulk without knowing about anything else (Collision Volumes for instance) they are all linearly laid out in the component store's memory and if someone wants to retrieve just one of them, they can do so via the key.

So much for the general thing. Now regarding rendering, I'm still left in some kind of halfway immediate mode, where I tell the renderer the entities I want rendered via entity key. When I'm done declaring entities to be rendered, the renderer fetches all the components required for rendering, e.g. Mesh, Material, Transform (wich is Scale, Rotation, Transformation). Mesh- and Material-ID as retrieved from their component stores are aggregated into a sort-key, so that "entities to be drawn" are then grouped by similar meshes and materials. The Transforms have to sorted alongside so I can pack them up and provide them to instanced draw calls where many entities with the same mesh are submitted with just a single draw call and all necessary position data. Christer Ericson has a great post on this on his blog.

I'm just throwing this out, not knowing whether that last bit is a good idea at all (in OpenGL ES, anyway). I'm also aware that I glossed over a lot of details but it ought to be kept simple so you can evaluate the idea. Anyway, this whole thing should scale pretty well (provided the component stores and sorting mechanisms are implemented efficiently) and should also lend itself well to be data-driven as one just needs a mechanism that reads entity/component descriptions and then hits the stores to plug the components together.

One big question mark for me is how to handle interaction between components, but you wanted to know about rendering, so that should do for now :)

EDIT: Check out Niklas Frykholm's blog for a clever way to manage associating entity-keys to components.

---
Tags: opengl, c++, rendering, opengl-es2
---


# Question
Title: Is it possible to have a cross platform multiplayer game on iOS?
Does Apple allow socket programming? I figure if I am able to send and receive UDP packets (at least over wifi) the possibility is there.

# Answer
Yes you can do it, why didn't you even bother to search?

This post implies you can, and this one links a page @apple which also implies you can.
> 3 votes

# Answer
I don't know about socket programming but you could have a server through which the 2 devices can communicate and exchange data.

Or if you don't have a server then you can use BUMP for your cross platform game.
> 1 votes

---
Tags: iphone, networking, multiplayer, ios, ipad
---


# Question
Title: Why do I get a segmentation fault on launch with this code?
I am currently writing a pong clone in C++ with SDL on top. Currently, I have hit a roadblock. If I add a new variable, my game won't launch, and will give "segmentation fault" in the debug terminal.

When I comment out a variable, the following code gives no errors, but otherwise, it just returns "Segmentation Fault" on the debug terminal after flashing the frame the game would normally appear in.

```
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#ifdef __APPLE__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#include "SDL/SDL_image.h"
#include "SDL/SDL_framerate.h"

#include "checkcol.h"

Uint8 *keystates = SDL_GetKeyState( NULL );

int main ( int argc, char** argv )
{
    // initialize SDL video
    if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    {
        printf( "Unable to init SDL: %s\n", SDL_GetError() );
        return 1;
    }

    atexit(SDL_Quit);// make sure SDL cleans up before exit

    // create a new window
    SDL_Surface* screen = SDL_SetVideoMode(640, 480, 16,SDL_HWSURFACE|SDL_DOUBLEBUF);
    if ( !screen )
    {
        printf("Unable to set 640x480 video: %s\n", SDL_GetError());
        return 1;
    }

    SDL_Surface* left = IMG_Load("left.png");
    SDL_Surface* right = IMG_Load("right.png");
    SDL_Surface* ball = IMG_Load("ball.png");

    if (!left||!right||!ball)
    {
        printf("Unable to load a png: %s\n", SDL_GetError());
        return 1;
    }

    // centre the bitmap on screen
    SDL_Rect leftr;
    leftr.x = 0;
    leftr.y = (screen->h - left->h) / 2;

    SDL_Rect rightr;
    rightr.x = (screen->w - right->w);
    rightr.y = (screen->h - right->h) / 2;

    SDL_Rect ball1;
    ball1.x = ((screen->w - ball->w) / 2)+50;
    ball1.y = (screen->h - ball->h) / 2;

    SDL_Rect ball2;
    ball2.x = ((screen->w - ball->w) / 2)-50;
    ball2.y = (screen->h - ball->h) / 2;

    bool b1xm=0;//describes ball 1's movement in x
    bool b1ym=0;
    bool b2xm=1;
    bool b2ym=1;

    unsigned short lscore=0;
    unsigned short rscore=0;

    FPSmanager * manex;

    SDL_initFramerate( manex );
    // you want the top framerate to be 60 for example
    SDL_setFramerate( manex, 60 );

    // program main loop
    bool done = false;
    while (!done)
    {
                         //this is where my main code is
    } // end main loop

    // free loaded images
    SDL_FreeSurface(left);
    SDL_FreeSurface(right);
    SDL_FreeSurface(ball);

    // all is well
    printf("Exited cleanly\n");
    return 0;
}

```

# Answer
You are passing an unallocated pointer (manex) to a function that is expecting it to be allocated. In debug mode, you are passing (IIRC) the value 0xCDCDCDCD. In release, you are passing it a mystery value.

Take out the * between FPSmanager and manex, like so, and use the addressof operator:

```
FPSmanager manex = {0};
SDL_initFramerate(&manex);
SDL_setFramerate(&manex,60);

```

Chances are this is your actual problem, the other issue of variables perhaps just masking it.

Also, as I commented above, *DO NOT* call *ANY* other SDL function prior to your call to SDL\_Init. You've been warned.
> 6 votes

# Answer
```
Uint8 *keystates = SDL_GetKeyState( NULL );

```

This is initialized at startup, even before your main() is called, thus it is called before SDL\_Init.

Change it to:

```
Uint8 *keystates = 0;

```

and later on, in main() After the SDL\_Init;

```
keystates = SDL_GetKeyState( NULL );

```
> 1 votes

---
Tags: sdl
---


# Question
Title: Calculating the number of tiles shown on an isometric map
I'm currently changing an existing computer game from a top-down view to an isometric view. The map consists of an infinite number of tiles. Only the tiles which are currently visible in the players window should be shown.

What i know is:

* How many pixels the worldmap has been scrolled on x and y axis
* The width and height of a single tile
* The width and height of the players window

What i need to know is

* The coordinates of the first tile to be shown
* The amount of tiles that will fit in the players window

To visualize the old approach was something like this (the dashed square represents the players window):

So with the old approach this calculation was pretty simple.

The new one looks like this:

And this is where i'm stuck at the moment. I can't figure out how to calculate which tile is in the upper left corner of the players window and how many tiles fitting inside the players window on the two new axes.

Can anyone help me with that? If yes, it would be really nice if the solution also contains a short explanation.

Thanks a lot in advance.

# Answer
If you have a "screen-pixel" to "tile" position function, you could just get the tiles from the 4 corners of the screen and you are done (the green ones in your second image where the dotted line have a corner).

How to do it if you don't?

You might want to check out "Mapping Screen to World Coordinates" here (scroll down a bit)

(fast answer as I'm @ work)
> 3 votes

# Answer
Sorry running a bit out of time. The main idea is to think "triangular" and no longer "rectangular". So you need to find out which triangle is in the upper left corner of the window and how many triangles fit in it. Then the last step would be to convert this into the "rectangular world".
> 0 votes

---
Tags: tiles, maps, isometric, tilemap
---


title: Open trading card game rulesets?

text:
# Question
Title: Open trading card game rulesets?
Got pitched a project where we need to make a trading card game to promote a clients project. I don't have any brilliant ideas for rules, but was pondering if any "open-source" rulesets existed, or if its possible to purchase a licence to use some ruleset somewhere.

I noticed that Shadow Era are using the exact same rules and card structure as the World of Warcraft TCG, and was wondering if that was open, or just a "ballsey move" from Shadow Era's side.

It's gonna be a duelling TCG, but we are throwing a steampunk setting in the mix, to seperate it from the fantasy brands.

It's ofcourse sad that we don't have the time to come up with our own original and thrilling card game structure, but the hours we would have to put into making such a system is simply way out of our budget.

# Answer
> 0 votes
Using another card games rules is kind of a tricky thing to do as you may have the rules but since you would be using your own info/stats/etc on the cards, the rules or cards would have to be adjusted (over and over) to fit your needs. Which could go waay beyond your projects scope. Some searching online doesn't really offer much in terms of public domain or open tcg rules so your best bet would be to spend some time learning multiple card games rules and taking notes from them. There are a good handful of rules that pretty much span across all card games that you could use as a 'skeleton' for yours.

Licensing the rules from another company could be an option but to find the right company for the right price would probably take a long time and could turn out to be a problem down the road when you want to change things.

---
Tags: game-mechanics, open-source, card-game, architecture
---


title: music for an arcade game?

text:
# Question
Title: music for an arcade game?
I'm thinking about music for my brick breaker game, but I don't know how to choose any.

If I'd make a loop from a few seconds, I think it would get annoying very quickly. I also found some longer length tracks (about 2 minutes), but when this is over, it's going to be repeated anyway, just like when you'd select a new level, you'd have to listen to the same beginning of the song again.

I can't put an hour of music in my application, so what would you recommend I'd do for the music?

# Answer
> 3 votes
All arcade game music is repetitive **if** you pay attention to it. The music you choose should not be something that is very noticeable. You want your users to be playing your game not listening to the music. The music should just be there to fill in the void of no sounds.

As an example, take a look at the tetris sound tracks.

As a side note, if you are looking for a program to help make sound effects I would suggest trying this: http://www.drpetter.se/project\_sfxr.html

# Answer
> 1 votes
First, find a loop of music that is a few minutes long, and isn't very annoying to listen to (not too loud, no really obvious parts that'll signal it's repeating), and use that for your game.

Second (and more importantly), give players the ability to *turn off* the music, probably with a single button that is always accessible in the game.

A combination of these should make it possible to have some music that works, but won't get annoying to players, because they can just turn it off when they get bored of it.

---
Tags: assets, sound, audio, music, user-experience
---


title: Top-Down Racing Game C++

text:
# Question
Title: Top-Down Racing Game C++
I'm creating a Top-Down Racing Game in C++ using GLUT/OPENGL and SOIL first of all I just wanted some opinions on how the track should be done. I was thinking about using a tile-map and so far I've implemented one but it draws a polygon for each value in the tile-map then uses the assigned texture. This is obviously a really in efficient way of drawing the background.

So how to go about concatenating the appropriate texture's together into one PNG/GL-TEXTURE that way I can just draw one big polygon and use the texture created from the concatenation process.

Also what's the best way of going about collision detection when it comes to tile-maps?

# Answer
You have a few thousand polygons on screen, so what? Do you experience performance issues on anything better than a 5 year old cheap laptop? Cause you shouldn't, and if you do it's not because you use a few thousand polygons.
> 2 votes

---
Tags: c++, opengl, textures, glut
---


title: What makes "AAA" games so special?

text:
# Question
Title: What makes "AAA" games so special?
What makes a "AAA" game. and its engine and technology, so special? Why are they so hard to make, and take so long to make? Why can't an average basement dweller write a game or engine with graphics that are just as good or realistic?

Take *"Crysis"* or *"Battlefield 3"*, for example; if someone knew the techniques, algorithms, and everything else needed, what would stop them?

# Answer
1) **Creating Assets** What "looks good" has a lot to do with a combination of technical features + artwork. Once you implement a i.e. a displacement map shader, you need to find a good artist and provide him with the tools to generate said displacement map. For an AAA game, the team involved in creating the assets is huge.

2) **Performance and resource budgeting** It's much easier to make a feature that runs a demo scene at 60fps on your beefy development box than to run the maximal scene in the game at 60fps on your minimum specs (and consoles)

3) **Time and Effort** I'm not a professional, and I have no numbers for AAA games, but here's a useful number: http://www.ohloh.net/p/doom3/estimated\_cost Doom 3. 174 person-years.

4) **Nothing, really?** If you're just looking to implement cool graphics features, go ahead and whip a tech demo together! I saw this video a while back: http://www.youtube.com/watch?v=9N-kgCqy2xs or just youtube for random Unity3D or XNA demos or follow indie studios like Wolfireand you'll see that people outside the AAA game world are putting together great things.
> 8 votes

---
Tags: game-design
---


# Question
Title: How to run DirectX10 on non-compatible hardware?
I'm going to be away for a little bit, bringing my netbook with me to do some basic DirectX10 stuff.

**How can I run DX10 on DX9.0c hardware?**

# Answer
> 12 votes
## Windows Advanced Rasterization Platform (WARP)

> WARP is a high speed, fully conformant software rasterizer. It is a component of the DirectX graphics technology that was introduced by the DirectX 11 runtime. The DirectX 11 runtime is installed on Windows 7, Windows Server 2008 R2, and Windows Vista with the \[KB971644\] update.
>
> **To use WARP**
>
> Direct3D 10, 10.1, and 11 components can use an additional driver type that you can specify when you create the device (for example, when you call the `D3D11CreateDevice` function). This driver type is `D3D10_DRIVER_TYPE_WARP` or `D3D_DRIVER_TYPE_WARP`. When you specify this driver type, the runtime creates a WARP device and does not initialize a hardware device.
>
> Because WARP uses the same software interface to Direct3D as the reference rasterizer does, any Direct3D 10 or 10.1 application that can support running with the reference rasterizer can be tested by using WARP. To use WARP, rename `D3d10warp.dll` to `D3d10ref.dll` and place it in the same folder as the sample or application. Next, when you switch to ref, you will see WARP rendering.

I copied all of that from the article, but looks like the most relevant and useful part. You probably should read the entire article though.

I was pretty sure that doing this was impossible when I read your question. A little digging and I was surprised.

# Answer
> 2 votes
Direct3D no longer ships with a software rasterizer. You could, however, check out WARP. http://msdn.microsoft.com/en-us/library/gg615082.aspx

# Answer
> 1 votes
WARP is good but you're going to find it quite slow on a netbook. My experience is that even on a quite beefy i7 it struggles to hit 60 fps with relatively simple scenes, and also is incredibly CPU-intensive - more black marks against it for netbook use.

If you want to use the D3D10 API I'm going to make an alternative suggestion. Don't. Use D3D11 instead and use feature levels to gain support for downlevel hardware. Just specify D3D\_FEATURE\_LEVEL\_9\_3 in your D3D11CreateDeviceAndSwapChain call, stick within the documented restrictions, and you'll run.

---
Tags: directx10
---


title: isometric buildings

text:
# Question
Title: isometric buildings
after switching to a third person view I was intrigued to make my new project isometric. Since I haven't really started yet this isn't much of a problem. Work so far was merely testing movement and camera control. As I'm using panda3d I just need to update the camera to render in orthographic perspective.

I have to admit that I didn't intend to go for a "pure" isometric game. The standard implementation with sprite-based rendering requires a tiled map but with panda3d I thought I'd just do this:

* Create a normal, textured map.
* Add a vertical mesh for each vertical object in the game. This mesh serves as a canvas: A partially transparent texture is drawn on it.
* Add a horizontal mesh that works equally for horizontal objects.

When the player steps behind one of these canvas meshes it's faded out. This works great for smaller objects like trees or stones. But there's a problem with buildings:

Imagine a multi-floor building with each of its four walls being rendered on one of the omnipresent canvases. Upon entering the first floor the horizontal objects of all floors above the player as well as the front wall become transparent. Now the player climbs up the stairs to the second floor. That means that only a part of the outer wall has to be removed. The wall around the basement can remain visible. With my current solution I'd always saw off the entire front.

The first idea that came to my mind was to split the wall into different sections.

**Question:** Is there a "canonical" implementation of multi-floor buildings in isometric games ? How are vertical tiles implemented ?

What would you do ? Please answer the second question on behalf of panda3d's possibilities.

# Answer
> 3 votes
Generally speaking, multi-floored buildings in an isometric perspective are handled by making the floor above transparent and only the outer walls (that are facing the camera) of the floor below visible, just as I think you are saying.

Do you have any images that can help describe the issue that you are having?

---
Tags: rendering, isometric, panda3d
---


# Question
Title: Which approach is better: Frequent small updates, or occasional large ones?
I recently released the first publicly available free Alpha for my top-down shooter: Dread

I'm trying to decide whether a weekly / bi-weekly small update release schedule is better than the more traditional monthly (or longer) large updates.

The more frequent schedule would mean that players would have a new build to play more often, but the new builds would likely only have a few bug-fixes / feature additions at a time. Would players grow tired of the constant updating, or would they feel more attachment as they are more involved in the development process?

I'm thinking that, due to the somewhat experimental nature of my game, it might be a good thing for people to have the opportunity to suggest tweaks to the new features during their infant stages. But I don't want my desire for feedback to bias my decision.

What are your thoughts / experiences on the matter?

# Answer
This depends on the average time between plays of your game. Profile your player base or gather statistics about how often they play.

Two extremes to modify according to your situation:

If players **play every day**, like in World of Warcraft, lean towards **incremental updates**. The game will feel more alive, offering a little bit of new content every couple of days. This also means players will not be faced with a huge download and/or jarring gameplay changes.

If players **play for a few days every two months**, like in Terraria, lean towards **larger updates**. When players come back to your game, they will have the opportunity to experience a heap of completely new content, hopefully reinvigorating what they found fun to begin with. This also means players coming back will usually only have one update to worry about.
> 10 votes

# Answer
First, if feedback is your goal, I would recommend setting up a UserVoice account. You can get one for free (with some limits). Drop a link in your game for feedback to go to your uservoice page.

The update schedule really depends on how simple your update process is. If all I have to do is double click your patcher, wait five minutes (or less) and start playing, I think a bi-weekly is fine.

Now, for an alpha/beta, bi-weekly is fine, maybe even weekly or every 10 days would work. That keeps people involved and they feel like there is something new happening. Once your game is released, I would rather see monthly updates, with immediate critical bug fixes.

That said, you can still gain feedback through external sources, I recommend uservoice because its simple to setup, and it is very simple for your users to submit feedback. That said, there are other providers with similar services. Check them out and pick one that suits you.
> 3 votes

---
Tags: game-design, game-industry, release
---


title: Javascript Isometric draw optimization

text:
# Question
Title: Javascript Isometric draw optimization
I'm having trouble with isometric tiles drawing.

At the moment I got an array with the tiles i want to draw. And it all works fine until i increase the size of the array.

Since I draw ALL tiles on the map it really affects the game performance (obviously) :D.

My problem is I'm no genius when it comes to javascript and I haven't managed to just draw what is in viewport.

Should be fairly simple for an expert though because its fixed sizes etc. Canvas is 960x480 pixels, each tile 64x32. This gives 16 tiles on first row, 15 on the next etc. for a total of 16 rows.

Tile 0,0 is in the top-right corner. And draws X up to down and Y right to left. Going through the tiles on the first row from left to right as +X -Y.

Here is the relevant part of my drawMap()

```
function drawMap(){
    var tileW = 64; // Tile Width
    var tileH = 32; // Tile Height
    var mapX = 960-32;
    var mapY = -16;
    for(i=0;i<map.length;i++){
        for(j=0;j<map[i].length;j++){
            var drawTile = map[i][j];
            var drawObj = objectMap[i][j];
            var xpos = (i-j)*tileH + mapX;
            var ypos = (i+j)*tileH/2 + mapY; // Place the tiles isometric.
            ctx.drawImage(tileImg[drawTile],xpos,ypos);
            if(drawObj){
                ctx.drawImage(objectImg[drawObj-1],xpos,ypos-(objectImg[drawObj-    1]));
            }

        }
    }
}

```

Could anyone please help me how to translate this to just draw the relevant tiles? It would be deeply appreciated.

# Answer
You need to modify your start index of the for loops so that i and j start at your current screen offset. Lets leave those at i=0, j=0 for now. (Assuming no scrolling)

Then you need to modify your end indices, map.length & map\[i\].length. This means you are drawing all the tiles, but like you said there is a limited amount of tiles you see, all dependent on your screen height/width.

As a starting point i would set the first for loop's end to ScreenHeight / tileH and your second for loop to ScreenWidth / tileW.

```
int ScreenTilesHeight = ScreenHeight / tileH + 1;
int ScreenTilesWidth = ScreenWidth / tileW + 1;
for(i = 0; i < ScreenTilesHeight ; i++)
{
  for(j = 0; j < ScreenTilesWidth ; j++)
  {
...

```

I don't know how big your canvas is so fiddle around with the **\+ 1**, until you are happy with the looks.
> 1 votes

# Answer
You can have your for() loops cover a rectangular area of the map which is big enough to cover the whole screen. This is a lot more tiles than you need.

Then you can further cull tiles which are off the edge (e.g. the diamond-shaped area which is outside of the screen rectangle) after you do the transformation.

If after transformation a tile is obviously off the edge of the screen, don't render it.

This is not the most "clever" or "efficient" way, but it is most likely to work.
> 0 votes

---
Tags: javascript, html5, isometric, html-canvas
---


# Question
Title: Unity3D GUI - what exactly it does when create controls and check their statuses?
On unity3d website in the manual on this page: http://unity3d.com/support/documentation/Components/gui-Controls.html

I found an example of "GUI.changed" function usage(below). And it looks like it creates toolbar object on every frame. Am I right or not?

```
/* GUI.changed example */

// JavaScript
private var selectedToolbar : int = 0;
private var toolbarStrings = ["One", "Two"];

function OnGUI () {
    // Determine which button is active, whether it was clicked this frame or not
    selectedToolbar = GUI.Toolbar (Rect (50, 10, Screen.width - 100, 30), selectedToolbar, toolbarStrings);

    // If the user clicked a new Toolbar button this frame, we'll process their input
    if (GUI.changed)
    {
        print ("The toolbar was clicked");

        if (selectedToolbar == 0)
        {
            print ("First button was clicked");
        }
        else
        {
            print ("Second button was clicked");
        }
    }
}

```

# Answer
OnGUI functions are called multiple times a frame. It's called once to do setup code for doing GUILayout stuff. It's called again to actually draw the frames, and it's called N additional times for (I think) each input event that might be relevant to the UI.

This is known as "Immediate Mode GUI", which you can read a bit more about here: http://iki.fi/sol/imgui/ (as well as other places if you look up that phrase, or "IMGUI").

http://unity3d.com/support/documentation/ScriptReference/MonoBehaviour.OnGUI.html

> OnGUI is called for rendering and handling GUI events.
>
> This means that your OnGUI implementation might be called several times per frame (one call per event). For more information on GUI events see the Event reference. If the MonoBehaviour's enabled property is set to false, OnGUI() will not be called.
> 6 votes

---
Tags: unity, performance, gui
---


title: Matrix for 2D perspective

text:
# Question
Title: Matrix for 2D perspective
I'm trying to determine whether what I'm attempting to achieve is even possible mathematically. I'm obviously not a seasoned game developer so I'm having trouble even coming up with the terminology to pose this question.

My 2D game (and I must stress that it is 2D) has a perspective such that the "camera" looks down at the game world from 45 degrees. Here's a rough sketch describing the look I'm trying to achieve:

As objects move from foreground to background (such as the red box pictured), they not only get smaller but are moved towards the center of the screen. So whilst the on-screen representation is rectangular, the actual game world has this shape:

Now I suspect I can do all this without using a matrix. I've already got the scaling working and don't think it would be too difficult to offset on the x axis objects according to their distance from the camera.

However, what I'd really like to know is whether I can encompass this perspective inside a simple matrix. I've had a look around the web but have got lost in a sea of nomenclature that I don't understand and information that doesn't appear to be relevant to me (such as 3D camera positioning, etcetera).

Can anyone tell me whether I'm barking up the wrong tree? If it is possible, can someone point me towards some articles or blog posts that describe this in detail?

# Answer
You are talking about doing manually something which is already done for you automatically by 3D APIs. One of the most basic functions of any 3D engine is to handle the transition from a bunch of objects in 3D space and a camera (naturally you must always have a camera) to a 2D picture (technically a projection) on the screen.

In your case, doubtless an object's representation moves more pixels per second going left or right than away from the camera, due to your angle (unless you deliberately have a fundamentally illogical physics model, like many such pseudo-3D games, and have those speeds be equal - not criticizing). This would be handled by what is known as the ***view matrix***, which looks at where objects are in the world and says where they should be on the screen.

If objects far away did not get smaller, and the road away from you looked straight if it was straight (ie did not appear to narrow due to perspective) you would have the familiar isometric game. To make far away things smaller, and a few other similar things, you apply what is known as a ***projection matrix*** which pretty much takes what the camera sees, and "distorts" to show how it would look if the camera had an arbitrary lens. An isometric game has no projection matrix and thus everything is... Well, isometric.

There is usually a third kind of matrix, a ***world matrix***, in 3D engines - because parts of 3D models are placed relative to the models origin, you need the world matrix for placing models in different points of your world. It's also like position and rotation (and scale, and skew if you have 4D matrices) of your object all in one handy mathematical entity.

So what you usually do is, you multiply (*matrix multiply*) these three matrices, and multiply the "model" (which is a bunch of points and polygons defined with respect to a model origin) in order to place a model's image on the screen. These matrices are not invariant, of course. For instance, the world matrix is generated depending on where your object moves.

I think isometric games are at the "2D threshold" - they are roughly the same amount of work Math-wise in 2D and 3D:

* You can make a "2D" isometric game with an identity matrix for a projection matrix, and put all sprites on billboards (in the computer graphics meaning) but you'll still have to muck about with a quite superfluous "camera" to create the 3D transformation matrices.
* You can make a 2D isometric game with sprite graphics, where you say directly where on the screen you want each sprite to be drawn (in the familiar x, y with regard to top left of the window fashion). But if you have, say an isometric RPG, and characters can jump, you'll still have to keep track of height and calculate the y coordinate accordingly, and if you don't do some trigonometry with sizes and speeds the game world will be very "strange" form a physics point of view.

However, once you do more 3D-stuff than a sprite-based isometric game would entail, as you are, I think it would be much less trouble to do everything in 3D, unless your goal is to make a 3D engine from scratch. As for your question, hopefully it is clear to you now that what you want to do can be done, it can be done easily, and it is routinely done by just about everyone out there who does 3D as a matter of course. To sum it up: Yes, it can be done, and it's fairly straightforward, but you shouldn't do it and would save yourself a lot of needless work if you just used a 3D engine.

For learning about linear algebra, you may find sources like the Khan Academy or the MIT lectures helpful. As someone who already knew linear algebra but had no idea how it applies to 3D graphics, I have found XNA and RB Whitaker's XNA tutorials very helpful and easy. They also explain using matrices for 3D like I did here, except better.
> 3 votes

# Answer
A matrix is one of many ways of storing an arbitrary transformation, but it happens to be a very simple way, since "apply the transformation to a point" is simply "multiply a vector by a matrix".

Fundamentally, you have several coordinate systems you are converting between:

1. 3D Object Space. This is the logical location of your objects.
2. 3D Camera Space / Eye Space. Camera space is that trapezoid (actually a frustum, since it extends up into the 3rd dimension as well) in your question. The Z coordinate is from the near side to the far side, the X coordinate maps from the left side to the right side, etc.
3. 3D Screen Space. This is taking the frustum of cameraspace and stretching it into a rectangular shape.
4. Pixel Coordinates on screen. This is pretty much the X and Y coordinates of screenspace, but offset so that the origin is at the top left instead of center, and the Y coordinate is probably flipped.

See http://www.songho.ca/opengl/gl\_transform.html for a good article that includes math and diagrams on the coordinate transformations.

some Pseudocode to get you headed in the right direction: You'll probably want to find an existing matrix math library for whatever platform you're using.

```
objCoords = x,y,z,1 = ... my objects location ....
eyeCoords = modelViewMatrix * objCoords
screenCoords = projectionMatrix * eyeCoords
screenCoords = screenCoords / screenCoords.W  // <- w is the perspective factor here
// at this point, screenCoords contains an X and Y
// you can work with in your 2D engine.

```
> 2 votes

---
Tags: 2d, mathematics, matrix, perspective
---


# Question
Title: Z rotation causing skew Android OpenGL ES 2.0
If I rotate about the X, or Y axis there is no skewing however for a pure 2D game that does not help me. When I try to rotate about the Z axis however the quad I am rendering for the sprite starts to skew until it disappears at 90 degrees appearing again shortly after a slowly resuming a quad shape. As far as I can tell I have written the code correctly, it is as I have written it before on 2D projects and it worked there I am either missing something stupid or OpenGL ES 2.0 does something different then what I expect, some excerpts of code follow:

Projection/View:

```
Matrix.setLookAtM(ViewMatrix, 0, 0, 0, 3, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
Matrix.orthoM(ProjectMatrix, 0, -width/2, width/2, -height/2, height/2, 0 , 100);

```

Rotation/Scale/Translation(For in place set to identity first):

```
Matrix.translateM(Translation, 0, x, y, 1.0f);
Matrix.setRotateM(Rotation, 0, angle += 0.05f, 0.0f, 0.0f, 1.0f);
Matrix.scaleM(Scale, 0, 64,64,1.0f);

```

Multiplication of Matrices:

```
Matrix.multiplyMM(MVPMatrix, 0, ProjectMatrix, 0, ViewMatrix, 0);
Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Translation,0);
Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Rotation, 0)
Matrix.multiplyMM(MVPMatrix, 0, MVPMatrix, 0, Scale, 0);

```

Thanks for any help.

# Answer
> 1 votes
The issue here was Matrix.multiplyMM, and using MVPMatrix as the output put and the input. In most all other libraries I used/made that would be correct. However looking closer at the specification for the function the api provided is undefined if any of the inputs or outputs overlap

---
Tags: android, graphics-programming, opengl-es2
---


title: Making Halo and Call Of Duty?

text:
# Question
Title: Making Halo and Call Of Duty?
I have never done any sort of game development in my life, the only time i have looked into it is with Cocos 2D for iPhone apps, i saw the effort involved just to get a half decent map game with one png character walking around. Could someone summarise the programming languages and graphic packages someone would use to make a game on the scale of something like Halo or Call of Duty!? I wouldnt even know where to begin...!?

EDIT:

Just to clarify i'm not even dreaming of making the next Call of Duty or Halo i was just curious about what goes into it!

# Answer
> 9 votes
In summary:

1. Spend tens, if not hundreds of thousands of dollars (if not more) buying the rights to use an existing game engine, songs and sounds for a sound track, and art assets.
2. Spend hundreds, if not thousands of man-hours developing a game using said engine, as well as developing music, sound and art assets not secured in point 1.
3. ????
4. Profit

In detail:

C++ using OpenGL is a popular choice for cross-platform stuff; C# and DirectX is a popular choice for games targeted specifically for windows or XBox platforms. PS3 and Wii have their own methodologies; I'm not familiar with PS3; but I know Wii is similar to GameCube; which in turn is similar to OpenGL. Most stuff outside of the sphere of "Microsoft Platforms Exclusively" is done in C++.

**Edit; to clarify:** What you really need with a project of that scale is a near-unlimited amount of man-hours to throw at it.

# Answer
> 7 votes
> Could someone summarise the programming languages and graphic packages someone would use to make a game on the scale of something like Halo or Call of Duty!?

One important thing to remember is that software development is not a production line where you feed stuff into a program or tool and get a game out of the other side. It's a constant construction and modification process where a team of people are continually adding more and more to the software and refining the behaviour until it finally does something close to what they hoped for. It's important to realise this because some people think that they could make these AAA games themselves if only they had the correct program for it - but the programs are only the tools. You still need the team of experienced and knowledgeable craftsmen to work those tools and there's no getting around that.

But, you asked about the tools. There are very few standard tools, which might be surprising:

* Microsoft Visual C++, or some other C++ compiler if the platform requires it. Programmers use this to write the game logic. I'm not going to claim that you *need* to use the C++ language to make a AAA game these days, but for the most part, that is what is chosen. Much of that is because the 'knowledgeable craftsmen' I mentioned above have this as their language of choice, but probably more of it is because the AAA development studios have a large body of existing C++ code that they need to reuse to have any chance of making large games in short timescales.
* Adobe Photoshop. This is pretty much the be-all and end-all of 2D graphics. There are other, more creative tools artists may use, but they'll probably still need Photoshop anyway.
* 3DS Max or Maya. These are advanced 3D modelling tools that allow you to construct characters, vehicles, environments, etc. Artists work with this to sculpt the visuals for the game.

Beyond that, you'll probably have a game engine. This is not necessarily an off-the-shelf piece of software like Unity, Unreal, or the latest Id Tech engine, but basically refers to whatever lump of code you have at your disposal that has been used to previously make a game and which can be re-purposed to make your future game. Often it's a bit of a hybrid, as you might have licensed some 3rd party code for certain features but written much of your own around it. If you haven't done a big game before, this is where you have to make some choices about what external code to bring in, otherwise you'll spend far too much of your time developing technology and not much on the actual game.

There are various bespoke tools that sometimes come with specific game engines, or which are developed in-house. Level editors, particle effect viewers, archive creation tools, conversation tree designers, etc etc. All depends on what sort of games you make, what engine you're using, and whether you got around to making these tools in the past or whether you just stuck with hand-editing text files...

If all this sounds sadly vague then unfortunately that is the nature of the beast. There is no magical tool to automatically make AAA games (although UDK and Unity are getting close!) but there is a lot of experience in doing it, and a lot of prior code used for the purpose. Today's massive games are built on the games of 5 years ago. And they were built on the games of 10 years ago. And so on. But the good news is that going from small games to big games is just a series of incremental steps - as you understand the procedures better, the route to the top becomes a lot clearer.

# Answer
> 3 votes
For **Call Of Duty**, it uses an OpenGL-engine powered by either C or C++. There are a number of free 3d engines available, but most AAA game companies either create their own or buy one, which is very, *very* expensive. Then you would have to hire coders to make the game unique, and hundreds of artists to make all the graphics. Don't forget about the story, multiplayer level designer, etc. Call Of Duty: Black Ops was produced in two years (with an already functioning engine) with about 250 employees working full time. If you think about it, you better have a lot of skill and a lot of money to make a game like that.

# Answer
> -5 votes
You can always use blender to make it. It will program it for you. The only programming you have to do is binding the things together. That uses like they said C#, C, or C++. If you want blender go to blender3d.org . Your welcome. You should see what people did in blender. You can deferentially make Halo or COD in it. If you don't want to do any work they have a *demo* that basically covers COD.

---
Tags: 3d
---


# Question
Title: Roguelike Class Structure Makes Everything Effectively Global
A brief rundown of the hierarchy of the game data objects:

Configuration - loaded from XML files, has Descriptors, among other things

Atlas - has a Configuration, has a CreatureInstance(represents the player's creature instance), is an associative array of AtlasColumns

AtlasColumn - has an Atlas(parent), is an associative array of AtlasCells

AtlasCell - has an AtlasColumn(parent), is an associative array of Layers

Layer - has an AtlasCell(parent), is an associative array of LayerColumns

LayerColumn - has a Layer(parent), is an associative array of LayerCells

LayerCell - has a LayerColumn(parent), has a CreatureInstance, a array of ItemInstances, and a TerrainInstance

CreatureInstance/ItemInstance/TerrainInstance - has a LayerCell(parent), has a Descriptor

Descriptor - has an associative array of properties needed by an instance to do its particular function

The most important thing in the Configuration are the Descriptors. A Descriptor has all of the properties that are needed by the various types of instances. It has properties that drive behavior, what it looks like on screen, and so on.

So here's the part that bothers me:

Everything... EVERYTHING, from Atlas to TerrainInstance can talk up and down the entire chain, the reason being that if, for example, the TerrainInstance is a square upon which a player steps and suddenly a number of monsters are conjured around him, the TerrainInstance needs to have access to the neighboring LayerCells. Or for another example if a CreatureInstance when attacking the player's CreatureInstance is able to take items from the player's inventory, and relocate them somewhere else in the dungeon, it needs access to a different Layer or AtlasCell in order to put the item where it needs to go.

An alternative that would appear to be "better encapsulated" might be a messaging system that sends little message objects up and down the chain and handles things at the appropriate level, but is that really any BETTER than just having the objects be aware of one another?

The game I'm writing started out with mostly hardcoded item and creature types, and gradually morphed its way into something similar to the more flexible roguelike framework that I've detailed above. I'm finally switching from C# to Java for it(the language is immaterial, however), and I'd like to not have missed something glaringly obvious that will cause great pains later when I need to refactor it.

So, the question: is the apparent lack of encapsulation within the data/business objects of the game demonstrate a fatal flaw in the architecture? And if so, what is that flaw and how can I correct it before I get too far along?

# Answer
> 9 votes
There's nothing wrong with objects knowing about other objects. That doesn't defy encapsulation.

However, I don't think anything is gained by having `CreatureInstance` actually store a reference to it's `LayerCell`. That's a needless coupling of data. It should have a "location" type, and `Atlas` should have a `FindCell` function that takes this location type.

> Or for another example if a CreatureInstance when attacking the player's CreatureInstance is able to take items from the player's inventory, and relocate them somewhere else in the dungeon, it needs access to a different Layer or AtlasCell in order to put the item where it needs to go.

What you're saying is that the `CreatureInstance` itself needs to directly do the following:

* Detect that it's attack hit the target.
* Look in the inventory of the target.
* Remove some items form it.
* Place those items in the world.

This is highly unnecessary. Why does the `CreatureInstance` have to do this? Yes, conceptually, it is the creature's attack that causes items to be removed. But why does the `CreatureInstance` object have to deal with that?

Here's how I would do it.

The `CreatureInstance` would have one or more `Attack`s. An `Attack` is an object that, when successful, can cause one or more effects. Effects include:

* Dealing damage, possibly with damage types.
* Removing items from the target and placing them on the map.
* etc.

All the `CreatureInstance` has to know is what `Attack`s it can perform and who it can perform them on. When it decides to use the `DrainItemsAttack`, it simply says, "I'm using `DrainItemsAttack` on this target."

The `DrainItemsAttack` would invoke the "RemoveAndDropItems" effect. That's not a class; that's a free function (or a static member of some class, since you're using languages that don't allow free functions). It doesn't have to have state, so it doesn't need to be a type. It's just a function that takes some number of inventory items from a `CreatureInstance` and places them on the ground.

It is *that* function which needs to be able to inspect inventory, remove items, find suitable terrain to place them on, etc. Each of these operations should be its own function. So your "RemoveAndDropItems" effect would be implemented like this (pseudo-code):

```
bool RemoveAndDropItems(int numToRemove, CreatureInstance target, Atlas world)
{
  for(numToRemove)
  {
    ItemInstance item = target.FindSuitableItemToRemove();
    if(!item)
      return false;
    target.RemoveItem(item);
    LayerCell loc = world.FindSuitableLocationToPlaceItem(item, target.loc());
    world.PlaceItem(item, loc);
  }
  return true;
}

```

This way, `CreatureInstance` isn't responsible for finding places to put stuff. You have functions for that. Nor does it have to have knowledge of `ItemInstance` or other types; that's all taken care of elsewhere.

# Answer
> 2 votes
I've been designing my roguelike framework on and off for the past few years and I come to think that the traditional OOP approach doesn't provide a very useful abstraction for a typical roguelike world for the reasons that you mentioned - everything is so interdependent on each other that each class may potentially need to know about every other class.

For example, AI routines should logically be a part of the Creature class, but AI potentially needs to know everything - the current dungeon map, the state of PC's quests, current World events etc. Even implementing simplest actions such as moving isn't straightforward: do you have a *Creature.move(x,y)* method and require every Creature object to know its current dungeon level, OR you have a *DungeonLevel.moveCreature(creature, x, y)* method? What if monsters in your game can move from one dungeon level to another - do you need an even higher level method, e.g. *World.moveCreature(creature, dungeonLevel, x, y)* ?

So in the end I decided to simply make most functions global, instead of agonizing over the correct location of each method in the class hierarchy, and use classes mostly as data structures. Now my Creature object doesn't have to link back to the parent object, and it contains only simplest code that doesn't need to be aware of other classes.

---
Tags: architecture, roguelikes
---