# Question
Title: How can I have my game engine track player history?
I'm in the very early stages of designing a browser-based text RPG. The project is basically just something I'm doing for fun and as a learning experience. I'm starting to wrap my head around the infrastructure of the game and I keep getting hung up on the best way to accomplish this.

If I have a map comprised of a grid with different items/monsters/quests/etc. in each 'tile', what's the best way to keep track of the areas on the grid where the player has been?

If the map is a grid of 1000x1000 squares, I want to know that in the player's entire gaming history, they have already visited squares A-1, F-6, GQ-46, etc. This list could be huge for each and every player.

Along the same lines, if I have quest-dependant events, how do I track the quests players have completed? Each player would need to have something letting the engine know if they have or have not completed potentially hundreds of quests.

My first idea was to save this information somehow in each player entry in the database, but that would mean a field for every one of the tiles in the 1000x1000 map. That doesn't seem like it would scale.

I'm just not sure how to store the info that lets the engine say "hey, I know that out of all the tiles on the map, this player has been on this particular one before." or "out of all the quests, this player has completed this particular one".

What is the best way to approach this?

# Answer
Since your map is a grid of fixed size and all you want is "has been visited", for the first part you can use a bit-map. For a 1024x1024 grid your storage size would be 128K and very fast to look up and small enough to keep in memory if you need super fast access (for fog of war rendering, or info overlays).

The quest info could be done two ways. It would be pretty easy to store them in a database and run queries as needed, and probably the best solution overall, @Dan Grossman

The other method would be to generate a hash from the quest information then simply store a list of hashes that the player has completed. Storage would grow dynamically, hash lookup at run time is very fast, and new quests could be added whenever you wanted.
> 4 votes

# Answer
A database seems like overkill. As @Patrick Hughes says, a bitmap is a great choice for map coverage plus 'fog of war' implementations. Bitmaps can also be used to track true/false conditions of game story. For example, you might have a list of ids or an enum that map to game events, like

```
enum GameEvents {
    VisitedTheTown = 1,
    KilledTheOgre,
    SavedThePrincess
}

```

Then you can do `BitMap.Set(GameEvents.KilledTheOgre);` when that action happens, and you can query for it later if some dialog tree depends on it. It's also efficient to store in your save game since it's only 1 bit for every yes/no game event state. You just don't want to be adding/removing items from the middle of your enum if you want different versions of your saves to be compatible.

Another approach is to use a data structure called a Blackboard. Implementation is up to you but it's often like a cross between a property bag and the Windows registry. You can store yes/no conditions like in a bitmap but you can also store strings or quantities (for the ever popular "Kill 10 kobolds" quest).

Here's a link:

http://aigamedev.com/open/article/static-blackboard/

And a book that mentions the subject:

AI Game Programming Wisdom
> 0 votes

# Answer
A database is an excellent tool for something like this, storing it in any other way would force you to (partially) recreate what a database already solves for you. As was mentioned by Dan in comments, using a relational table that maps the players id to the cell id that has been visited is a good solution. Databases are built for just this sort of thing and querying it for if a cell has been visited is a fast operation.

If database storage is costly for you (which it might be on a hosted solution) you can consider compressing the number of fields somewhat. In the case of "has this cell been visited" you would normally be forced to travel through the areas sequentially, so to get from A1 to A3 you would have to pass through A2 (or go a path around A2 depending on terrain).

You can use this fact by storing strips into the database instead of each cell individually, for instance (player, row, firstHorizontal, lastHorizontal), this way you can find out if a player has been in a cell by:

```
select * from VisitedAreas where player=@playerID and row=@row and firstHorizontal<=@column and lastHorizontal>=@column

```

The update method would be more complicated in this case however, you would have to look for a strip that is next to the current cell and if one is found, update either first or lastHorizontal field as appropriate, or if one isn't found you add a new strip where first and lastHorizontal is the current location.

Quests can be solved in a similar way, (playerID, questID, progress), progress can either be a foreign key to a "QuestSteps" table or you could go the oblivion/skyrim approach and store a number from 0 to 100 for every quest that maps to what you have done so far, for instance:

```
10 - accepted quest
11 - killed 1 goblin
12 - killed 2 goblins
15 - found the necklace in the chest
20 - returned necklace
30 - discovered the necklace wasn't the questgivers
40 - killed the questgiver and retrieved the necklace
100 - returned the necklace to the goblin owner

```

Again, if you wish to reduce the number of fields per player you can lump quests together by area, in many cases the player would probably finish all quests in a region before moving on to the next. In this case you can have a RegionCompleted (playerID, regionID), while a player is working on the quests in a region this is blank and you check the "QuestCompetions" (playerID, questID, progress) table for each individual quest, once all quest are completed however you add a row to the "RegionCompleted" table to mark this, and then remove the rows that correspond to that region from the "QuestCompletions".

Hope this helps.
> 0 votes

---
Tags: architecture, rpg
---


# Question
Title: How can I build and run Doom 3 from source in Windows?
I am trying to build and run Doom 3 from the open source release in order to better understand how the engine works. Unfortunately I am not able to run the game from the binary I built. I just get the console, but cannot run the actual game.

Here is what I did:

1. Downloaded the source code from the game repo
2. Downloaded and installed the DirectX SDK
3. Purchased, downloaded and installed Doom 3 from Steam
4. Open the solution in the new folder using VS2010 SP1
5. Built the project
6. Ran it

The doom solution by default on the debug settings sets the command line to refer to the default steam doom3 installation path. This is the default command line arguments used to run the project from vstudio.

+set fs\_basepath "C:\Program Files (x86)\Steam\steamapps\common\doom 3" +set com\_allowConsole 1 +set si\_pure 0

Doing that resulted in the console opening with the following log:

```
DOOM 1.3.1.1304 win-x86 Jan 23 2012 00:50:27
1596 MHz Intel CPU with MMX & SSE & SSE2 & SSE3 & HTT
8176 MB System Memory
0 MB Video Memory
Winsock Initialized
Found interface: {A3B0D223-3776-4D39-B7AD-9053DDB2E8D5} Broadcom NetLink (TM) Gigabit Ethernet - 0.0.0.0 NULL netmask - skipped
Found interface: {8FBA30BE-8F70-40B5-8C79-C32E8E1E74B8} Bluetooth Device (Personal Area Network) - 0.0.0.0 NULL netmask - skipped
Found interface: {80300E42-A240-45A3-97C5-261C0ED3B93B} Intel(R) WiFi Link 5300 AGN - 192.168.1.111/255.255.255.0
Sys_InitNetworking: adding loopback interface
doom using MMX & SSE & SSE2 & SSE3 for SIMD processing
enabled Flush-To-Zero mode
enabled Denormals-Are-Zero mode
------ Initializing File System ------
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game00.pk4 with checksum 0x29cdb978
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game01.pk4 with checksum 0x51c6981f
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game02.pk4 with checksum 0xf3ec6f7
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game03.pk4 with checksum 0x5d4230ea
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak000.pk4 with checksum 0x28d208f1
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak001.pk4 with checksum 0x40244be0
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak002.pk4 with checksum 0xc51ecdcd
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak003.pk4 with checksum 0xcd79d028
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak004.pk4 with checksum 0x765e4f8b
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak005.pk4 with checksum 0x8ffc3621
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak006.pk4 with checksum 0x95b65ab
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak007.pk4 with checksum 0x666bdb3c
Loaded pk4 C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak008.pk4 with checksum 0x23ae5993
Current search path:
C:\Program Files (x86)\Steam\steamapps\common\doom 3/base
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak008.pk4 (3 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak007.pk4 (38 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak006.pk4 (48 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak005.pk4 (63 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak004.pk4 (5137 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak003.pk4 (4676 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak002.pk4 (6120 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak001.pk4 (8972 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\pak000.pk4 (2698 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game03.pk4 (2 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game02.pk4 (2 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game01.pk4 (2 files)
C:\Program Files (x86)\Steam\steamapps\common\doom 3\base\game00.pk4 (2 files)
game DLL: 0x0 in pak: 0x0
Addon pk4s:
file system initialized.
--------------------------------------
----- Initializing Decls -----
------------------------------
------- Initializing renderSystem --------
using ARB renderSystem
renderSystem initialized.
--------------------------------------
5206 strings read from strings/english.lang
Couldn't open journal files
execing editor.cfg
execing default.cfg
execing DoomConfig.cfg
couldn't exec autoexec.cfg
5206 strings read from strings/english.lang
----- Initializing Sound System ------
sound system initialized.
--------------------------------------
game using MMX & SSE & SSE2 & SSE3 for SIMD processing
enabled Flush-To-Zero mode
enabled Denormals-Are-Zero mode
--------- Initializing Game ----------
gamename: baseDOOM-1
gamedate: Jan 23 2012
Initializing event system
...473 event definitions
Initializing class hierarchy
...142 classes, 191092 bytes for event callbacks
Initializing scripts
Compiled 'weapon_pistol::Raise': 3091.7 ms
---------- Compile stats ----------

Memory usage:
     Strings: 79, 9648 bytes
  Statements: 67875, 1357500 bytes
   Functions: 2109, 250532 bytes
   Variables: 147376 bytes
    Mem used: 2476344 bytes
 Static data: 2277552 bytes
   Allocated: 3281600 bytes
 Thread size: 7068 bytes

...6 aas types
game initialized.
--------------------------------------
-------- Initializing Session --------
WARNING: idChoiceWindow::InitVars: gui 'guis/mainmenu.gui' window 'SNDBPrimary' references undefined cvar 's_driver'
session initialized
--------------------------------------
--- Common Initialization Complete ---
------------- Warnings ---------------
during DOOM 3 initialization...
WARNING: idChoiceWindow::InitVars: gui 'guis/mainmenu.gui' window 'SNDBPrimary' references undefined cvar 's_driver'
1 warnings

Type 'help' for dedicated server info.

```

I don't know if the warning I am getting is the problem or if there is something else. Also, this is when the configuration being used is "Dedicated release", but I have also tried with "Dedicated Debug". It is my understanding that the "dedicated" versions don't use OpenAL but is there any other difference?

My main question is: How to just get this to run from source?

# Answer
> 8 votes
"Dedicated" in the configuration name refers to the game's dedicated multiplayer server. It's for sever operators exclusively, and runs an empty multiplayer server that exists solely to receive connections from other clients.

You don't want that. Run a configuration that starts with "Debug" or "Release" instead of "Dedicated."

---
Tags: c++, windows
---


# Question
Title: How can I implement projectile motion like Angry Birds?
> **Possible Duplicate:**
> Tracking Object Position - Firing on a Trajectory

I need help in implementing the projectile motion in my game as was implemented in Angry Birds.

Please help.

# Answer
> 2 votes
Projectile motion is just a function of gravity and velocity. At every tick, decrease your vertical velocity by `g` (the force of gravity), and then add `g` to your current height. If you're having trouble doing this, come back and ask another question with some of the code that you've tried.

For a more in depth look at the physics required in these sorts of games, Google around for some game development blogs or how-to's, or start with this one here.

# Answer
> 1 votes
Physics.

Specifically look at http://en.wikipedia.org/wiki/Hooke's\_law, http://en.wikipedia.org/wiki/Equations\_of\_motion and the application of a constant force of gravity.

Obviously if you're not sure about how to apply these things together, perhaps look at implementing a Physics engine.

# Answer
> 1 votes
Here is some code for doing exactly what your ask for...

http://developer.anscamobile.com/code/how-make-angry-birds-catapult

It's written in Lua and uses the Corona SDK. But I'm sure you could port it over to whatever platform you are working on.

# Answer
> 1 votes
Just read this tutorial(its a series so go through all of them): http://www.emanueleferonato.com/2011/11/03/develop-a-flash-game-like-angry-birds-using-box2d-predictive-trajectory-line/

# Answer
> 0 votes
You haven't told us what is the problem. Anyway, I guess you are asking how to do it. Here is a link.

Implementing the equations is not hard at all.

---
Tags: cocos2d-iphone, projectile-physics
---


# Question
Title: How can I convert the 3D Object designed in MAYA or 3D Max to OpenGL Object?
I'm try to convert the 3D Objects created in the Maya or 3D Max to Simple OpenGl object anyone please guide me how can I do so???

# Answer
> 2 votes
I think Assimp is what you are looking for( https://github.com/assimp/assimp ). There are some good tutorials out there if you head over to lighthouse3d ( http://www.lighthouse3d.com/cg-topics/code-samples/importing-3d-models-with-assimp/ ). It uses the new Core profile so it's as future safe as anything you will find. The tutorial is in C++ but it should be hard to port to C# if that's really what you want to use. Also, there is a C# wrapper of Assimp in the repo with it^\_^ Good Luck!

# Answer
> 0 votes
This is a pretty general question so this will be a pretty general answer. Don't think of it as exporting to OpenGL; instead you export from a 3D art tool to some file format and then write code to read that file format. So for example you can export to OBJ and then write code that reads in all the vertices from an OBJ file and puts that data into arrays for using with OpenGL.

You can find file format descriptions for most of the commonly used 3D file formats. For example, here's an explanation of OBJ file format: http://www.cs.clemson.edu/~dhouse/courses/405/docs/brief-obj-file-format.html

---
Tags: c++, opengl, c#
---


# Question
Title: Should collision detection be done server-side or cooperatively between client/server?
I am working on an online game that will have very heavy collision detection processing. Player models will collide with other players, mobs, structures, terrain, and solid objects that only exist server side (not stored in client data files).

For security purposes, should I do all collision detection server-side? Or should I have the client do the detection and have the server follow up on it somehow? I feel like it will be too much for the server to do by itself (I am designing the engine for hundreds of players on one server).

Does anyone know how mainstream MMOs do it? I know that almost all MMOs right now are susceptible to physics hacks and usually deal with them by detecting hacks and banning people. I would rather the hacks did not work at all, at least for the physics component.

# Answer
> 22 votes
It seems like the obvious answer is to do most of your detection client-side (for smoothness), and then you interpolate to what the server says if your client is too far off. The server will tick at a less frequent rate than the client (like, say, 10hz), and would probably need to have some basic "can this player have reached where he says he currently is from his last known location" code, which implies some kind of nav mesh-type solution and pathfinding.

That might be prohibitively slow depending on what your needs are. You might make a design decision, for example, to not care about player-player collision on the server. Most games, as far as I know, don't even care about that on the client. It really depends on what your needs are.

But the rule of thumb is that you should never trust the client. It if impacts gameplay, you have to at least verify it on the server.

# Answer
> 27 votes
So, a few answers here.

* Client-side collision is ideal from a performance point of view and from a player feel point of view. You don't want collision to be laggy, you want players to run into a solid object and stop. If you do it server-side, you're either looking at rubberbanding players all over the place or giving players noticable lag when they try to move. Bad mojo, in both cases.
* Server-side collision is ideal from a security point of view. The closer your clients get to "dumb terminals", the less exploitable your game is. There's a reason that nobody playing a text-based MUD has to worry about wallhacks or speedhacks - it's because the client isn't doing anything worth mentioning.
* Doing *both* is "ideal" in almost every case. Let the clients do their thing, then doublecheck on the server to make sure people aren't cheating. The downsides are complexity, synchronization (what exactly *do* you do if the two disagree), and sheer server CPU usage.
* What I recommend is to do it almost entirely client-side. The client is authoritative about its position, just like in a full client-side system, and does all its own processing. On top of that, you randomly have the server check various players once in a while. Keep the server load low, but this will root out cheaters surprisingly fast.

Alternatively, do it client-side for now, add the server-side verification at some point in the future if your game gets popular enough that people are cheating in it. Which, let's be honest, it probably won't, so there's no point in spending the coder time on it right now.

# Answer
> 3 votes
World of Warcraft doesn't do collision detection between players/mobs. There may or may not be technical reasons behind this decision, but really, this has to be more of a game design decision than a technical decision:

Imagine how exploitable it could be in player-vs-player situations. Or how hard it would be to use the bank/auction house/mailboxes if other (often idle) players blocked your movement!

As for client vs server based collision detection - really, unless movement is very slow, it has to be primarily client-side, so it looks right to each client. Laggy/delayed collision response, and/or colliding with 'invisible' objects would be quite unpleasant.

# Answer
> 2 votes
If you are concerned about the hacks and that has big impact in the game play then the answer is YES.

In my browser based game which is a "city building" kind of game, I am not bothered about the hacks because the client engine is not going to fail when I layout the saved game state.

However it could potentially abuse the gameplay as the player needs to spend game coins (or premium cash) to expand the playable area in order to build more houses/buildings. So, I am going to implement a simple check of number of tiles occupied by the newly added building agains how many free tiles are available.

---
Tags: c++, collision-detection, mmo, server
---


# Question
Title: How do I make "weaponsclash" = animations adapating to parameters
Meaning: how do I build my animations/system so that I can have swords blocking each other? I honestly believe this is the hardest part of a game: I need animations to interact with each other. If a monster uses attack 1 on hero 2, then both NPCs have to play a different animation based on,

A, How big these NPCs are. I need them to be able to be scaled (monsters can grow, but when it jumps on a small player, it still has to look just as fitting as with other sizes) B, Speed of the monster when it runs up for the attack. C, Countless other things I suppose.

How do I achieve this? KI, Pathfinding... all that is meaningless unless I can build a believable combat system.

# Answer
> 3 votes
The most common method is to not bother. Just use generic animations like most MMOs. One guy makes an attack, the other guy makes a blocking animation. Damage is dealt, numbers appear, everyone is happy.

Now, if you actually give a damn about how your game looks, you need to expend effort.

The idea is fairly simple. To coordinate animations between entities, you need to... coordinate animations between entities. The two entities need to talk to each other and work out which animations each of them will play.

One entity should probably be the "leader" in terms of who's in charge. It dictates when things will happen and how they will occur. Let's say the attacking entity is always the lead.

The attacker informs the defender that he's being attacked. So now the attacker references the defender and vice-versa.

Next, both must select which animation to play. This is generally done by a table or something similar based on the available parameters. For each possible set of parameters that affects which animation to play, you have an entry in the table that says which to play. So you'd have ranges of enemy sizes, self-sizes, ranges of distances to the target, etc.

The attacker and defender play a different animation obviously. But the tables they select from are designed to match: given the same attacker size, defender size, and distance, the attacking animation selected will match the defender's animation selection.

Then they play their animations. Note that timing may need to be involved here. Especially if distance is involved, you generally don't want the defender to be defending until the attacker is close enough. So he won't play his animation until the attacker reaches a certain distance. This requires the defending entity to track the position of the attacker and play the animation at the right time.

Your biggest problem (and the reason why most games punt on it and use generic anims) is likely going to be what happens when a third entity gets involved. If you're already in the middle of a lengthy scripted sequence, what do you do if someone else tries to attack you?

This is generally not a good thing. So oftentimes, you simply say that nobody can attack someone who is attacking/defending currently. In some games, elaborate animations are only used for specialized events. Generic animations are for basic fighting, but you might have a special anim for the final blow.

---
Tags: animation
---


# Question
Title: What technique should I use for the AI for Go?
I am currently undertaking a project where I need to program AI for Go (the Asian strategy game) and I would like to know, how do I start? I am aware of the many approaches to AI for their applications to Go, such as the neural network, machine learning (supervised learning, etc), the Monte-Carlos method, or knowledge based AI. I am more interested in machine learning however I am short on time as I have about two months to complete it.

I am also considering minimax and alpha-beta pruning with brute force as a compromise in case I don't have enough time to do anything else. I am fully aware that it is not the best way to go about this but if I am short on time then I have no other choice.

# Answer
> 4 votes
AI for GO and Chess is strangely much harder to code than AI for a 1st person shooter for example, mostly because the games are pure strategy and take a remarkable amount of intelligence to play well.

This may not be the answer you are looking for, but I would suggest doing a search in online university library databases such as JSTOR etc, for people that have done dissertations on the subject. Learn from then and try and emulate what they have done at first.

I would also strongly suggest you download a framework for coding GO AI that someone else has made, rather than taking time doing this yourself. I feel pretty certain that such a thing must exist.

ah, here we go (I googled 'japanese "GO" AI framework')

http://www.gnu.org/software/gnugo/free\_go\_software.html

that search also threw up a number of pdf dissertations on the subject. Good luck!

# Answer
> 2 votes
Minimax with alpha-beta pruning is a good start. Then, try to define a search heuristic. This heuristic decides which position to explore during minimax expansion. For example, it can search the "risky" positions before the "safe" ones (fuzzy logic can be used here).

For the machine learning exercise you can define a linear evaluation function for positions, and let your agent learn the best weights.

---
Tags: ai
---


# Question
Title: How can I alleviate network lag issues with players from other countries?
I am developing a small multiplayer game where players move through the map and interact with each other. The game is written in VB.Net.

When I tested my game with players on a LAN everything worked pretty smoothly. Testing it on the internet with players from the same country worked pretty well, without lag, also. The problem is when players from other countries try to connect to the game: they can connect and play but the game is very laggy for them.

What should I do to fix the lag?

# Answer
> 12 votes
I'll rather delve into the problem you are having with network latency: *it's unavoidable*. Network programming is a fine art and much more psychologically involved than tricking the eye (as you do with graphics programming); people are very sensitive to their perception of time.

What you essentially need to do is do prediction on the client. For example, in a strategy game this is the naive way of doing things:

1. The user selects a unit and issues a move command to some place.
2. The command is packaged up and sent to the server.
3. *Some times passes as the server gets the command and starts sending back the 'update position' commands.*
4. The unit starts moving.

Typically if you are connecting from a separate country you can expect latencies of up to 400ms, or 600ms if your connection is bad (and even over 1s if you are using TCP and the packet loss is high enough - which it probably will be). Anything over 30ms can be perceived from the average user's perspective - so you are fighting a losing battle. To further compound the issue latency can vary/change (and as the average latency get higher so does the variance) - for example at 180ms I often get about 20ms variance on a premium priority account: this means that a packet takes between 170ms and 190ms to travel from South Africa to Europe *on the most stable bandwidth available here*. (This is also called 'jitter').

Jitter and latency are two defining characteristics when talking about lag. Most people see them as the same thing; when in actuality they have different outcomes: latency delays the outcomes of your commands, jitter makes things move forwards and backwards or erratically.

We compensate for this using two strategies at the same time: client prediction (solves average latency) and interpolation (solved latency variance). Both of these are described in depth on a large amount of websites, so I will only briefly touch over them here.

**Client Prediction**

Essentially what the client does here is it anticipates what the server might be sending it at some point in the future. You basically need to resolve the difference in time between the server and the client: in 180ms I will receive a packet from the server telling me where this unit is, but in reality it's actually sending that packet right now - so I will chance a guess and move the unit to where I think the server will say it will be given its velocity, acceleration and sometime even information about the controller (mouse, keyboard, game pad) of the person controlling that unit.

**Interpolation**

This is when the client says, "OK, I am getting irregular updates from the server even though it is sending them at regular intervals". What we do here is instead of updating the unit to where the server says it is each time: introduce delays between updates from the server and let the client figure out where the unit is in between those delays. To do this we use a very simple function called 'lerp'.

**Fine Art**

The fine art comes in when you need to trick the user and make them believe that things are happening as they do them (where in reality that signal takes time to reach the server). For example in the case of the 'move command' above what we could do instead is:

1. The user selects a unit and issues a move command to some place.
2. The command is packaged up and sent to the server.
3. The client starts moving the unit.
4. *Some times passes as the server gets the command and starts sending back the 'update position' commands.*
5. The client starts receiving the position of the unit and over a duration of time (possibly one second) gradually moves from its prediction to what the server will be saying further down the line (depending on the current latency) - once again you would use a lerp here. Furthermore ensure that you smooth (a moving average of the latency might work nicely) the latency so that the unit doesn't jump around.

This way as soon as the user issues the command they see a result - the lerp helps us gradually move to actuality and the smoothing ensure that the unit doesn't jump forwards and backwards due to variance (hopefully just slow down and speed up in a way the user can't notice).

Some resources:

# Answer
> 3 votes
MySQL (in general, any SQL) is not the best choice for storing your live data. But I doubt that's your problem currently.

It seems like your issue is that your game doesn't work with people connecting from outside the country due to the high latency. Possibly your networking code is embedded in your game loop somewhere, so a high latency network call is slowing down the rest of the game

Example of embedded network send anti-pattern:

```
while(true) { // MAIN GAME LOOP
    GetPlayerInput();
    GetDataFromServer(); // <-- this is a blocking call
    RunGameLogic();
    SendDataToServer();  // <-- this is another blocking call
    Render();
}

```

You need to decouple your networking logic from your main event loop so that the latency doesn't affect the rest of the loop.

One quick way to fix it is to move the networking code to a different thread, and have it interface with the main loop through an event queue. Another way would be to convert to asynchronous calls or Socket.Poll.

---

> crux of the question was basically like: if I will learn how to use sockets and make server/client comunication does my game will still lag for Foreign players.

No, if written correctly. The only "lag" they should experience is that events happen later for them, but the game should not run slower overall.

---
Tags: multiplayer, client-server, lag
---


# Question
Title: How can I map thumbsticks to cardinal directions?
I've got a tile based game that has notions of moving up, down, left, right and the diagonals (by alternating horizontal/vertical movement).

I've found that if I use the default `ThumbStick<Direction>` buttons that XNA provides I'm often moving diagonally instead of in a straight line. E.g. moving the thumbstick left, often just triggers 'down' too (but only just).

How can I map moving a thumbstick to the 8 discrete directions so this accidental diagonal movement doesn't occur?

I'm starting to think about favouring up/down/left/right over diagonals (as you more frequently move straight in my game), however, I'm not sure how do put this into code.

# Answer
> 3 votes
That's because you're probably taking any value != 0 as a "direction trigger". For example, if the thumbstick is 99% to the left and 1% to the bottom, it will trigger both.

Try to use a 15% (or some other value that you feel good with) as a threshold.

# Answer
> 14 votes
## Distance-Based

You will basically need to take two things into consideration: a threshold (inversely a deadzone) and the dominant vector. Given an `enum` like the following:

```
public enum Direction { None, Up, Down, Left, Right }

```

You would find the dominant direction (if the deadzone isn't in play) and use that.

```
// You could make this user-configurable.
const float Deadzone = 0.8f;
const float DiagonalAvoidance = 0.2f;

public static Direction GetDirection(Vector2 gamepadThumbStick)
{
    // Get the length and prevent something from happening
    // if it's in our deadzone.
    var length = gamepadThumbStick.Length();
    if (length < Deadzone)
        return Direction.None;

    var absX = Math.Abs(gamepadThumbStick.X);
    var absY = Math.Abs(gamepadThumbStick.Y);
    var absDiff = Math.Abs(absX - absY);

    // We don't like values that are too close to each other
    // i.e. borderline diagonal.
    if (absDiff < length * DiagonalAvoidance)
        return Direction.None;

    if (absX > absY)
    {
        if (gamepadThumbStick.X > 0)
            return Direction.Right;
        else
            return Direction.Left;
    }
    else
    {
        if (gamepadThumbStick.Y > 0)
            return Direction.Down;
        else
            return Direction.Up;
    }
}

```

## Angle-Based

With this one you basically ensure that, once again, we don't fall within a deadzone - but also that the angle is within certain ranges.

```
const float PI = (float)Math.PI;

// You could make this user-configurable.
const float Deadzone = 0.8f;
const float AliveAngle = PI / 4 - (PI / 16);

// Remember PI = 180 degrees
const float AliveAngle1Start = PI * 0;
const float AliveAngle1End = PI * 0.5f - AliveAngle;

const float AliveAngle2Start = PI * 0.5f + AliveAngle;
const float AliveAngle2End = PI * 1f - AliveAngle;

const float AliveAngle3Start = PI * 1f + AliveAngle;
const float AliveAngle3End = PI * 1.5f - AliveAngle;

const float AliveAngle4Start = PI * 1.5f + AliveAngle;
const float AliveAngle4End = PI * 2f - AliveAngle;

public static Direction GetDirection(Vector2 gamepadThumbStick)
{
    // Get the length and prevent something from happening
    // if it's in our deadzone.
    var length = gamepadThumbStick.Length();
    if (length < Deadzone)
        return Direction.None;

    // Find the angle that the stick is at. see: http://en.wikipedia.org/wiki/File:Atan2_60.svg
    var angle = (float)Math.Atan2(gamepadThumbStick.Y, gamepadThumbStick.X);
    if (angle < 0)
        angle += PI * 2; // Simpify our checks.

    if (angle > AliveAngle4End)
        return Direction.Right;
    if (angle > AliveAngle4Start)
        return Direction.None;
    if (angle > AliveAngle3End)
        return Direction.Up;
    if (angle > AliveAngle3Start)
        return Direction.None;
    if (angle > AliveAngle2End)
        return Direction.Left;
    if (angle > AliveAngle2Start)
        return Direction.None;
    if (angle > AliveAngle1End)
        return Direction.Down;
    if (angle > AliveAngle1Start)
        return Direction.None;
    return Direction.Right;
}

// Inlined in release so don't worry about it.
private static bool IsBetween(float value, float start, float end)
{
    return value > start && value < end;
}

```

## Remarks

The way I did the distance-based one would likely emulate the (possibly more expensive) angle-based one - this is because of the `absDiff < length * DiagonalAvoidance`. Either way experiment with them and see which you like best.

---
Tags: xna, c#, input, controllers, xbox-controller
---


title: Cocos2D: TileMap performance question

text:
# Question
Title: Cocos2D: TileMap performance question
I´ve got a question regarding TileMaps. Each level in my game is going to be determined by the length of the tile map. I would like to create a map that will be about 5 mins (in length) long. I want to add depth to my map so I will be making individual layers to create that depth illusion via ParallaxNode. Each independent layer is going to be scrolling automatically at different speeds however the ground layer is going to be scrolling the fastest thus increasing its length being a map that long and the ground layer being longer. Will that bring performance in my game to it's knees?

# Answer
> 1 votes
Yes, that should be fine for your needs. Simple all you are doing would be some form of parallax scrolling methods alongside your basic tile-map with X amount of layers. Unlikely to cause you any issues on its own. Really it will depend on what else you have going on, usually things like physics, any other render intensive calls and how many enemies you will have in your game. Like eBusiness said, testing is key to your performance, in regards you should every now and again when you've implemented something new look at "stress testing". How many of X can i have along with X & X before i start losing performance?

Really quite simple things, so shouldn't be too hard. As for simple optimization, remember to:

1. Only render what is on-screen and can be seen by the player. Which with the iDevice screens won't be that much at all. Your'll probably need to add a simple offset of + 1 to this, as otherwise the player can see the edge tiles being drawn on-screen.
2. Only render tiles that contain items, you don't want unnecessary draw calls rendering blank tiles.

Hope that answers your question.

# Answer
> 2 votes
There is nothing to suggest that this should be problematic, the feature is certainly within the capabilities of an iPhone.

However, as always with regards to performance, testing is key. Whenever you are in doubt, implement as much as is needed to make a benchmark.

---
Tags: cocos2d-iphone, cocos2d, tilemap
---


# Question
Title: Can using different vertex-buffers for each vertex-attributes be good in certain scenarios?
Is there scenarios where this is actually good practice? Or does it slow down performance?

Example:

```
//Vertex format is:
//X, Y, U, V
var myXYs:Vector.<Number> = new <Number>[
  -1, -1,
  1, -1,
  1, 1,
  -1, 1
];

var myUVs:Vector.<Number> = new <Number>[
  0, 0,
  1, 0,
  1, 1,
  0, 1
]

//Create actual VertexBuffers....
// ...yaddiyaddiyadda...

//Set context3d's vertex-attributes:
//Assign 'va0':
context3D.setVertexBufferAt(0, bufferXY, 0, Context3DVertexBufferFormat.FLOAT_2);
//Assign 'va1':
context3D.setVertexBufferAt(1, bufferUV, 0, Context3DVertexBufferFormat.FLOAT_2);

```

Would the GPU have to constantly internally 'swap' between bufferXY and bufferUV to process the vertex-data? Or does it handle it just as good as a single vertex-buffer?

**NOTE:** My goal is to figure out a way to minimize uploading data from CPU to GPU for a large number of objects (more than the 128 limit with vertex-constants **in Stage3D**) by manipulating a list of vertices only responsible for the position of objects rather than the entire geometry + color and/or UV coordinates.

# Answer
If you're fetching all the vertex attributes in the shader, then in general attributes in multiple streams *may* be slower than all attributes in one stream, due to the loss of cache locality. However, using multiple streams can still be a good idea in some cases, such as:

1. Some passes only need to read a few of the attributes. For example, drawing the object into the shadow map usually only needs positions and is vertex bound, so it can be a win to have the positions set aside in their own stream.
2. Some attributes are static and some are dynamic. This sounds like your proposed solution. You may be able to save bandwidth overall by keeping the static attributes and the dynamic ones in separate vertex buffers so you only need to update the dynamic ones.
3. Instancing, where the inner and outer attributes must be in separate streams. This is probably what you *should* be doing if you're rendering many copies of an object, since it lets you have an outer vertex buffer with one entry per *object* and an inner vertex buffer with the the vertices for one copy of the object.

In any of these cases the slowdown due to fetching from multiple streams (which may be slight) can be offset by the reduced use of bandwidth overall. As always, the golden rule is to profile it. YMMV, as these things are very dependent on hardware and on details of your shaders and scenes. Measure the performance and see what's fastest for your case.
> 6 votes

---
Tags: flash, rendering, performance, gpu, vertex
---


title: Collision 100% avoidance implementation

text:
# Question
Title: Collision 100% avoidance implementation
I'm an absolute beginner with game development and all I know about collision avoidance/resolution, I learnt it *on* or *through* this site in the past week... so don't hesitate to correct me if what I'm asking here is based on wrong assumptions / misunderstanding. I tried of my best to be clear, but that said, the subject is still novel to me.

## Vehicles

In my game, I have vehicles that move autonomously. They are placed in a 3D space, and their motion is governed by a number of variables which are different for each vehicles. The one of interest here are primarily:

* Only *forward* motion.
* A *speed* that can vary between min & max, but whose min is **not** (even close to) zero.
* A *steering radius* that is dependent from the speed (the higher speed, the larger radius)
* Two *maximum accelerations* (for decreasing and increasing speed)

## Goal

My goal is to implement some sort of AI that will a **100% accurate collision avoidance** (i.e. I will be sure that the vehicles will **never ever** collide).

## Design

* Although **I would prefer more the idea of having the AI "onboard"** (i.e. each vehicle having it's own "collision avoidance AI", eventually querying and/or sending messages to other vehicles) it is also possible for me to implement the CA AI at a central level (dispatching commands to the vehicles).
* In most of the cases, the vehicle will simply have to steer clear of each other in any direction, but under certain circumstances, they will have to avoid collision **and going towards the same target**

## What I found so far and where I got stuck

Within the many many links I found in other questions on this very site, I found of particular use these ones:

1. Collision between pool balls
2. Unalligned collision avoidance
3. Queuing

While these three links "opened my eyes" in many ways, it is not immediately clear to me how to use that information in my case. In particular article #2 only "tries" to prevent collision (but collisions do happens time to time). While article #3 needs to stop vehicles sometimes to prevent collisions.

What I also noticed, is that the collision avoidance algorithms linked above use a **"instant projection" of linear speed** to check if something is on the way of the vehicle. I was wondering if this is enough in my case or if I had to project my position in a more realistic way (e.g.: If I am 60° into a steering 90° to the right, I should calculate my position for the rest of the 30° of the curve, and then assuming linear motion).

Finally, I am particularly **afraid of deadlocks**. In other words: although the density of vehicles in the world will be fairly low, I am worried that given a certain numbers of vehicles converging towards the same point, once they will realise they are on a collision course, any evasive manoeuvres will be impossible as it would bring the vehicle on a collision path with some other ones.

## Question

**How can I reach my "goal"?** An in depth-explanation is of course very much appreciated, but links to external resources would also be of great help (I'm sure I'm not the first with this problem, but probably I used the wrong keywords to search the web?)

Thank you in advance for your help!

# Answer
Have you looked into **flocking algorithms**? When I look at your description that's what comes to mind for me. There's lots of articles around for this, here's one I like. Likely you won't be using all the aspects of flocking, like cohesion. Most of the aspects would be useful for what you're trying to do, like alignment and separation, both of which would help in avoiding collisions. You'd end up with something a bit different than flocking, but it should help you get started.

Good luck!
> 5 votes

# Answer
Here is an approach: Every vehicle has a short projected path where the vehicle in the end slows down and enters a loop, these paths may not overlap. Whenever a vehicle comes to the point where it is set to slow down you try to generate a new path that does not overlap any of the existing. If that is not found to be possible the vehicle continues on it's given path and retries making a new path periodically.

The method could be improved to allow tighter traffic by letting paths leading to loops overlap each other and loops where it can be determined that this will not cause a collision.
> 3 votes

# Answer
Have a method in each vehicle where it performs a radial search around itself, if there are any other vehicles inside this radius, move away in a fashion suitable to your liking: 1) Move in the opposite vector, 2) slow down, 3) speed up, etc.

You can even do combinations: If the other vehicle's vector is not straight ahead or directly behind: move away; else if it is straight ahead: slow down; else: speed up.
> 0 votes

# Answer
> My goal is to implement some sort of AI that will a 100% accurate collision avoidance (i.e. I will be sure that the vehicles will never ever collide).

If this were possible, it would have been put into all the world's aircraft by now.

I suggest relaxing the 'autonomous' aspect and having a function that resolves predicted collisions between 2 (or more) vehicles. It can be as naive as picking random new directions to travel in and seeing if that resolves the problem, but the important thing is that the function only returns when it's reached an agreement that suits both vehicles.

I also suggest that any vehicle that is predicted to collide in the near future reduces its speed while maintaining the same look-ahead distance - this will give your vehicles more opportunity to avoid collisions, just as in real life.
> 0 votes

# Answer
It sounds to me that *crowd simulation* might be the topic most relevant to what you're trying to achieve. The GAMMA group at UNC has a large body of work on the subject that might be worth looking through. Their description:

> Crowd and multi-agent simulation is the process of simulating large numbers of people, creatures, or other characters, each interacting in one environment. These actors are expected to move to their goals, interact with their environment, and respond to each other. Crowd simulations have many uses, including improving architectural planning, enhancing training environments and virtual realties, and **driving artificially-intelligent (AI) characters in games** and movies. Our group has worked on many problems in crowd simulation, **including fast, guaranteed, collision avoidance, real-time path and motion planning,** crowd flows, and directed behaviors.

http://gamma.cs.unc.edu/research/crowds/
> 0 votes

# Answer
I don't think there is a 100% avoidance method, but if you vehicles possess full world informations, you could encase each vehicle into a box whose length depend on its speed, and perform collision check on those boxes. If there is indeed a collision, steer away, with a strength depending on the imminence of impact (or area of the collision between the two boxes), and slow dow (but keep your box the same length during the avoidance operation).

Obviously this won't work if the vehicles does not posses full informations, but in this case nothing will garanty a 100% avoidance (except, as already said, parallel movement)

some methods described here would probably be useful, notably this one :Unaligned Collision Avoidance steering behavior

regards
> -1 votes

---
Tags: collision-detection, ai
---


# Question
Title: How important do you find exception safety to be in your C++ code?
Every time I consider making my code strongly exception safe, I justify not doing it because it would be so time consuming. Consider this relatively simple snippet:

```
Level::Entity* entity = new Level::Entity();
entity->id = GetNextId();
entity->AddComponent(new Component::Position(x, y));
entity->AddComponent(new Component::Movement());
entity->AddComponent(new Component::Render());
allEntities.push_back(entity); // std::vector
entityById[entity->id] = entity; // std::map
return entity;

```

To implement a basic exception guarantee, I could use a scoped pointer on the `new` calls. This would prevent memory leaks if any of the calls were to throw an exception.

However, let's say I want to implement a strong exception guarantee. At the least, I would need to implement a shared pointer for my containers (I'm not using Boost), a nothrow `Entity::Swap` for adding the components atomically, and some sort of idiom for atomically adding to both the `Vector` and `Map`. Not only would these be time consuming to implement, but they would be expensive since it involves a lot more copying than the exception unsafe solution.

Ultimately, it feels to me like that time spent doing all of that wouldn't be justified just so that the a simple `CreateEntity` function is strongly exception safe. I probably just want the game to display an error and close at that point anyway.

How far do you take this in your own game projects? Is it generally acceptable to write exception unsafe code for a program that can just crash when there is an exception?

# Answer
If you're going to use exceptions (which isn't to say you should, there are pros and cons to that approach that are outside the specific scope of this question), you should write properly exception safe code.

Code that does not use exceptions and is explicitly not exception safe is better than code that uses them but is half-assing its exception safety. If you have the latter case, you have a whole class of bugs and failures that can occur when an exception happens that you probably cannot recover from at all, rendering one of the benefits of exceptions entirely null and void. Even if its a relatively rare class of failure, it's still possible.

This isn't to say that if you use exceptions, all code must provide the strong exception guarantee -- just that each piece of code should provide a guarantee of some sort (none, basic, strong) so that in the consumption of that code you know which guarantees you the consumer can provide. Generally the lower-level the component in question, the stronger the guarantee should be.

If you're never going to provide a strong guarantee or never going to really embrace the exception handling paradigms and all the extra work and disadvantages that implies, you also won't really be getting all the advantages it implies and you might have an easier time just forgoing exceptions altogether.
> 26 votes

# Answer
My general rule of thumb: If you need to use exceptions, use exceptions. If you don't need to use exceptions, don't use exceptions. If you don't know whether or not you need to use exceptions, you don't need to use exceptions.

Exceptions are there to be your absolute last line of defence in always-on mission-critical applications. If you're writing air traffic control software that absolutely cannot ever fail, use exceptions. If you're writing control code for a nuclear power plant, use exceptions.

When developing a game, on the other hand, you're much better off following the mantra: Crash early, crash loudly. If there's a problem, you really want to know about it as soon as possible; you don't ever want errors to be invisibly 'handled', because this will often conceal the actual cause of later misbehaviours and make debugging much more difficult than it needs to be.
> 14 votes

# Answer
The problem with exceptions is you have to deal with them anyway. If you getting an exception because your out of memory then it might be possible that you will be unable to handle that error anyway. Might as well just dump the entire game in 1 giant exception handler that pops up an error box.

For game development I prefer to try and find ways to make my code graciously continue with failures when possible.

For example I will hard code a special ERROR mesh into my game. It's a rotating red circle with a white X on it and a white border. Depending on the game an invisible one might be better. It has one singleton instance initialized on start. Since it's baked into the code rather than using any external files it shouldn't be possible to fail.

In the event a normal loadMesh call fails instead of throwing back some error and crashing to desktop it will silently log the failure to the console/logfile and return the hardcoded error mesh. I found out that Skyrim actually does the same thing when a mod screwed things up. There's a good possibility that the player wont even see the error mesh (unless there's some major problem and many of them are like it).

There's a fallback shader too. One that does basic vertex matrix operations but if there no uniform matrix for some reason it should still do the orthogonal view. It has no proper shading/lighting/materials (although it does have a color\_overide flag so I can use it with my error mesh).

The only possible issue is if the error mesh version might permanently break the game in some way. For example ensure that it doesn't apply physics since if the player loads an area, then the error mesh kicks in it might fall to the floor then if they reload the game this time with the correct mesh working, if it's bigger it might be embedded in the ground. That shouldn't be too hard since your probably going to store your physics meshes with your graphical ones. Scripting might also be a problem. With some stuff you will just have to hard die. Not really sure what use a fall back 'level' would be (although you could make a small room with a sign saying there was a error, just make sure the save is disabled since you don't want the player stuck in it). Instances of fall back objects/components would be more problematic since they need to be unique but you can still have a special position that sets things to (0.0, 0.0, 0.0) or (-1000000.0, -1000000.0, -1000000.0) but once again you have to ensure it wont be saved or anything.

In the case of 'new', for game development it might be better to look at using some kind of a factory. It can give you various other advantages like preallocating objects before you actually need them and/or making them in bulk. It also makes it easier to make things like a global index of objects that you can use for memory management, finding things by an id, (although you can do that in constructors too). And of course you can handle allocation errors there too.
> 5 votes

# Answer
The big thing about missing runtime checks and crashes is the potential for a hacker to use a crash to take over the process and perhaps subsequently the machine.

Now, a hacker can't exploit an actual crash, as soon as the crash happens the process is useless and harmless. If you simply read from a null pointer it is a clean crash, you make a mistake and the process die instantly.

The danger comes when you execute a command that is not technically illegal, but wasn't what you intended to do, then a hacker might be able to direct that action using carefully crafted data that should otherwise be safe.

An uncaught exception isn't actually a real crash, it is just a way to terminate the program. Exceptions only happen because someone wrote a library that specifically throws an exception given certain circumstances. Typically to avoid going into an unexpected situation, which might be an opening for a hacker.

Actually, the dangerous move is to catch exceptions rather than letting them slip, that is not to say that you should never do so, but be sure that you only catch those you know you can handle and let the rest slip. Otherwise you risk undoing the safety measure carefully put into your library.

Focus on the errors that do not necessarily throw exceptions, like writing beyond the end of an array. Your program wouldn't by chance be able to do that?
> 2 votes

# Answer
You need to look at your exceptions and need to look at the conditions that can trigger them. A hell of a lot of time, a large percentage of what people use exceptions for can be avoided by proper checks during the development/debug build/testing cycle. Use asserts, pass references, always initialize local variables on declaration, memset-zero all allocations, NULL after free, etc, and an awful lot of theoretical exception cases just go away.

Consider: if something fails and may be a candidate for throwing an exception - what is the impact? How much does it matter? If you fail a memory allocation in a game (to take your original example) you generally have a bigger problem on your hands than how you handle the failure case, and handling the failure case by means of an exception won't make that bigger problem go away. Worse - it may actually hide the fact that the bigger problem is even there. Do you want that? I know I don't. I know that if I fail a memory allocation I want to crash and burn horribly and do so as close to the point of failure as possible, so that I can break into the debugger, figure what's going on, and fix it properly.
> 2 votes

# Answer
Not sure if quoting someone else is appropriate on SE but I feel none of the other answers really touched upon this.

Quoting Jason Gregory from his book Game Engine Architecture. (GREAT BOOK!)

"Structured exception handling (SEH) adds a lot of overhead to program. Every stack frame must be augmented to contain additional information required by the stack unwinding process. Also, the stack unwind is usually very slow-- on the order of two to three times more expensive than simply returning from the function. Also, if even one function in your program (or library) uses SEH, your entire program must use SEH. The compiler can't know which functions might be above you on the call stack when you throw an exception."

With that being said, my engine I'm building doesn't use exceptions. This is because of the before mentioned potential performance cost and the fact that for all my purposes error return codes work fine. The only time I really need to look for failures is in initializing and loading resources and in those cases returning a boolean indicating success works fine.
> 1 votes

# Answer
I always make my code exception safe, simply because it makes it easier to know where problems arise, since I can log something whenever a exception is generated or caught.
> 0 votes

---
Tags: c++, software-engineering
---


# Question
Title: How was the world game market segmented in 2011?
Is there a source (or perhaps several) presenting how was the world game market segmented in 2011 (or does anybody know themselves)? For example:

* How many casual gamers there are? What is the total business, of which how much in virtual item sales?
* How many console gamers there are? How much is spent in hardware, how much in software?
* How many mobile gamers there are? How much is spent in hardware, how much in software?

And how all above is in different regions / countries?

# Answer
Generally you need to pay for this information, and I don't believe the comprehensive information you are specifically asking for is available all from a single source.

There was a similar question awhile ago asking specifically about casual gaming breakdown. Of the sources provided in that question, the following are likely the most relevant to your broader question:

These can provide you breakdowns of the relative distributions of (sometimes potential) casual or console gamers based on retail metrics and whatnot. I believe they both are US-focused, however. You'd have to find similar organizations for other regions.

Obtaining accurate financial statistics (total revenue in the casual space, et cetera) is not practical because not all companies disclose this information.
> 3 votes

---
Tags: marketing
---


# Question
Title: How does one do unit testing in a game engine?
Much to my shame, I have never written a proper unit test, only small unorganized test programs that I would then dispose of after the test succeeded. I don't really have a clear idea of how unit testing should be performed in a game project. (My language is C++.)

Should I have a separate project for each subsystem in my engine and an associated test with it, and then have a bigger project/ solution that builds the actual engine? Say for example I have the `event` module in my engine; how should I handle that?

# Answer
> 20 votes
First, you'd need a unit testing framework. In the past I've used UnitTest++ and Google Test. The former is very lightweight and the latter is more featured but somewhat more cumbersome. It integrates well with Google Mock should you ever need that sort of thing. There are of course many other options: see this list (by the eventual author of UnitTest++) and Wikipedia for example.

Unit testing is about writing focused tests to stress particular isolated independent bits of code ("units") under various scenarios. While in some cases you can unit test everything, it's usually not practical to achieve 100% coverage and, especially in games, can be quite difficult -- it's arguable whether or not unit testing your renderer output is in any way meaningful, useful, or a "true" unit test regardless.

It's important to remember that any (automated) testing is better than no (automated) testing. So you shouldn't stress too much over the fact that your tests aren't "true unit tests" and be proud that you simply have tests. Unit testing frameworks are usually useful for building looser, "non-unit" tests as well since they include functionality for packaging tests and reporting failures uniformly.

I would encourage you to resurrect your old tests and build them into a test project using one of the available frameworks -- something you can easily run from time-to-time (or automatically as part of a release or integration build) that runs all your tests. Write new tests for bits of code as it becomes apparent they would be useful to you, for example if you discover a subtle bug you could have detected with a test, you can add one to catch any regressions you may make in the future.

You will probably find that it's mostly your lower-level utility code that is amenable to unit testing, in games. That's fine -- that's foundation code that could disturb a lot of higher layers if it breaks.

You won't go to programmer's purgatory for not having tests for every little function and logical gate in your codebase, so don't spend more time than you need on writing tests. If you have to think harder or spend significantly more time writing the tests for a module than it took you to author the module in the first place, you may be wasting your time. Unit testing -- testing in general -- is a tool you learn to use appropriately to help you, not a chore you have to perform for everything.

# Answer
> 7 votes
There's a great series of blog posts about using TDD and unit testing for game developmnent here: http://gamesfromwithin.com/stepping-through-the-looking-glass-test-driven-game-development-part-1

# Answer
> 4 votes
A "unit" is the smallest testable piece of code, typically a single function or class. A unit test is another piece of code that exercises that unit of code to ensure it behaves as intended. A single code unit may have many tests, in order to cover all cases.

Typically, tests are not included in the main build of a project. Rather, there is a seperate build configuration for testing that includes all the test code and produces a program that runs all the tests and reports the results. A testing framework will provide all the scaffolding for this and is recommended, though not strictly necessary. If you are totally new to testing, you may be better off at first writing your own ad-hoc test rig, to make sure you understand everything that's happening.

Cover as much code as you can with tests, prioritizing code that you are not confident about, or code that is fragile and may be broken by future changes. You should run the tests often, ideally after every code change.

---
Tags: c++, software-engineering, unit-testing
---


# Question
Title: Using spherical harmonics to build complex sound scapes
I was having a discussion at work today on how to improve room acoustic modelling. It was suggested that very little work appears to have been done on the subject yet tonnes has been done in graphics. It was further suggested that as sound and light are just wave forms it might be possible to use things like ray tracing and radios to get a good approximation.

At this point I began thinking about spherical harmonics to simulate this behaviour. You could simultaneously do specular-esque reflections as well as audio scattering modelled as diffuse reflections. As a bonus you'd also get obstructions blocking sound transfer. The only problem was how to handle the attenuation of multiple frequencies. Surely though this could be modelled by applying some form of transform to the audio spectrum (FFT).

Anyway does anybody know of any papers on this subject, especially on how it would be performed in real-time. Failing that anybody got any advice or useful general information?

# Answer
Yeah, it's a good idea. Malham already wrote a paper on this, which was based on some comments by Menzies (back in 1999!).

Also note Nosal's MASc thesis discussing using radiosity for acoustics.

As for lighting, (which does 3 sets of functions, one for R, one for G, one for B) you would need to do a different "set" of SH functions for each rough frequency band you want to represent (say one for low frequency, 60Hz-1kHz, one for mid 1kHz-2kHz, one for high 10kHz-20kHz, etc). Let everything below 60Hz pass through everything (which is pretty much what sound does in real life)

You'd need to model the acoustic reflection capabilities of each material, however, just as lighted materials each respond to RGB differently.
> 5 votes

# Answer
It sounds like an interesting problem, though I am wondering how much accuracy you will need before people just can't tell. Anyway, this answer focuses on the "real time" part, but I don't know of any papers as it isn't something I've investigated.

Obviously if you want to calculate this accurately in real time, with mobile sound sources, calculating reflection would be fastest using the graphics card. For example if you have a simplified version of the world running simultaneously, you could use it to render "reflection patterns" to a texture or cubemap and infer from that texture how you should output the sound. Sounds (or separate frequency bands of sounds) in that model would be point light sources. With only basic (1 bounce) reflections you might find that you don't need any more accuracy anyway, while this should be very quick especially with simplified geometry and reduced resolution. I'm not entirely sure if there are performance problems with multiple scenes on one graphics card, though.

Getting further into areas I know little about, a BSP tree seems like it could be useful for waves that bend around corners as (I think) it defines volumes and their connections to other volumes.

Depending on the situation, a further optimisation would be to cache results from the above tests. For example, storing a cubemap of sound that could be rotated based on the players orientation but not recalculated entirely, or a couple of cubemaps that you can interpolate between based on the player's position.
> 3 votes

# Answer
I saw a talk at GDC on this 6 or 7 years back. Possibly this one: Geometric Modeling of Sound Propagation in 3D Games.

Others by the same author:
> 3 votes

# Answer
I haven't actually tried this, but I've always wondered if an approach such as light propagation volumes could be used for audio. In light propagation volumes a small 3d texture is used (32x32x32 I believe) in which light bounces and occlusions are simulated by flood filling the 3d texture. Since it uses spherical harmonics, it might be able to do this with audio as well. I'm not an audio expert however
> 2 votes

# Answer
Doug James of Cornell's computer graphics program has done a lot of work in accurate modeling of sounds in an environment. However, most of his papers handle specific cases of sound generators (thin shell objects, flames, etc.) They also are probably not efficient enough to do in real-time along with the other tasks your game has to do.

However, it may be of use for you to read through some of them. It may give you ideas on how to proceed and/or modify his approaches to be cruder but efficient enough for real-time performance.

His site is here:

http://www.cs.cornell.edu/~djames/

Of particular interest might be his "Harmonic Fluids" and "Harmonic Shells" papers.
> 2 votes

# Answer
I have also given this some thought. I felt the primary concern (in terms of realism/performance trade-off) was that spatially your ears are inferior to your eyes - and quite easily accept something that might not be as realistic as your eyes would need. There is a very good chance that trying to perfectly model sound in the local environment is overkill - EAX is probably 'good enough'.

In a closed environment (e.g. Quake) I would firstly calculate two properties about each room: 'transferrance' and immersion:

**Transferrance** would indicate how the sound would be affected by travelling through this room and would most likely count toward a parametric EQ (ideally you would add echo/reverb from each room, but your EAX chip might not have this much bandwidth). The parametric EQ would also ultimately simulate the sound attenuation.

**Immersion** would be calculated by splitting the room into nine cubes (possibly, even just one might be good enough) and calculating the local sound properties from that perspective. These parameters would be used in the EAX environment.

Finally each of your rooms would be connected by a graph, where each point in the graph are the portals connecting each room.

When the sound triggers you would do a flood fill (no an A\* search) and keep track of the the transferrance and distance travelled. When the sound reaches the player you would queue it up to play at some point in the future; based on the distance travelled. You might keep track of the number of graph points passed and eventually 'cull' the sound (in other words, a continuous flood fill). You might have to use CUDA to do this as it could get CPU bound.

When a sound plays you would use a 3D sound API (OpenAL) to and place it at the portal at which it entered through, you would then find out which of the nine cubes the player is currently in and apply that EAX environment.

The neat thing here is that if your environment is sufficiently complex you would get free 'global' echoes and players would perceive sound coming from the right direction; and if you get the EAX environment correct hopefully the effect would be convincing enough that the brain would accept it.
> 1 votes

---
Tags: audio, spherical-harmonics
---


# Question
Title: How can I create a curved path for a ball?
I am creating a soccer game. Now I want to shoot the ball and create an after-effect resulting in a curved path. I tried several things, but nothing seems to work.

I am using a 3D tool, but the camera is from the top. I especially want to create a curve of the ball with the effect to the left or right.

What is the best way to create a effect on the ball?

# Answer
The physics are very complicated, so it might be best to fake it by treating it as a weak gravity that pulls left or right depending on the kicker (and each kicker would have their own different fake gravity) and the fake gravity gets stronger as the ball slows down (so the curve becomes more J shaped). This sample article that gives an idea of some of the physics involved. The reason for the complication is that it involves both turbulent and laminar flow (the equations for which are terrible and headache inducing) depending on all sorts of factors such as the roughness of the ball (smooth like a billiard ball, dimpled like a golf ball, and the smoothness of last world cup ball made it move differently from a regular regulation ball), the impulse given to the ball (and how offset from true dead-center it is) and whether the ball is wet or dry.
> 1 votes

---
Tags: physics
---


# Question
Title: Is the output from D3DCompile specific to one GPU, or not?
In Direct3D 11 there is a two-stage shader compilation process; you first pass the HLSL source code into D3DCompile, which outputs a "blob" of bytecode. You then take this blob and call CreatePixelShader or another of the CreateWhateverShader methods to finally get an object that can be bound to the D3D pipeline and used.

My question is: is the bytecode produced by the first stage machine-independent or is it specific to the GPU on which it was compiled? I could not find a straight answer to this in the MSDN docs. I heard somewhere that HLSL compiles to machine-independent bytecode which is then translated into GPU-specific machine code by the driver, but I have not been able to confirm this.

# Answer
> 3 votes
This Presentation by AMD should answer your question about shader compilation in DirectX and intermediate representations of shader code:

http://developer.amd.com/media/gpu\_assets/Dark\_Secrets\_of\_shader\_Dev-Mojo.pdf

I have only skimmed over it, but HLSL shader object code seems to be hardware independent indeed.

Also, from my own (albeit small) experience: I compile shaders using fxc.exe and distribute the shader object files in an archive just as any other type of game asset. During run-time, I just read those object files into ordinary byte buffers and pass them to ID3D11Device::CreateVertexShader() for instance. How would that ever work if shader object files were not platform independent?

EDIT: Sorry, I only just noticed that you were specifically asking whether the output of D3DCompile was platform independent. Since that output can (and must) be fed to Create...Shader just as fxc-output can, I suppose it's pretty much the same thing, added to the library for convenience.

# Answer
> 1 votes
I'm not sure where in MSDN docs it is written, but HLSL bytecode is independent of GPU. HLSL shader compilation is happening in D3D API, not on driver level like in OpenGL case.

---
Tags: hlsl, directx11
---


title: Reading data disks in Xbox360 homebrew

text:
# Question
Title: Reading data disks in Xbox360 homebrew
I heard that X360 homebrews are not allowed to be started from DVDs; however, they can be downloaded from PC or via live and started.

The question is: it is disabled to access DVD drive at all?

I want to access data tracks, without using any (theoretically prohibited) media APIs for playbacks; also I don't want to *run from disk* (which is prohibited by Microsoft).

# Answer
if you mean XNA, you can't deploy your game on a disc

http://forums.create.msdn.com/forums/p/8399/122831.aspx

or read data from a disc

http://forums.create.msdn.com/forums/t/14886.aspx
> 2 votes

---
Tags: xbox360, homebrew
---


title: Multi Threading In Update Loop

text:
# Question
Title: Multi Threading In Update Loop
Okay so I am working on a game engine and this was my previous game loop:

```
Game::Run()
{
    While(!m_GameDone)
        Client.Update();
        LocalServer.Update();
}

```

but what I want to do is:

```
Game:Run()
{
    ClientThread = new CThread(...);
    ServerThread = new CThread(...);
    ClientThread.StartTask(Client::Run);
    ServerThread.StartTask(LocalServer::Run);
    CThreadSystem.WaitForTasksToFinish();
    return;
}

```

And then Client::Run and Server::Run would be:

```
Client::Run()
{
    while(!m_Gamedone)
    {
        this.Update();
        this.Render();
    }
}
Server::Run()
{
    while(!m_Gamedone)
        this.Update
}

```

So my two big questions are.. Is this a good idea? and How do I make a thread execute a function from a class instance? The threading system I am using right now is WinAPI and XTL (not STL).

UPDATE:

Okay, everyone wants to tell me about locks and data sync. The client and server threads DO NOT SHARE ANY COMMON DATA/OBJECTS. The client and server threads have their own serialized update loops and don't use any common classes or structures. I just wanted to know how to start a thread with a function in class instance scope.

# Answer
Yes this is a good idea in general though I would consider splitting the server side out and making a dedicated server.

Secondly here is how you launch a Win32 thread and get it to call a function in a class.

```
class MyClass
{
     public:
     static void ThreadStartLoc(void* MyClassPtr)
     {
         ((MyClass*)MyClassPtr)->InternalThreadRun();
     }

     private:
     void InternalThreadRun()
     {
          // Do your loop here
     }
}

```

Start the thread with this call.

```
MyClass* MyClassPtr = new MyClass();
_beginthreadex(NULL, StackSize, MyClass::ThreadStartLoc, MyClassPtr am, 0, NULL);

```
> 2 votes

# Answer
Assuming your Update() methods look like this:

```
for each entity in allEntities
{
    entity.Update()
}

```

You'd need to either synchronize (aka lock) the entire loop:

```
lock(allEntities)
{
    for each entity in allEntities
    {
        entity.Update()
    }
}

```

Preventing almost any multi-threading gain. The other way would be to synchronize around each and every entity update call:

```
for each entity in allEntities
{
    lock(entity)
    {
        entity.Update()
    }
}

```

Again, preventing almost any multi-threading gain and is probably much slower than just synchronizing the whole loop. Synchronizations are expensive:

> Another reason to avoid having many locks in a system is the cost of entering and leaving a lock. The lightest locks use a special compare/exchange instruction to check whether the lock is taken, and if it isn't, they enter the lock in a single atomic action. Unfortunately, this special instruction is relatively expensive (typically ten to hundreds of times longer than an ordinary instruction)
>
> http://msdn.microsoft.com/en-ca/magazine/cc163744.aspx

That said, there are multi-threaded solutions that either avoid or minimize locking. One way is to use 1 thread for the core game and other threads for non-core game elements, like generating and animating trees and animals in Flight Sim X \[ref\].

An other way to do it is to have 2 copies of every game entity (wasteful, I know). One copy would be the `present copy`, and the other would be the `past copy`. The present copy is strictly write only, and the past copy is strictly read only. When you go to update, you assign ranges of your entity list to as many threads as you see fit. Each thread has write-access to the present copies in the assigned range and every thread has read-access to the all past copies of the entities, and thus can update the assigned present copies using data from the past copies with no locking. Between each frame, the present copy becomes the past copy, however you want to handle the swapping of roles. \[citation needed\]

If you aren't noticing performance issues, I wouldn't change anything. Multi-threading issues can be tough to track down.
> 1 votes

# Answer
Use duplicated data synchronized with message passing via 1 directional ques. It lets you scrap any kind of locking. It should also be a very flexible system.

Here are a few pointers, it's basically a system I worked out to tie in threading, multiplayer network replication and saving/loading. It's only theoretical, i've never implemented it so I cant say much about the performance.

This is a lot of text but typing it out helps me flesh it out too ☺

Firstly understand that mutex locks are going to kill performance and should be avoided. If you have 2 threads and they both lock the same game world state for their entire operation then they will be slower then just going unthreaded. Atomic stuff is better performance wise but if we get creative we can actually avoid it.

Don't base your synchronization around 'Objects' or 'Entities'. Base it around individual properties.

Give each property a unique id. Depending on your requirements, a simple game might just use an unsigned int, a more complex game like a MMORPG might use a UUID (32bytes) of which part is a timestamp that should allow ids to be generated across multiple separate servers that don't even know about each other with a statistically close to impossible chance of a id collision. If you keep those id's in sync rather than generating them dynamically this will help with network replication too (the simplest way is to transmit the whole list of dynamic properties, their current values and ids).

Named strings ids can help with scripting so you can do things like "dungeon12.dragon3.health = 1000" and/or print out a human readable list of all ids and their values for an object (which can help with things like writing level editors), but names add parsing overhead, so if you do want that it's probably best to have regular numbered ids too for things like threads and network.

Work out what properties are 'static' (or const) and what are 'dynamic'. The static stuff can be ignored with regards to synchronization. The memory could also be shared between threads without any synchronization and doesn't need to be transmitted to clients over a network (provided it's 'shipped' with your game (A custom level might need to be transmitted it the client doesn't have it though, and maybe you want to make a really flexible engine that allows you to alter vertex information on meshes which would be useful for a networked 3d editor). Things like unchanging objects in the level, the level itself, mesh information. The dynamic data will probably only be a small fraction of all your game data.

A good idea is to give each property a flag/timestamp that indicates it was changed (or created) at runtime (one flag for properties changed since file was loaded from disk, another one for properties that have changed since the last network/thread replication transmission). This allows you to make fast and compact saves since you only need to store the changes from the initial state. You can also let players jump into the middle of a game on a network and just upload a list of all the properties. It saves manually separating the properties in dynamic and static.

As a side note if you want almost instant loading/saving find a way to keep all the dynamic values separate from the static ones then when you save you can just 'snapshot' the current game state, copy it off to another block of memory and spawn a background thread to write it to the disk while the player keeps playing. Loading can just scrub the current dynamic state and restore the saved properties without effecting the unchanged ones.

Your properties are no longer going to just be basic data types in a class, they will be small classes of their own.

Look into serialization. That's the art of taking data from program classes and turing it into something that can be transmitted or stored to disk. Stuff can be serialized to bother binary, plaintext and XML. It might be handy to be able to choose between them (network and thread communication would want binary, XML might be usable for loading levels from disk and gives you an editable format).

For increased performance try to keep all the property information in a flat list somewhere so you don't have to walk up and down a tree, octree, BSP or whatever and query all the information inside of each object. It also helps with the above save/load system since you just copy the list.

Give each thread its own copy of the dynamic data, we will synchronize them manually. Ensure that 'Client' thread only has dynamic information it needs to know about, that is stuff the player can actually see or stuff with in range. In addition to reducing what we have to deal with, this also helps with preventing network cheating (the player can't wall hack if there is no entity information of what is behind the wall, of course that would require your server thread to work out what every player actually can see which is possible if you render a really low resolution low graphics version for each player but a a simple ranged/clipping frustum based system is more likely but that still prevents players from knowing about stuff on the other side of the map). You might be able to tie this into your 3D drawing code here since it will be doing similar things when working out what is visible and needs to be drawn, it's also handy to separate your render scene graph from your game world information, there's no sense in keeping mesh/texture/VBOs and so on inside your game objects, that's all render information. It also helps keep your game API agnostic when it comes time to port from DirectX to OpenGL or some kind of ASCII renderer.

Work out a property ownership/security. Just about everything will be 'owned' by the server except a few special classes for clients to send their information too. Stop clients from having the power to edit values they shouldn't but lets you use 1 global system for managing properties (ie rather than treating client information as different from the gameworld properties).

Work out the 'flow' of information. For example the 'Server' thread will be updating the 'Client' thread with regards to the entities in the game world. It won't normally be happening in reverse, the client shouldn't be updating entity information directly even on their own character otherwise it would allow hacks to teleport around the map. Instead a special controller object that they 'own' should be used that the server watches and uses to sync the game world's representation of a player.

To keep things in sync between each thread/network client use uni-directional FIFO message passing pipe RPC ques. Basically a simple FIFO that only has a single producer and a single consumer can be implemented in such a way that no mutex locks or atomic information is needed. Technically you might want a single atomic on the que itself depending on what your programming language/compiler do, it might be that all simple variable changes are atomic without having to do anything. Also depends on how 'theoretically' safe you need to be vs what actually works in the real world. C++ would probably work without issues in most places but technically the standard doesn't say anything about it so it's theoretically possible for your computer to explode, C++11 introduces atomic\<\>. I don't know what C# does. These FIFO ques can be used between threads and between network clients.

You can do some plumbing on your FIFO's to allow them to be split to multiple consumers or combine messages from multiple producers. (Basically just a list of FIFO's that actss like its just one big message que).

Use an Observer Pattern for your threads. Give each observer a dedicated que. You can thread threads and remote clients as basically the same just one goes across the network. Put your security in the network receiving part.

Work out a RPC language for your messages. What need to be transmitted across the network. The same can be used for inter-thread communication.

* UINT - Message sequence number
* BYTE - Op code
    + Set int/uint.
    + Set string.
    + Set float.
    + Set array.
    + Add object to list. (we tread a list as a property, it lets you add objects to a level). Do you create new objects here or is that separate.
    + Remove object from list.
    + Request Ping (So we can calculate lag)
    + Send Ping response (Pong).
* UINT - Property ID
* DATA - Property value, length depends on type. Some types will need their length appended at the start.
* Checksum?

You could have special opcodes for things like setting the player name or a bit of text in chat, but otherwise you could just give the player ownership of special string properties that the server watches. Player set the string, server send a chatmessage/namechange request. Actually using that method you could perhaps decompose the above into something even simpler there the network codest just involve setting a few special state objects on the server. You would have SetRawDara, LengthOfData, Id. And floats, ints, strings, arrays and so on would all be treated the same way. Just leave it up to the server to check its valid (does player own that object, is the data size correct) and work out what to do with it.

You probably want to use both TCP and UDP. For things like player location UDP is fine. Things like chat or transmitting the initial state would need reliability.

For thread-\>thread communication you might actually want a different RPC. You actually might be able to use a list of lambada functions and ditch the protocol/parsing totally (On C++11 this should be possible, don't know about C#). Or use function pointers. If you do that network stuff would need to be treated somewhat separably but that's probably for the best. You don't need the security ownership stuff in thread-\>thread either and if the source is internal you can trust that the size of data being set it sane.

Each thread/client checks the que(s) before (or after) it calls its update function. If there are new messages it looks at the operation

Server thread has a Game World State. It contains every single object. When a property it owns is updated it will transmit it to all listening (or ones within range) 'client' threads via the FIFO. It will listen to a list of ques, one from each client. Its loop will basically be:

* Check incoming thread.
* Process incoming messages (This should be a FIFO that has combined all incoming client messages), update values as required.
* Perform its own updates.
* For each value updated (both from the incoming threads that need to be broadcast on to everyone else (unless you are doing p2p) or the internal update are added to a list of things to be broadcast to all clients.
* Send a broadcast message to all listening clients.

Come to think of it, working out what player is listening to a particular 'property' might be a bit hard since a health property won't have any concept of the object itself or where it is in space so maybe ensure that each property has a parent reference.

Network thread(s). Either one global one, one per-connection, or a pool that processes network packets. This is the same for both clients and server.

* Listen for a packet.
* Check the validity on the packet
    + Does the client 'own' the property id it is trying to change.
    + Is the size correct.
* If valid, convert it to the internal message representation (function pointer, lambada function, opcodes whatever). Add it to the FIFO que for this client.

Client threads:

* Process messages from server (possibly from other clients if your doing p2p).
* Update properties
* If using a separate rendering thread send relevant messages to that (ie just visible information, position, any new objects in view)

Rendering thread (this can be sound too ☺):

* Receive and process messages.
* Render.

Physics thread is a bit more complicated. My recommendation would be to ensure that your physics engine works predictability so all clients will get an identical result. Rather than transmit a continuous stream of position updates, instead transmit the basic physics information (overall force being applied, velocity, current position) and let the clients work it out.
> 1 votes

---
Tags: windows, xbox360, multithreading, winapi
---


title: Using Vectors for 2d animation

text:
# Question
Title: Using Vectors for 2d animation
I've decided that it's best to start using vectors in my games instead of the
`xPos += xSpeed` and `yPos += ySpeed` approach.

I'm posting some of the code from my basic model class which handles movement logic in my game so that someone can tell me if I am using vectors correctly. I have a position, direction, acceleration and velocity vector. Here is some code, I can post more if needed:

`model.update()` and `rotate()` function

```
public function update():void
{
    checkInput();
    pos.addVec(velocity);
    velocity.addVec(accel);
    velocity.multiplyScalar(friction);
    dispatchEvent(new Event(Event.CHANGE));
}

public function rotate(val:Number):void
{
    angle += val;
    direction.x = Math.cos(angle * degreesToRads);
    direction.y = Math.sin(angle * degreesToRads);
    direction.normalize();
}

```

and the `checkInput()` function

```
private function checkKeys():void
{
    accel.set(0, 0);
    if(keys[Keyboard.LEFT])
    {
        rotate( -5);
    }
    if (keys[Keyboard.RIGHT])
    {
        rotate(5);
    }
    if (keys[Keyboard.UP])
    {
        accel.x = direction.x * 0.8;
        accel.y = direction.y * 0.8;
    }
    if (keys[Keyboard.DOWN])
    {
        accel.x = direction.x * 0.5;
        accel.y = direction.y * 0.5;
    }
}

```

Hopefully someone can tell me if I'm using vectors correctly by adding acceleration to velocity and to speed and also if I'm doing rotation the correct way or if there is a better way. Or anything anyone can suggest to improve would be great.

# Answer
There's no "correct" way to do this. Using `xPos += xSpeed` and `yPos += ySpeed` is basically the same as `pos.addVec(velocity)`. I suggest you use what you're comfortable with.

If movement behaves as it should, then go ahead. Some minor things you could improve, by looking at your code:

* Events are slow. Don't dispatch them in the update loop... call methods directly or use signals.
* You should calculate movement in a framerate independent fashion, so that your game runs at the same speed on slower computers as well. The way to do this would be to measure the elapsed time since the last frame and use this delta for movement calculation.
* You don't need to `normalize` your direction after the rotation calculation. It's a unit vector already.
> 1 votes

---
Tags: physics, actionscript-3, vector
---


title: How does this animation work?

text:
# Question
Title: How does this animation work?
This project "Locomotion Skills for Simulated Quadrupeds" creates an animation for the dog model in the program. However if you go into the project's files the dog's skeleton is made of individual obj files for each bone. How were the bones loaded into the program to make the complete animation? It's as if the position of the obj's were attached to... the vector I guess? Can anyone elaborate a little more?

My reasoning for this is because I want to replicate it, create a model (to be animated) out of separate model files. I guess my question is how make one character out of several separate model files? Thanks

# Answer
Animation is a very complex part of 3D rendering, and I recommend you read this first. But here's what's going on in a nutshell:

In order to animate a mesh you need to define a set of 'bones' for the animation, and it's the bones that are being rotated and translated according to the animation. The model that's being displayed will have it's vertices linked to one or more bones which will determine their transformations.

The separate obj files you're seeing in the project are each linked to one of the bones, so that when the program is running you can clearly see the movement of each bone. They simply apply the world transform of each bone to the mesh associated with that bone.
> 1 votes

---
Tags: animation, game-mechanics, models
---