# Question
Title: Is there a typical career path to learn game development "on the job"?
The extended version of the question is: what is the typical career paths that a developer *without specific experience in game development* should take if he/she wishes to work in the game development industry? In other words, what are the positions such a programmer might aspire to get hired for, in the game industry?

I am asking because it seems to me that - even without direct experience with 3D modelling, physics engines, shaders, etc... - for as much complex as these topics might be - they are still "just" top layers one can learn "on the job" if he/she has already good programming skills and experience in software design (for example during peer-programming sessions).

I have no knowledge whatsoever of the game industry, so maybe I am being naïve here, but for all the other programming jobs I previously took, I learned most of the specificics while working on concrete projects... so I wonder if there is a chance to do the same with game development.

Thanks for your time and advice! :)

PS: I don't know if this is important or not for answering the question, but scripting languages are the languages I am more proficient in.

# Answer
> The extended version of the question is: what is the typical career paths that a developer without specific experience in game development should take if he/she wishes to work in the game development industry? In other words, what are the positions such a programmer might aspire to get hired for, in the game industry?

There isn't a typical career path, per se; that would imply a lot more structure to the industry than actually exists. However, as a programmer, without specific experience in programming in areas for games (graphics, physics, et cetera) one can be expected to get hired as an entry level programmer -- perhaps as a general "gameplay" programmer.

If you are interested in those other areas, you will likely need to dedicate time to learning them on your own -- at least a little bit.

N.B. that 3D modelling is not typically a task performed by programmers at all, and while programmers may employ some scripting in their day-to-day jobs, it's not their primary function (designers tend to do a lot more with scripting languages, if the game uses them).
> 4 votes

# Answer
If you want to work in the games industry as a programmer, make a game demo.. I can not stress enough how much one of these will increase your chances if you do not want to go to a school for game development.

If however you are more interested in level and environment development, this is what designers do. You may want to get an existing engine (Unreal?) and make up a level if that is the sort of work you are after as opposed to a programming job. (I mention this because of your mentioning of scripting vs programming)

Hope this helps.
> 5 votes

# Answer
There are two positions that a programmer without specific game industry experience might qualify for in a major game studio.

First, depending upon level of experience as a programmer in a non-games industry (and the specific studio's stance on this), he may qualify either as a junior or as a mid-level programmer. At a major studio, it would be essential to be able to show proficiency with C++ in order to get either of these roles. At web-game-making studios, Flash will be necessary, etc.

On the other hand, if the programmer had much leadership background, he might qualify for an "assistant producer" role. That is a largely non-technical role, though; more of what most other industries would call a "project manager".

Any game industry job will involve some degree of mentoring, to teach new hires about how to use the company's tools and how to follow their best practices. For a junior-level position, the mentoring will be a bit more extensive, intending to bring a hire from "I studied this at university"-level up to a professional level. But you absolutely will not find a game industry job where they pay you (for example) to learn how to program in C++ (or whatever the particular studio's standard language of choice might be); that's a skill they expect you to have already mastered before applying for the job.

Short version: No, there is really no career path to learn game development "on the job". There is enough competition for game industry jobs that no company will pay someone to learn, when they can pay someone else to work right now. If you want to get into the game industry, you either need to get game experience, or else get equivalent experience elsewhere, using similar tools to those that are used in the game industry.
> 4 votes

# Answer
Regarding my career path, I began 10 years working as a Flash developer in digital agencies. There is a huge demand for Flash games used as marketing incentives by big brands (see www.thefwa.com). After 5-6 yrs of developing "branded" Web games, I was hired by a AAA company for a year - I chose to move back to Web games later.

AS3 is a decent object-oriented language, close to Java, it's quite easy to move from Web games programming to mobile programming, and later to AAA game programming.

Most employers in marketing/digital/Web agencies are now facing a huge demand regarding (Flash, or native) mobile development, so you'll get lots of opportunities to evolve/demonstrate your skills regarding non-scripting languages (and running OpenGL decently on poor hardware, which is basically the basics of consoles game programming).

Some Web games are including quite sophisticated algorithms and game mechanics, see dofus.com or the Zynga games, even my own job is about building RPG-like isometric stuff, with scripting/AI features.

So you'll probably should learn extensively Flash, iPhone and Android, find a day job in that field, and you'll reach your goal quicker than you think.
> 2 votes

# Answer
> In other words, what are the positions such a programmer might aspire to get hired for, in the game industry?

In my experience, there are no routes into game programming that allow you to learn on the job. You must demonstrate your suitability for the role before applying, usually with a combination of an academic qualification and a collection of code samples.

> I am asking because it seems to me that - even without direct experience with 3D modelling, physics engines, shaders, etc... - for as much complex as these topics might be - they are still "just" top layers one can learn "on the job" if he/she has already good programming skills and experience in software design (for example during peer-programming sessions).

In theory, yes. In practice, no. Nobody is going to pay you to learn this stuff because for every one person in your position, there are fifty of equivalent experience who are teaching themselves these skills in their spare time with a view to presenting a demo to prospective employers.

> but for all the other programming jobs I previously took, I learnt most of the specificities while working on concrete projects... so I wonder if there is a chance to do the same with game development.

Most other programming jobs either have fewer domain-specific requirements (eg. I used to work in geographical information systems, but the amount I needed to know about map projections and the like could be picked up in a day) or are less able to rely on applicants to be self-motivated and thus *have* to provide the training. Games development is very heavily domain specific and has an army of self-motivated people eager to break into the industry.
> 2 votes

# Answer
On the programming side, I can only speak for Germany, but everyone that I asked in game development, as well as what I generally read online tells me the same thing (And I don't know why it would be any different anywhere else): Study computer science.

And it's not really that hard to imagine why. Programming games (and aspects related to it) requires almost everything you learn in your typical computer science major - on the math side a decent knowledge of linear algebra, calculus, statistics and the stuff related to theoretical computer science (number theory, graph theory, computational geometry, algorithms and data structures... the list goes on and on and on) will help you a ton.

Also, most computer science majors will lead you through a ton of topics that are directly related to game development - besides the usual programming courses, there's also courses for things like artificial intelligence, software engineering, project management, distributed computation etc.

In addition to all of that, many universities now also offer optional side courses like "Computer Graphics", "Game Development", etc.

So if you want to the way of the programmer (instead of becoming a level designer or something), I tell you: Go for computer science.

There are of course a lot of things that a strict classical computer science master doesn't cover when it comes to game development - but that's also the case for almost anything that you'll program out in the real world. The "real" experience is mostly gathered by actually programming games as a hobby at home.

But that is just the programmers side of course - I can't really tell you where all the other artists come from (Graphics artists, sound engineers etc).

Still, I hope my answer helps you.
> 1 votes

---
Tags: career
---


# Question
Title: Easy road from DisplayObject to Molehill?
I have a finished Flash game which is rendered using the built-in display tree, i.e. `Bitmap`s contained in `Sprite`s (and a text here and there, few vector graphics, and one bitmap-filled shape). For extra performance, I'd like it to use Molehill for rendering, but that's not possible out of the box.

What's the easiest way to make this game use Molehill when available, but fall back to the current method if it's not available?

# Answer
You might want to check out ReMx, it's a 2D game dev framework for Molehill, and there is Away3D for 3D graphics with Molehill.
> 2 votes

---
Tags: opengl, flash, actionscript-3, molehill
---


# Question
Title: What is a good technique for 2D tile-based terrain generation meeting these requirements?
As a summer project I decided it would be fun to make a Flash game. Right now I'm going for something like the look of Terraria. It's been a lot of fun, but today I've hit a snag. I need a way to generate my worlds. I've read up Perlin noise as a possibility, but I my attempts have given me sporadic looking results. What are some techniques used to generate these 2D tile-based worlds?

Ideally I would like to be able to generate mountains, plains, and caves.

# Answer
> 6 votes
It sounds like you're looking to generate a "side view" of the generated terrain.

There are plenty of terrain generation algorithms discussed on the web. You could probably adapt many of them by cutting out all but one dimension from the calculations. This would give you information about the primary surface/underground boundary. If you want to be more directed in your search, you probably want to look for "1D" terrain generation or "Worms-style" terrain generation. You'll get results like this thread on procedural terrain (including caves), and this interesting web demo.

Perlin noise alone would work well for the areas where you want to generate plains, since it's very smooth. It doesn't work so well for mountains and craggy areas with sharp discontinuities -- you'd want to combine it with something else for that. Consider the first portion of this page on fractal terrain, or applying random cuts and displacements to the terrain.

Caves can be done by randomly punching holes in your terrain as a simple first pass, but you can also look for information on how rooms in Rogue-like games are generated and apply that. You might also consider looking into cellular automata.

---
Tags: flash, tiles, terrain, procedural-generation
---


title: Scrolling a WriteableBitmap

text:
# Question
Title: Scrolling a WriteableBitmap
I need to simulate my background scrolling but I want to avoid moving my actual image control. Instead, I'd like to use a `WriteableBitmap` and use a blitting method. What would be the way to simulate an image scrolling upwards? I've tried various things buy I can't seem to get my head around the logic:

```
 //X pos, Y pos, width, height
 Rect src = new Rect(0, scrollSpeed , 480, height);
 Rect dest = new Rect(0, 700 - scrollSpeed , 480, height);

 //destination rect, source WriteableBitmap, source Rect, blend mode
 wb.Blit(destRect, wbSource, srcRect, BlendMode.None);
 scrollSpeed += 5;

 if (scrollSpeed > 700) scrollSpeed  = 0;

```

If `height` is 10, the image is quite fuzzy and moreso if the height is `1`. If the height is a taller, the image is clearer, but it only seems to do a one to one copy. How can I 'scroll' the image so that it looks like it's moving up in a continuous loop? (The height of the screen is 700).

# Answer
> 1 votes
You can't "scroll" a buffer without somewhere to store the bit that's shoved off the end, so it looks like you'll need to either have a separate store for the swapping blit, or separate source bitmap. I would choose the latter for simplicity's sake, then you can store a scroll position and generate your rects using that.

You'll need to generate two rects, one for the top and one for the bottom, the one for the top will need to start at zero height, and increase until it reaches the bottom, the source rect that pairs with it will also start at zero height, but will start from the bottom of the source image:

```
Rect src = new Rect(0, 700-scrollPos, 480, 700);
Rect dest = new Rect(0, 0, 480, scrollPos);

```

Your bottom rect will be the one you see to start with, and will take up the entire screen at the beginning, reduce in size while moving down the screen out of the way of the top rect, the source rect for that would be doing the same, but instead of moving down, it just shrinks.

```
Rect src = new Rect(0, 0, 480, 700-scrollPos);
Rect dest = new Rect(0, scrollPos, 480, 700);

```

And using those two blits, you have a scroller.

---
Tags: c#, camera, silverlight
---


title: What is involved for a simple UDP game?

text:
# Question
Title: What is involved for a simple UDP game?
I once tried to write a simple game with UDP in a week as a throwaway test. It went horribly.

I threw it away early. The main problem i had was restoring the game state of all players/enemies/objects to an old state and fast forward the game to the point of time the player is playing (ie half a second before a jump. A little early or late can make the player miss the jump)

Maybe this method is not the easiest way? i suspect it to be but i designed it wrong from the beginning and realized at the end of 2nd day. (so i didnt learn too much or wasted that much time)

For myself and others, What is involved for a simple UDP game and how do i write one? Or how do i solve the prediction problem restoring to state properly.

I'll mark this as CW bc i know there will be lots of helpful answers.

# Answer
> 9 votes
Glenn Fiedler has written an excellent set of articles on this, which covers pretty much all of the basic concepts.

# Answer
> 3 votes
Rolling your own can be educational, but you often get more done if you can leverage an existing implementation (or at least start from there).

I've used both ENet and Raknet. I only used Enet in a simple game but it did what I needed. Enet uses a lower level API than Raknet. Raknet was used in a larger project. Raknet is extremely powerful, but wants to make you structure your game around Raknet's framework.

### Enet:

* Connection Management
* Sequencing
* Channels
* Reliability
* Fragmentation and Reassembly
* Aggregation
* Adaptability
* Portability
* Freedom

### Raknet:

* Object replication
* Autopatcher
* Secure connections
* Robust communication layer (basically all of Enets features rolled up in one item)
* Remote procedure calls
* Voice communication
* NAT punchthrough

# Answer
> 2 votes
If you have the time and energy, you could download the Quake 3 source and study it. It's fairly easy to comprehend if you're comfortable with C, and equally easy to tinker with.

Which other multiplayer games have source available and use UDP?

# Answer
> 0 votes
If you go homebrew (as I did) you're going to learn tons - also about stuff you didn't want to know. Like NAT traversal. According to caspin, Enet is missing out on that, but you could always find some open source STUN code that works in most situations.

---
Tags: architecture, networking
---


# Question
Title: Variable-step update() in game loop is falling behind, how can I get around this?
I'm working on a minimal game engine for my next game. I'm using the delta update method like shown:

```
void update(double delta) {
    // Update code that uses `delta` goes here
}

```

I have a deep hierarchy of updatable objects, with a root updatable that contains several updatables, each of which contains more updatables, etc. Normally I'd just iterate through each of the root's children and update each one, which would then do the same for its children, and so on. However, passing a fixed value of `delta` to the root means that by the time the leaf updatables are reached, it's been longer since `delta` seconds that have elapsed. This is causing noticable desyncing in my game, and time synchronization is very important in my case (I'm working on a rhythm game).

Any ideas on how I should tackle this? I've considered using StopWatches and a global readable timer, but any advice would be helpful. I'm also open to moving to fixed timesteps as opposed to variable.

# Answer
> 4 votes
It's not clear why this should be a problem. If the delta is the time between updates, then it doesn't matter if it's called 1ms late providing it's consistently called 1ms late, which would appear to be the case. It's also not clear how you are observing that this is a problem given that presumably there is no visual output until the whole lot has returned.

It's also hard to imagine any time-based game that has an update() so slow that it takes even 1ms to update the object. What are you doing in these updates?

I would suspect that your delta calculations are simply wrong in some other way. Could you post a simplified main loop showing how you are obtaining this value?

# Answer
> 0 votes
I guess you have to have a fixed delta time for all your update scene class. It doesn't matter if the accual time is passed while you were processing previous nodes, but it's important that all your nodes move step forward with same measure.

in general you can update your scene using two different methods:

1. one is to have all objects in your scene to be in same time frame at the end of update call. It doesn't matter if they are updated 2 miliseconds or two hours, the only important thing is to have a snapshot of your game objects at **specific** time T. this way you can have show your gamestate, since in every picture all objects should be in same time. for example you can't imagine picture of a man being chased by a lion and say "hey that picture is wrong the man and lion are 2 seconds out of sync!"
2. you can update object in your scene asynchronized. I'm not much of an expert in this feild myself but I know there are some simulations based on async updates in different node. I've just seen this method once used and it was to optimize simulation speed in Connway’s Game of Life. it's called hashlife. but still to give user the simulation results the application would continue simulation untill all the cells reach some **specific** generation and then show the results.

Now back to your problem, I assume you have some problem with syncing audio and video in your game. As kylotan suggested there should be something wrong with your delta time calculator. then again I guess you can somehow predict how much you update call going to last (for example if you are running your game at 60fps, you may assume each game cycle last around 0.016 seconds) and just play music with that much difference with your accual game time.

---
Tags: timer, synchronization, timing
---


title: Game State / Screen Management

text:
# Question
Title: Game State / Screen Management
What's the best way to handle game states / screens? My problem is this:

PlayGameScreen adds a new InventoryGameScreen to the game during it's update. This immediately adds InventoryGameScreen to the array of GameScreens. That's throwing an exception when iterating over the array that the contents of the array have changed.

Should I have two more arrays, like screensToBeAdded and screensToBeRemoved and do all the processing for them at the end of the game loop after drawing all the other screens?

# Answer
There are several equally valid approaches, and enqueuing pending changes for later processing like you have suggested is but one of them. It will work just fine; without more details it's hard to provide much more advice.

That said, this concrete example is for game state management in XNA, but the concepts should apply to any language/platform/technology/et cetera and it might help demostrate a working solution you can learn from.
> 2 votes

---
Tags: architecture, actionscript-3
---


# Question
Title: Questions before I revamp my rendering engine to use shaders (GLSL)
I've written a fairly robust rendering engine using OpenGL ES 1.1 (fixed-function.) I've been looking into revamping the engine to use OpenGL ES 2.0, which necessitates that I use shaders. I've been absorbing information all day long and still have some questions.

Firstly, lighting. The fixed-function pipeline is guaranteed to have at least 8 lights available. My current engine finds lights that are "close" to the primitives being drawn and enables them; I don't know how many lights are going to be enabled until I draw a given model. Nothing is dynamically allocated in GLSL, so I have to define in a shader some number of lights to be used, right? So if I want to stick with 8, should I write my general purpose shader to have 8 lights and then use uniforms to tell it how many / which lights to use?

Which brings me to another question: should I be concerned with the amount of data I'm allocating in a shader? Recent video cards have hundreds of "stream processors." If I've got a fragment shader being used on some number of fragments in a given triangle, I assume they must each have their own stack to work on. Are read-only variables copied here, or read when needed?

My initial goal is to rework my code so that it is virtually identical to the current implementation. What I have in mind is to create my own matrix stack so that I can implement something along the lines of push/popMatrix and apply all my translations, rotations, and scales to this matrix, then provide the matrix to the vertex shader so that it can make very quick vertex translations. Is this approach sound?

Edit: My original intention was to ask if there was a tutorial that would explain the bare minimum necessary to jump from fixed-function to using shaders.

Thanks!

# Answer
> 2 votes
1. Going from fixed function to programmable function involves only creating a shader program wich is built from at least a vertex and fragment shader. If you "Use" this program glUseProgram function. Every vertex is pushed through the programmable pipeline.
2. Another thing is (but optional) is to get rid of all the glBegin/glVertex etc and just use VertexBuffers so you have less calls to the GPU.
3. Most of the time when using gl version 3 or higher you also get rid of all matrix functions provided by opengl and do it yourself or use some library like glm.

So I would start with 1. You then can push your light info as uniforms to your shader program and use them in the vertex or pixel shader depending on if you want per vertex lighting or per pixel lighting.

I also suggest you read up on deferred shading (not needed for converting from fixed to programmable but still cool ;-)) which means that you render your scene into intermediate buffers (textures). In one channel/texture you render color info in another the depth in another the normals. Than you use another renderpass and use those textures as input and you can do the lighting in this second pass.

P.S. In modern hardware the fixed function pipeline is also implemented in the programmable pipeline and this shader is default enabled by the driver. Maybe you can find the source to this one to have the exact same result as your opengl 1.1 implementation.

---
Tags: opengl-es, glsl, hardware
---


# Question
Title: Suggestions for implementing a dynamic 2D level
I am working on a game that needs a level that is completely generated. Currently my approach is to draw textures for the levels pixel by pixel during the game (in XNA with SpriteBatch). This is too intensive unfortunately. The game has frame drops even when I only draw 1 level texture each draw cycle.

Here is an example of the current prototype. It is a simple sidescroller with the avatar swimming through a cave. The shape of this cave will alter throughout the level (textures and physics collision shapes). You can clearly see the boundaries of the level tiles in the screenshot below. These are generated just before they move into camera view.

For inspiration I looked at PixelJunk Shooter 2. These levels are obviously not generated, but some of the levels have movement. How do you guys think they implemented it? My guess is that the level and other objects in the game are actually flat 3d models, but I am not sure..

# Answer
For the generation of the cave, I would lean towards dynamic mesh generation, upon which you apply your background texture.

If your cave stays the same height throughout the whole game, you could start with the generation of a spline or a bezier curve, and convert this into vertices. Extrude these vertices for two different meshes towards the top and bottom to create the cave and calculate UVs. You obviously need to make sure the end of one mesh links up with the start of the next.

You could pre-generate a few 'screens' and generate new ones on the fly during the game.

It is also possible with tiling techniques; I would invert the idea and create just the path superimposed over the background. You could pre-define path tiles and link them together with the same screen type generation.
> 4 votes

---
Tags: xna, c#, textures, graphics-programming
---


# Question
Title: Finding out which tile a mouse click landed in
I am working on an isometric grid based game and im having an issue trying to link a mouse click from the user to a tile. I have been able to split the problem into 2 parts :

* Finding a rectangle that surrounds a tile (which I have been able to do)
* Figuring out from the rectangle which tile the click landed in (has got me stumped)

Here is an example of a rectangle with tiles on the inside:

The rectangle is 70px long and 30px high so if i use an input of say 30x(top)/20y(left) how would I go about determining which tile this fell into?

# Answer
> 8 votes
For each step you make in x direction you will move 35px left and -15px up to your canvas;

For each step you make in y direction you will move -35px left and -15px up to your canvas;

This means that you can convert your tile coordinate system easely in pixel:

(x,y) =\> (35·x,-15·x) + (-35·y, -15·y) = (35·x - 35·y, -15·x - 15·y) = (Xpx,Ypx)

You have to resolve the inverse problem you know Xpx and Ypx and you want to know x and y (in tile coordinate).

Xpx = 35·x - 35·y ;

Ypx = -15·x - 15·y ;

can you solve this?it should be:

x = 1/70·Xpx - 1/30·Ypx

y = -1/70·Xpx - 1/30·Ypx

Obviously you will have non integer values in general case: taking the ceil of both x and y will gives you the coordinate of the whole tile.

---
Tags: algorithm, tiles, isometric
---


# Question
Title: Automating repetitive game development tasks
Disclaimer: this is an open-ended and kinda "far out" question

Over the last few years I've made a few iPhone games. I use very common programs like Xcode and Illustrator to make the games.

Lately I've become tired of repeating certain tasks over and over again. Here are some examples:

* in Xcode: "clean target, build, run" over and over again
* in Xcode: delete image resources and then import updated image resources (identical names)

I'd like to automate these tasks in Xcode. Any ideas? I've done some automation in Photoshop using the "button mode" thing where you record a macro... that's been very useful.

Here's the kinda wacky or "far out" part of the question: how can this automation be done via voice commands? (perhaps using a Nuance product or something)

Here's an example of what I'd love to do via a few voice commands:

1. Save artwork from illustrator at a user-specified size (@2x versions as well)
2. Delete "someArt.png" and "someArt@2x.png" from Xcode
3. Add the updated versions of someArt.png to Xcode
4. In Xcode: clean target, build, and run

I know this question probably seems bizarre... but something like this could make certain things substantially easier for game developers.

Edit: wonder if a combination of AppleScript and Nuance might work?

# Answer
These are the kind of tasks you can usually script from a shell, assuming the programs in question are sufficiently scriptable. Mostly Xcode is simply going to do its work by calling out to GCC or LLVM or whatnot, so if nothing else you can write scripts for your shell of choice or in a language like Python to drive those tools.

You can also use higher level tools like AppleScript or Automator, and tie that to voice recognition commands via Apple's built-in voice recognition system (which can be enabled and configured via the System Preferences application). You can even incorporate voice commands into your scripts, as described here. Although I still think voice commands are a bit unusual.
> 2 votes

---
Tags: automation
---


# Question
Title: Did first generation Pokemon games use event driven input or poll based input?
Did the first generation Pokemon games for gameboy poll for the d-pad state or was the input state done based on events?

I'm currently trying to implement a similar control and I'm interested in comparing my input with that of the gameboy and Pokemon.

I'm using SneakyInput and cocos2d.

# Answer
> 2 votes
It really doesn't matter -- you can use either polling or event-based interrupts to simulate the other kind of input, so that decision is largely irrelevant in trying to mimic the characteristics of the input from older devices.

That said, you can find a lot of information about systems that old on emulation enthusiast websites (this one, for example, contains a wealth of information about the hardware and memory-mapped registers uses by the GameBoy -- it's similar to the document linked in some of the comments, if not exactly the same in a different format).

To achieve emulation of a particular game's input characteristics you'd want to do it at a higher level -- taking into account things like how the game handles two opposing directional bits set for joystick input, for example. Many older games don't handle this well, because it is generally not possible to physically interact with the device fast enough or in such a fashion as to cause some of the potential states to exist. This is how tool-assisted speed runners do some of their work.

You may want to scan through the TASVideos resource page for Pokemon and see if maybe there are any control-related oddities you should be emulating if you really want that level of similarity to the game.

But I don't think it matters very much to the end result if you choose polling or not, even though that is generally what was used on the GameBoy.

---
Tags: input, cocos2d
---


# Question
Title: Which is faster: raycasting or shadowcasting?
I'm looking to create an FoV implementation and I was wondering which algorithm is faster - raycasting or shadowcasting?

# Answer
Raycasting and shadow casting are *types* of algorithms, not algorithms themselves (in this context). So neither have any performance characteristics, per se, and thus neither one is faster than the other.

"Shadow casting" as a FOV technique isn't very common, I've only ever seen the term used widely in Roguelike development circles (and in fact the RogueBasin has a number of articles on shadow casting FOV techniques, such as the spiral path implementation and plenty of articles on FOV in general).

You also might find this article from GDNet interesting.

It's important to remember that there are more factors to consider than just performance -- while shadowcasting techniques tend to be faster than their raycasting counterparts, you pay a trade off in the shape of the results. Some algorithms generate more anomalies and artifacts than others, some procedures don't produce exactly uniform or symmetric results.
> 1 votes

---
Tags: algorithm
---


# Question
Title: Tracking Object Position - Firing on a Trajectory
How can I calculate the position of an object after "firing" it from a fixed point?

I am to create a small game - most likely with canvas (pure HTML, JS based) or Adobe Flash - in which the player fires objects at other obstacles in order to clear them.

# Answer
> 2 votes
You may want to look at this question and this one.

Assuming you are not using a physics engine/library that will handle the motion for you (and simply call back in to your code when a collision event occurs), you probably want to simulate projectile motion (also here, here, and in general here).

# Answer
> 2 votes
Good old physics will help you here. Specifically the equations of motion: http://en.wikipedia.org/wiki/Equations\_of\_motion

If you want to simulate projectile motion (as in an arc) there's plenty of information for that too:

http://www.ajdesigner.com/phpprojectilemotion/vertical\_velocity\_equation.php

http://hyperphysics.phy-astr.gsu.edu/hbase/traj.html

http://library.thinkquest.org/28388/Mechanics/Motions/Projectile.htm

---
Tags: physics, projectile-physics, trajectory
---


title: How to manage requests for a MMOG?

text:
# Question
Title: How to manage requests for a MMOG?
I read that most servers handle more than 50 requests per second. Is this true? how many requests can a normal server handle?

How do MMOG manage requests having to update player actions instantly?

# Answer
> 5 votes
> I read that most servers handle more than 50 requests per second. Is this true? how many requests can a normal server handle?

It's really impossible to say -- there isn't a standard definition for "normal" server, plus what many players (and even some developers without a lot of MMO experience) tend to regard as "a server" is actually a collection of both physical and logical servers that all interact to help simulate the game world. Some of them need to service a very high number of requests per second (quite more than 50), other don't so much due to their nature.

> How do MMOG manage requests having to update player actions instantly?

They don't. It's impossible to round-trip from the client to server instantly; instead, client-side prediction with server authentication is generally used to hide latency and make actions appear instant. You can more the latency around, but you can't ever really get rid of it.

# Answer
> 9 votes
Almost all high performance servers, MMORPG or not, use thread pools and multiple queues.

A sample design might look like this:

* On Windows, use IO Completion Ports to avoid requiring a thread per connection.
* When data is received, deserialize ("read") it into a new packet object. What I do is read the packet type (1 byte) and then use a dictionary/lookup table to find the object type. Once I have the type I use reflection to create the strongly typed packet object. I call a method on the packet to "read" the data from the stream.
* The packet, along with a "network session" object representing the connection are added to a global queue. When an item is in the queue a network dispatch thread wakes up and "routes" packets to.
* The packet router checks the type of packet. If it's a generic "network" packet (for example, "Ping"), it gets wrapped in a NetworkAction object and passed to the "network action queue". If it's a "simulation" packet (ie/ "Move Player") it gets wrapped in a SimulationAction object and passed to the "simulation action queue".
* The simulation action queue works the same as the network dispatcher - once an item is in simulation action queue a simulation dispatch thread wakes up and processes each message in the queue. In other words, only one thing at a time happens to a simulation, but multiple game simulations (ie/ regions, maps) can be loaded at once. Each simulation has its own queue.
* Rather than having one thread per queue or one thread per simulation, a thread pool is used. Threads are allocated as-required.

You might want to take a look at how IIS (Microsoft's Web Server) for Windows 2008/Windows 7 is architectured internally and use a similar approach.

* One "process" (http.sys in the kernel) listens on port 80. (MMORPG - your server process listens for new requests)
* Http.sys deserializes the packets as fast as possible, handling thousands of connections at once. (MMORPG - use IO Completion Ports and thread pools to read packets)
* Once enough information is known about the request (HTTP header) it passes the information to Windows Process Activation. (MMORPG - once you've read your packet, look at the packet and determine if it needs to be sent to the "game world" or handled directly. If it's a "game world"/simulation packet, toss it in a queue so that it can be "routed" to the correct simulation)
* Windows Process Activation determines which website should process the request. If a process is not running for the website, it starts one. If no one has used the website in awhile, it stops it. If the website crashes, it restarts it. Once the website worker process is ready, it passes the message to it. (MMORPG - Don't waste resources processing areas of the game world that don't have players. Determine where the packet should go, and if its an area of the world that is offline, start it up. Pass the packet into the "simulation action queue" - one for each simulation. Use simulations to subdivide your world - for example, one per map, one per region, etc)
* The website's worker process has a queue of all outstanding requests. It spins up a number of threads in a pool (~10-20) and once a thread is available, it passes the request to the thread. The thread remains blocked until the webpage is ready (ie/ read blog listings from database and generate HTML) and returns the content back to HTTP.SYS so it can be converted to a packet. (MMORPG - difficult to have multiple threads running in the world at once due to collision detection and entity graphs, but have one thread that processes items in the queue, perhaps using a priority queue).

I use C#, mainly because it simplifies most of what I described above. It has its own internal thread pools. Strangely enough, take a look at the Microsoft Robotics Platform. It has a component called the CCR - "Concurrency and Coordination Runtime" that makes it easy to build dispatch queues and multithread easily. They also have a service component that will route messages to services and start them as required.

The key point I'm trying to make is non-game services handle hundreds to thousands of requests per second on a single core machine with minimal CPU load. Games are more complex, but if you incorporate some of the same strategies it will go a long way. Just remember - keep it simple at first, get something working, and build out the complexity only when it's required.

---
Tags: mmo, server
---


# Question
Title: How can I pass an external instance to the constructor of an object that's being created using the default XNA XML content loader?
I'm trying to understand how to use the XNA XML content importer to instantiate non-trivial objects that are more than a collection of basic properties (e.g., a class that inherits from `DrawableGameObject` or `GameObject` and requires other things to be passed into its constructor).

Is it possible to pass existing external instances (e.g., an instance of the current `Game`) to the constructor of an object that's being created using the default XNA XML content loader?

For example, imagine that I have the following class, inheriting from `DrawableGameComponent`:

```
public class Character : DrawableGameComponent
{
  public string Name { get; set; }

  public Character(Game game) : base(game) { }

  public override void Update(GameTime gameTime) { }
  public override void Draw(GameTime gameTime) { }
}

```

If I had a simple class that did not need other parameters in its constructor (i.e., the `Game` instance), then I could simply use this XML:

```
<XnaContent>
  <Asset Type="MyNamespace.Character">
    <Name>John Doe</Name>
  </Asset>
</XnaContent>

```

...and then create an instance of `Character` using this code:

```
var character = Content.Load<Character>("MyXmlAssetName");

```

But that won't work because I need to pass the need to pass the `Game` into the constructor.

What's the best way to handle this situation? Is there a way to pass in things like the current `Game` using the default XNA XML content loader? Do I need to write my own XML loader? (If so, how?) Is there a better object-oriented design that I should be using for my classes?

Note: Although I used `Game` in this example, I'm really just asking how to pass any type of existing instance to my constructors. (For example, I'm using the Farseer Physics Engine, and some of my classes also need a reference to the Farseer `World` object too.)

Thanks in advance.

# Answer
> 5 votes
You want to load only the information about the character from the XML, and use that information in your character class:

```
public class Character : DrawableGameComponent
{
    public CharacterInfo CharacterInfo { get; private set; }

    public Character(Game game, string characterAssetName) : base(game)
    {
        _assetName = characterAssetName;
    }

    protected override void LoadContent()
    {
        CharacterInfo = Game.Content.Load<CharacterInfo>(_assetName);
    }

    public override void Update(GameTime gameTime) { }
    public override void Draw(GameTime gameTime) { }
}

//In your data-types project:
public class CharacterInfo
{
    public string Name { get; set; }
}

```

See this and then this blog post for more details.

---
Tags: xna, c#, xml
---


title: MMOs based on .Net?

text:
# Question
Title: MMOs based on .Net?
Are there any real MMOs where the server engine is based on .Net?

# Answer
RunUO and SunUO are free Ultima Online servers. Ultima Online client can be downloaded for free.

> SunUO is a free Ultima Online server for Linux/Mono and Windows.NET, based on RunUO. Ultima Online is a commercial MMORPG by Origin / Electronic Arts.
> 9 votes

# Answer
Photon Socket Server is a middleware provider which is using C++ as the underlying framework but the bulk of the logic (i.e. what you have access to) is using .NET.
> 6 votes

# Answer
Sorry, those are Russian games, but I assure you they're very real MMOs and have servers made with .NET. I worked on these servers myself, in fact (-8

Arena Online

Elements of war
> 5 votes

# Answer
I don't know of any commercial MMOs off the top of my head, but the NetGore Engine, the successor to the powerful vbGore Engine, is looking pretty good. NetGore is currently in very active development with a growing community.
> 3 votes

# Answer
Second Life runs (at least partially) using managed code. They run on MONO, which is a Linux port of .NET. It's possible they're just hosting .NET within C++ for the scripts, but they are running it at least partially.
> 2 votes

# Answer
Lord of the Rings Online's client uses .NET 1.1. Not sure about the server. I think Turbine's games (LotRO, DDO, Asheron's Call) use .NET.
> 1 votes

# Answer
I have no idea of the server side but the DDO client throws exceptions that look like .net when it crashes.
> 0 votes

# Answer
Vindictus server is fully written in .Net. Vindictus offers only one logical shard with hundreds of thousands of simultaneous users, which can be done via function and data distributed computing techniques.
> 0 votes

# Answer
I'm pretty sure that CCP Games uses some .NET components on their servers.
> -1 votes

---
Tags: mmo
---


# Question
Title: How to do smooth sprite movement on WP7 XNA
What's the correct technique for getting smooth sprite translations with XNA?

I've been developing the WP7 version of an app for a startup, so when we heard Angry Birds got ported today we wanted to check it out and compare. Angry Birds on WP7 had the sub-pixel blur problem with the bird sprites, whereas iPhone, Android, and Chrome all had smooth movement.

# Answer
> 5 votes
It sounds like they are accidentally rounding their sprite positions to the nearest pixel. This can happen automatically if you use the SpriteBatch.Draw() call that takes a Rectangle as the position of the sprite, since XNA's `Rectangle` uses integers instead of floats to represent position.

If sprites are drawn with integer coords, then sub-pixel rendering will not occur, and sprites will appear to snap from one pixel position to the next, instead of blending smoothly between them.

# Answer
> 2 votes
It could have to do with the framerate or it could have to do with the fact that xna does sub pixel rendering

---
Tags: xna, sprites, windows-phone-7
---


# Question
Title: the difference between diffuse texture and ambient occlusion texture
is there any difference between diffuse texture which used in diffuse lighting and ambient occlusion map, or this is the same texture just different naming, because i see it mostly it looked the same?

# Answer
The diffuse texture is the colour of the object without light effects. The ambient occlusion texture is a map that shows the shadows on an object if it was evenly lid from all sides (basically it tells us how much a factor ambient light should be on each position). You can also do ambient occlusion real-time, but that's more expensive.

Sometimes the diffuse texture and ambient texture are combined in one texture.
> 2 votes

# Answer
Yes. A "diffuse texture" is generally just a flat, plain color map. It's one of the oldest kinds of texture map still in widespread use today. An ambient occlusion texture map takes into account local effects of light sources (and is usually just comprised of magnitudes, not actual colors).

The Wikipedia page on AO has an image that illustrates the difference visually.
> 2 votes

---
Tags: textures, lighting
---


# Question
Title: What knowledge would I need to make a good simulation game
I have an idea for a game like theme park but don't know how simulation games are made.

I am not on my first game so I would appreciate constructive answers instead of "its hard, don't do it".

What I want is to know how simulation game mechanics are put together. I figure it would be heaver on the AI than normal games and not knowing much about AI would like to know some programming techniques I should look into for this style game.

Specific techniques please not just a book on AI.

What sort of architecture would be used? I guess it would have some sort of probability engine with pre designed events that are triggered based on the AI state.

Would it use a Finite State Machine (FSM) or be purely event driven?

Any information on how a sims game functions would be cool.

# Answer
> 5 votes
The source code to the original Sim City was released a little while ago. It may provide some limited insight (be wary that source code, in general, isn't the best educational tool, especially when used alone).

There's also these lecture slides on The Sims, as well as this article on a few "tricks" used in the Sims AI.

# Answer
> 0 votes
This is really, really wide-open. There are tons of ways to do it, including the ones you mentioned.

Personally, I would go with an FSM where each actor makes a decision, and then works towards that decision until it's done, impossible, or they are forced to change their mind for some reason. (Emergencies, etc.)

To add some more dynamic occurances, I'd give the actors needs and wants, and have them pick their next action based on those needs and wants, nearly sources to fulfill them, and a tiny bit of randomness.

Wants can even include peer pressure, which would have friends and families flock in a group instead of separating, and possibly make them consider the needs of others in the flock.

Some decisions (pathing) need to be handled constantly, but most can be handled when the scenario changes.

---
Tags: game-design, ai, simulations
---


title: 'Unblock' / 'Yellow Out' game questions

text:
# Question
Title: 'Unblock' / 'Yellow Out' game questions
I would very much like to build a game that is known as 'Unblock' or 'Yellow Out'. It is a puzzle game in which the task is to move a car out of a parking space by moving other cars in certain directions.

These are links where the game can be played:

My questions concerning this game are:

1. Is this game actually licensed? I see it's available under two names (perhaps even more). Does this mean the game idea can be used freely?
2. Is there an article about it? I have not been able to find it on Wikipedia. I would like to gather some information about the game so as to understand more details of it.
3. Is there some database with puzzles available? I can just check the puzzles of existing games, but that's a pain because I have to finish a level to get on to the following one. I was wondering whether there is a general list of puzzles somewhere.

Thanks!

# Answer
> Is this game actually licensed? I see it's available under two names (perhaps even more). Does this mean the game idea can be used freely?

I am not a lawyer and this is not legal advice; you should consult a lawyer for proper legal advice. That said, the idea itself for the game is unlikely to be protected in any capacity as it is very difficult to do so. What you want to avoid is copying the name, artistic assets, and probably the puzzles, of any other instance of this game that is out there.

> Is there an article about it? I have not been able to find it on Wikipedia. I would like to gather some information about the game so as to understand more details of it.

I don't think there is a whole lot of complexity behind the type of game. It's a relatively simple block sliding puzzle where the goal is to free some specific block from the play field. You aren't likely to find deep tomes of lore on such a simplistic concept.

> Is there some database with puzzles available? I can just check the puzzles of existing games, but that's a pain because I have to finish a level to get on to the following one. I was wondering whether there is a general list of puzzles somewhere.

You could look for solutions or spoiler guides for existing games (for example, all of the solutions for The Heist, an iOS game that has a sliding block puzzle mini-game, are available online. But I wouldn't recommend that because you'd then be copying their puzzles.

Instead you should invent your own. Use a different grid and different block sizes to help provide some uniqueness.
> 4 votes

# Answer
I'm not a lawyer so take my legal advice with that in mind, but I did make a version of this game. It's an Android game called Obstruction and I used it as a project to teach myself programming. I did not seek out any kind of licensing because, with so many clones available, it seemed that this wasn't an issue. I realized the puzzle doesn't have to use the usual 6x6 grid, so I made levels that are a little more abstract. Any shape works as long as it's made with right angles and the puzzle is solvable. I hand drew the designs for the 100 levels in my game, so I, personally, would recommend doing the same as opposed to copying other puzzles. Also, Obstruction has 7 different themes, none of which have anything to do with cars. The cars concept is what the very first game of this kind, Rush Hour, used and it's very over done. So my advice is don't worry about being the same, but try to be different.
> 1 votes

---
Tags: databases, licensing, puzzle, articles
---


title: 3D game on a planet

text:
# Question
Title: 3D game on a planet
Would it be much more work to create a 3D game on a planet rather than on a flat plane? What engines would support this and what techniques would I use?

An example would be a small sphere the player could walk around to get back where they started.

# Answer
> 15 votes
There's a nice article over at Gamasutra that explains the physics in Super Mario Galaxy, which is probably what you're looking for.

Basically they use the inverse surface-normal of the closest polygon underneath the player as gravitational force. If the player moves over to another polygon while in the air, they interpolate the normals to smooth motion and orientation of the player.

# Answer
> 5 votes
I don't think there are engines who specifically support this, but in general it's not all that complicated.

Instead of translating bodies purely linearly, you have to move it according to it's distance from the center of the planet, as well as depending on it's angle between the body-center\_of\_planet line and your coordinate system's axes.

# Answer
> 2 votes
If you just wanted simple wrap around, and didn't care about viewing the actual curving of the earth during game play you could simply:

Loop the game world like a planet (this may requires some fancy radial math for the position)

And for the map use a planet model.

---
Tags: physics, 3d
---


# Question
Title: How does OpenGL-ES 2 assemble primitives?
Two things I'm quite confused about.

1) OpenGL ES 2.0 creates primitives before the vertex shader is invoked. Why, then, does it not automatically provide the vertex shader the position of the vertex?

2) OpenGL ES 2.0 supports `glDrawElements()`, but it does not support `glEnableClientState()` or `GL_VERTEX_ARRAY`, so how can this call possibly be used to construct primitives?

NOTE: this is OpenGL ES 2.0, NOT normal OpenGL!

Thanks!

Resolution:

I think my confusion was stemming from the built in variable gl\_Vertex that some versions of GLSL support (according to some sources, I couldn't find this in the official documentation at http://www.opengl.org/sdk/docs/manglsl/) which gives you the position of the vector provided to the draw command. This isn't present in GL ES. Further, my code was't working, and as GLSL can be difficult to debug, I had no idea what was going on :)

In this case, using vertex attributes and passing the model-space location of the vertices and my transformation matrix allows me to transform the vertices correctly.

# Answer
1: Primitives are not "created" before the vertex shader is invoked. Primitive assembly is a part of the pipeline after the vertex shader executes. Using the parameter passed to glDraw\*, groups of vertex data output by the vertex shader are used to create primitives, which are then clipped, culled, and rasterized.

There is no "position of the vertex" attribute. That's because vertex shaders are *arbitrary code*. They take whatever attributes you want them to, and those attributes have whatever meaning your code desires them to have. If you want a position value as an attribute, name it `position` in your shader.

A vertex shader is required to output a position in clip-space, but how the vertex shader creates that data is up to the shader. It could do some matrix transforms on an attribute, which is the typical method. But it could also do more arbitrary things. Depending on the extensions available to you in your ES 2.0 implementation, it could fetch data from a texture to compute the position. It could use a Perlin noise function to generate the height for a height map. And so forth.

2: The functions you're looking for are `glEnableVertexAttribArrays` and `glDisableVertexAttribArrays`.

> this is OpenGL ES 2.0, NOT normal OpenGL!

It may as well be, since nothing you asked is different between desktop GL and GL-ES 2.0.
> 4 votes

# Answer
2) You must provide vertices using glVertexAttribPointer(). You can store vertices in system memory or in VBO.
> 0 votes

---
Tags: glsl, opengl-es2
---


# Question
Title: Shader effect similar to Metro 2033 gasmask
I was thinking about effects in games the other day and I was reminded of the Gasmask effect from Metro 2033. Once you put the gasmask on it blurred a bit in the corners and could ice up and even get cracked.

I assume that something like that is done using a shader. I have been experimenting a bit with game development, so far mostly playing with existing rendering engines and adding physics support etc.

I would like to learn more about this sort of effect. Can someone give me a simple example of a shader that would alter the entire scene like this. Or if not a shader then an idea on how it would be done. Thanks.

Edit : Include screenshot of the metro 2033 gasmask effect.

# Answer
It's a combination of full-screen effects. There are a few ways to render full-screen shader effects, the most common is to first render the scene (without effects) to texture. Then that texture and the effect shader is set and a fullscreen quad is rendered.

The blurring in the corners could be done with a refraction effect. A refraction texture controls how much the light should be bent for each texel in the screen buffer. Here is an example of a Unity refraction shader.

This tutorial (rastek) shows how to create glass and ice effects with DirectX 10/ HLSL.

The cracks look like transparent textures to me.
> 7 votes

---
Tags: shaders, graphic-effects, post-processing
---


# Question
Title: How can we match polygon data structure with a background image
I am referring to this fireball game.

The ball will collide with background, which is in polygon form.

I was wondering, how I can match my polygon data structure with the background image. Say, I had requested artist to draw me a polygon background. Then, how I can generate a polygon data structure to describe the polygon background image?

# Answer
> 3 votes
Your question may mean two diffrent things, and for both there is some solutions:

1. You have both the texture and the polygon and know you want to know how to store and draw your polygon. Storing a 2D polygon is a real easy job, you only have to store all the vertices in order in some array. and to apply a texture to your polygon you need equal number of vertices on your texture and the rest is done by the GameEngine. remember points on the texture and on your polygon should have same order.
2. You have some texture and you want to extract vertices/edges from it. This one is a much harder problem but still it's solvable. First of all I would rather force my artist to give me polygons for the shapes he is drawing as well but maybe that's not possible so here are the steps to generate vetices/edges from a raw image. let's assume you can easily check if a pixel is a part of shape or not. So for the above picture before it's cut we have some picture like this :

using edge detection algorithms you can get to this final image (all lines have one pixel width):

now you can select some black pixels as vertices and then create your polygon using them.

---
Tags: android, collision-detection
---


# Question
Title: How can I test different TV display types for my XBLIG game?
The XBLIG submission check-list asks to ensure all gameplay-critical graphics be visible in the 'TitleSafeArea'.

I've received a bug report during play-testing that says parts of my scrolling 2D map are only half-visible (chopped off from the left of the screen).

I've tested the game on a 47" TV and a 19" VGA monitor and both look fine. However, the bug report says the issue occurs on a standard 20" TV.

How can I test different sizes without buying differently sized TVs?

# Answer
> 5 votes
Take a reasonably good 4:3 LCD *monitor*. Put electrical tape, or some other opaque tape, over the left/right/top/bottom 5% of your screen. Put scotch tape, or some other semi-transparent tape, over the next 3% of your screen. (So a total of 8% on all sides is covered.) Now do the same thing with a reasonably good 16:9 LCD *monitor*, but cover 5% on the left/right with scotch tape - so 8% on top/bottom, 10% on left/right.

You now have two serviceable approximations of crappy TVs - the very edges are completely covered, and some amount beyond that is visible but too blurry to contain text or other detailed graphics.

For extra credit, implement that effect in your rendering engine to save yourself some tape.

One myth I've heard repeatedly about overscan/safe areas is that HD TVs don't have them. That's not true. All HD CRTs have overscan areas and many LCD and plasma models do as well. Some don't but will simulate overscan for non-HDMI/DVI/VGA input, including HD Y'PbPr ("component") input. I suspect this myth exists because most people hook up their HDTVs using HDMI or VGA.

Another myth I've heard is that the title-safe area is a fixed size, e.g it's always 2cm from the edge, or it's always 50 pixels from the edge, so it's proportionately smaller on large or HD TVs. That is also not true. Safe areas are generally proportional to the TV size, and that size is fixed regardless of the resolution the screen is displaying - they're a physical property of the TV screen, or simulated as such. I suspect this myth exists because higher-end and newer HDTVs do have smaller unsafe areas.

# Answer
> 2 votes
Orthogonal to your question, but; when playing on a television, many games will have the user resize the drawing area *(ie. "resize the screen using the joystick until these four white squares are at the corners of your screen")* when the game starts up for the first time. Make sure they can access it again later, in case they get a new TV.

# Answer
> 2 votes
Generally speaking you should design your game so that anything which *has* to be seen is drawn within the bounds of the TitleSafeArea, not the Viewport itself. You can find the size of the TitleSafeArea using the TitleSafeArea property of Microsoft.Xna.Framework.Graphics.Viewport structure. The size of the TitleSafeArea rectangle will change for different displays and platforms.

Without testing every size, type and model of TV ever made, you can't know that anything drawn to screen coordinates outside this TitleSafeArea will actually be displayed for a given user. On the other hand, you can be reasonably sure anything drawn inside this area will be displayed.

# Answer
> 1 votes
Many CRT TVs are not perfectly rectangular. They have pixels on the sides and top that are cut off at the sides. Typically the 80% inner portion of the screen is guaranteed to be safe.

On HD resolutions it will most likely to have 0 to 5% missing of the screen area.

**In your game engine, add some temporary guides so you can align all the critical parts in the viewing area, and test at all the resolutions that you need to support.**

Even if your screen is wide, and the aspect ratio is wrong on it, your guides will be able to help you adjust it.

---
Tags: xna, xna-4.0, hardware, compatibility
---


# Question
Title: Any learning/studying material for C/C++ that use game programming as learning context out there?
As most of game programming is done - I read on this very site - in C/C++ I was wondering if there is any learning/studying material for C/C++ that would target specifically game programming.

I am not looking for material about "developing games" or "software architecture for games", but rather for **material that uses "game programming" as the CONTEXT for introducing and illustrating C/C++ features, idioms, programming techniques, etc...**

With a simile: think to the GOF book on design patterns. There, they used "developing a text-editor" as a context for introducing design patterns, but the book is most definitively not a book about "developing text-editors".

**EDIT:** The book should contain code examples that are not dependant on proprietary technologies (e.g.: it should use OpenGL rather than DirectX, a dialect of C known to gcc rather than needing a specific commercial compiler, etc...)

Thanks in advance for your time and advice!

PS: My background: I am a programmer with a solid experience in OO scripting languages and only some experience in C and Assembler (on AVR microcontrollers), so I am thinking to mid-to-advanced level material, rather than tutorials for beginners, although it might be interesting to take a look to the latter ones if nothing else is available.

# Answer
There's Beginning C++ Through Game Programming..I found it to be a good book. All the examples it works on are small, text-based games.

If you're talking more advanced, I haven't seen anything like that.
> 6 votes

# Answer
There's C++ For Game Programmers but maybe Game Coding Complete will be a better match (although it does not focus on C++ only but there are some good chapters on C++ specific problems).
> 3 votes

# Answer
I really enjoyed this book

http://www.amazon.co.uk/Beginning-Game-Programming-Jonathan-Harbour/dp/1598632884/ref=sr\_1\_14?s=books&ie=UTF8&qid=1309350818&sr=1-14

this starts with windows programming then direct x in 2d then 3d.

a brilliant book to follow Beginning C++ Through Game Programming
> 1 votes

# Answer
Here you go: 20 online lessons. It starts from "zero", but you can skip/skim the beginner parts. Also perhaps the school offers more advanced material.

# Introduction to C++ with Game Development<br>

### Learning C++ in the context of game development

> Welcome to the first article of Learning C++ tutorial series, provided by the IGAD program of the NHTV University! These tutorials are designed to take you from zero to block 3 entry level of IGAD's program in a somewhat smooth fashion. We start at the absolute basics: all that you need to get started is some decent equipment, a fair bit of time, and quite a bit of dedication.

...

> A quick blurb about us: IGAD stands for "International Game Architecture & Design". We are a Dutch accredited course for game development, ran almost exclusively by teachers with game industry experience. We started in 2005, and so far, it's awesome. About the authors

...

> This tutorial is written by Jacco Bikker, Brian Beuken, Nils Deslé, and Carlos Bott. Look us up on the internet to find out about we did and still do related to games development.
> 1 votes

---
Tags: c++, architecture
---


# Question
Title: vector collision on polygon in 3d space detection/testing?
In the 3d fps in java I'm working on, I need a bullet to be fired and to tell if it hit someone. All visual objects in the game are defined through OpenGL, so the object it can be colliding with can be any drawable polygon (although they will most likely be triangles and rectangles anyways). The bullet is not an object, but will be treated as a vector that instantaneously moves all the way across the map (like the snipper riffle in Halo). What's the best way to detect/test collisions with the polygon and the vector. I have access to OpenCL, however I have absolutely no experience with it. I am very early in the developmental stage, so if you think there's a better way of going about this, feel free to tell me (I barley have a player model to collide with anyways, so I'm flexible with it).

Thanks

# Answer
You will probably want to define the types of polygons that you support. The easiest would be triangles since they can be rendered by OpenGL, and they also have a wealth of literature on the topic of "Ray/Triangle Intersection".

Once you pick your set of supported shapes, you will need to implement the required Ray/Shape intersection tests for each shape.

Assuming you are there, and that you implement a method for shape that is: `double GetIntersectionT(Ray r)` \- Returns `-1.0` if the intersection test fails.

You iterate over all of your scene shapes (Yes there are spatial partitioning schemes, but you obviously aren't there yet), and call this method on each of them. Store the smallest **positive** result along with the shape that returned it. Once all shapes have been tested, you know the first object to get hit.

The beauty of this method is that it also allows you to constrain T in such a way that you can ignore shapes that are too far out if you wanted to.

Also, if you are asking how to do this with OpenGL, you should know (At least this is as much as I know) that OpenGL is **only** a rendering engine, and not a physics engine (what you are trying to build), and therefore you will need your own API to test these things.
> 1 votes

---
Tags: java, first-person-shooter, lwjgl
---


# Question
Title: Algo for given an amount of XP, find a character's level
In a RPG context, what are the ways to quickly find a character's level, given his XP? There are two cases which I am looking at:

1. For when a formula is defined, like in the case of D&D, which is N = N\*(N-1)\*500, where N is the desired level.
2. When no formula is defined, each level has an amount of XP require which is defined by a table.

I guess the easiest way is to do a for loop and subtracting the XP required for that level from the character's XP pool, till he reaches a point where you can't attain the next level. What other ways are there to, given a character's XP, to find his level?

**Edit:** The language is PHP

# Answer
> 28 votes
You're asking the wrong question.

The right question is "will this ever be a bottleneck in my game". The answer to that, I can nearly guarantee, is "no". It will not be. You can implement this in the simplest most braindead manner and it will never use more than 0.01% of your game's CPU, most likely vastly less than that.

Loop through levels 1 through MAX\_LEVEL, find the first level with a higher XP requirement than the player has. There ya go.

You're making a game, not a technology showcase. Make it work, don't agonize over every cycle.

# Answer
> 10 votes
The RPG I worked on stored both the level as well as the current percentage to next level, instead of just a raw XP amount on the player. We did this so that if we ever wanted to change the values in the experience tables, the player wouldn't see a sudden drop or rise in level.

For instance, imagine your player has 1000 XP, which is enough to make him 50% through 3rd level. If we were to suddenly make it so that 1000 XP is actually only 90% through 1st level, the next time the player plays the game you would need to level the character back down to 1st level.

As experience is earned, you can add the percentage amount of experience to the player's current XP percentage. Most RPGs are actually designed so that the amount of experience given for an encounter is easily converted to this percentage. If the percentage is ever greater than 100%, increment the level of the player, subtract 100% away from the experience, and for the extra amount over 100% give them something like:

```
currentXPPercentage = ((Amount over 100%) * (Amount over 100% * Total XP for Previous Level)) / (Amount over 100% * Total XP for Previous Level)

```

...in the end, if you did it that way you'd be storing the player's current level. Yay for no for loop to determine players level.

# Answer
> 4 votes
If the formula is defined, just invert the formula to find the xp-to-level conversion. If you can't invert the formula, then use a binary search to find the level. This assumes that more xp always correlates with a higher level, but I think this is a safe assumption for most levelling systems :)

If you have a table instead (and you are using C++) then you can use `std::lower_bound` to find the corresponding level for XP:

```
const int numLevels = 6;
int xpForLevel[numLevels] = {100, 200, 400, 800, 1600, 3200};
int* it = std::lower_bound(xpForLevel, xpForLevel + numLevels, xp);
int level = it - xpForLevel;

```

This will work in O(log(n)) time for n levels, so it's fast enough for pretty much any use.

Note, if the given `xp` is less than that required for the lowest level, then `lower_bound` will return `xpForLevel + numLevels`.

If you want to find the XP required for the *next* level up, use `upper_bound`.

# Answer
> 3 votes
> 1. For when a formula is defined, like in the case of D&D, which is `Experience = Level*(Level-1)*500`

I agree that you should implement what is easiest, rather than worrying about performance, because cases like this will have little or no performance impact either way. However, in this case, it would be easier to just solve the equation for `Level` using high-school algebra, rather than take the time to code a lookup table as suggested by everyone else.

That specific equation can be solved using the quadratic formula.

# Answer
> 1 votes
Why not use a keypair dictionary to save the level and experience points needed for a given level. Then when you want to find out the level according to experience just ask if the current XP is higher or lower from the closest keypair value.

Once you reach a point where the value is right between two keypairs you know what level you are.

---
Tags: algorithm
---


# Question
Title: In a GUI, should input be handled when the button is pressed or released?
In the menu system for our game (selecting levels, options, etc.), the player presses the a button on the gamepad to go to the next screen. I coded the menu system to wait until the button is released before taking any action (i.e., displaying the next screen). Some recent playtest feedback suggested that we do it the opposite way: take action as soon as the button is pressed. I am curious, what is the standard way this is handled, and does it even make a difference?

# Answer
> 33 votes
In a game which is controlled by a gamepad, where control inputs directly change GUI focus from one GUI button to another, those GUI buttons should be activated when a controller button is *pressed*.

In a game which is controlled by a mouse (or if a gamepad is used to move a virtual mouse cursor around the screen), on-screen buttons should be activated when the mouse/controller button is *released* over the same button on which it was *pressed*. (If the press occurred over one GUI button, and the mouse was then moved, and released over a different GUI button, neither GUI button is activated)

The reason for this is that people's mouse control skills are highly variable, and often people have a little trouble positioning the cursor exactly where they want it, or even telling precisely which GUI button they're hovering over at the moment. The theory is that people can press and hold the mouse button to make the GUI button highlight, and if that GUI button wasn't the one that they intended to use, they can move their cursor away from it before releasing the mouse button in order to avoid pressing it.

But if your game is being controlled by a gamepad, then you absolutely want to take action when the gamepad button is pressed, not when it's released.

**Edit, five years later:**

In the time since this answer was posted, a new standard has begun to emerge for handling mouse-style cursors which are controlled by gamepads.

In the answer above, I suggested that these should be implemented to work exactly like cursors which are actually being controlled by mice; highlight on mouse-down, activate on mouse-up if the cursor is still over the same GUI element.

But now, gamepad-controlled cursors typically activate a GUI action after the gamepad button has been **held down for a period of time** (typically about one second). If you're going to follow this system, you'll need to have an on-screen indicator showing how long until activation will occur (often this is a little ring around the cursor itself, which fills up as you get closer to activating the hovered-over button), and you still need to highlight the element which will be activated, during the time that the button is being held down (and it might be a good idea to do that any time the mouse is over an element, even if the button isn't being held). While the button is being held, the cursor should not be able to be moved, in order to avoid accidental activations of GUI elements if the cursor is jostled at the last moment.

The benefit of this system is that it allows a user whose mouse-style cursor is over the wrong spot to avoid activating that element by just releasing the button early; the mouse-style "move away from it before you release" is less natural to accomplish on a gamepad than with a mouse, and this approach allows a gamepad user to abort an unwanted click far more easily.

We're even starting to see a few games experimenting with this cursor interaction model even when their cursor is being moved by a real mouse. No Man's Sky does this, as one example. It will be interesting to see whether this approach to handling mouse-cursor interaction will become increasingly common and expected over the coming years.

# Answer
> 1 votes
I'd take action as soon as the key is pressed.

The best example where the action took place after the key was released was in Starcraft: Broodwar. When I would press the keys very quickly, I would often press the next key before completely releasing the previous one which led to some commands being ignored. (1A Click, 2A Click, 3A Click - the 2 would be ignored)

This was changed in Warcraft III and the game felt a lot more responsive to me as a result and I never had the 'sticky control group' problems from Broodwar.

---
Tags: input, gui
---


# Question
Title: Using a shader messes up my alpha in XNA
I'm making a 2D game that ends up being too dark on some laptops, so I figured I'd use a shader so people could brighten it up if need be. Unfortunately, once I got it in there nothing would fade in or out, they'd just pop in and out.

Here's my FX file

```
float intensity;

sampler TextureSampler : register(s0);

float4 Glow(float2 texCoord:TEXCOORD0):COLOR0
{
    float4 Color;
    Color = tex2D(TextureSampler, texCoord.xy);
    Color.rgb *= intensity;
    return Color;
}

technique Technique1
{
    pass Glow
    {
        PixelShader=compile ps_2_0 Glow();
    }
}

```

Even after commenting out the `Color.rgb *= intensity;` line it still removes all fading effects.

I'm using the sprite batch to draw, and I begin and end it a few times because I use different BlendStates

```
brightnessShader.Parameters["intensity"].SetValue(brightness);
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
...
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, null, null, null, brightnessShader, Matrix.CreateScale(scale));
....
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
...
spriteBatch.End();

```

I'm using XNA 4.0.

# Answer
> 6 votes
`SpriteBatch` passes in both a colour (containing an alpha/transparency value) and a texture coordinate. You need to use the colour parameter. Here is the XNA `SpriteBatch` pixel shader (from XNA 2.0)

```
void SpritePixelShader(inout float4 color : COLOR0, float2 texCoord : TEXCOORD0)
{
    color *= tex2D(TextureSampler, texCoord);
}

```

So your shader would need to be something like this:

```
void SpritePixelShader(inout float4 color : COLOR0, float2 texCoord : TEXCOORD0)
{
    color *= tex2D(TextureSampler, texCoord);
    color.rgb *= intensity;
}

```

Also be aware of premultiplied alpha, which was added in XNA 4.0. Simply multiplying the RGB values may give you a result that is different to what you actually want to achieve.

Probably a better solution to your problem would be to render your entire scene as normal to a render target, and then gamma-correct that render target using a post-process pixel shader.

# Answer
> 1 votes
If your source bitmap is compressed with DXT1 you'll only get 1bit of alpha, on or off. DXT3 is a little better with 4bit so 16 total alpha values.

---
Tags: shaders, xna-4.0
---


title: OpenGL Performance Questions

text:
# Question
Title: OpenGL Performance Questions
This subject, as with any optimisation problem, gets hit on a lot, but I just couldn't find what I (think) I want.

A lot of tutorials, and even SO questions have similar tips; generally covering:

* Use GL face culling (the OpenGL function, not the scene logic)
* Precalculate anything you can
* Use interleaved Vertices
* Minimize as many GL calls as possible, batch where appropriate

And possibly a few/many others. I am (for curiosity reasons) rendering 28 million triangles in my application using several vertex buffers. I have tried all the above techniques (to the best of my knowledge), and received almost no performance change.

Whilst I am receiving around 40FPS in my implementation, which is by no means problematic, I am still curious as to where these optimisation 'tips' actually come into use?

My CPU is idling around 20-50% during rendering, therefore I *assume* I am GPU bound for increasing performance.

**Note:** I am looking into gDEBugger at the moment

Cross posted at StackOverflow

# Answer
as far as I know those are good optimization techniques but since new GPUs are beasts in matrix vector operations, maybe in your case you need to use more effective optimization techniques for example you may use frustum culling , dynamic level of detail ,occlusion culling, try to minimize state changes by sorting (you can also sort based on shaders ), minimize copying from/to GPU memory.
> 5 votes

# Answer
28 Million triangles at 40fps is 1120Million triangles/sec. This is pretty close to peak rates for top end graphics cards (what are you using?), so it wouldn't surprise me if you are simply limited by the clipping or setup hardware max throughput. The only way to get faster is to draw less triangles.

For your specific questions: •Use GL face culling (the OpenGL function, not the scene logic)

The hardware can avoid rasterization of invisible on-screen clipping. Helps most when your geometry is on screen and you are raster limited (or limited by memory bandwidth, or z-test performance). Turn it on (assuming you have closes/2-manifold objects).

•Precalculate anything you can

As someone said in another answer, you have more triangles than pixels. You may have all sub-pixel sized triangles, but more likely the triangles are either overdrawing each other on the screen, or they are off screen and clipped. For the former, you can look into occlusion culling techniques (occlusion queries, visibility pre-processing, z-pass rendering, front to back rendering, etc.). For the latter, you should group spatial coherent triangles (i.e., compact objects) into some sort of spatial hierarchy (be it an octree or a simple bounding box per object), and manually reject chunks of triangles on the CPU, in order to avoid even making the draw calls for those objects.

•Use interleaved Vertices

What is this? Are you referring to tessellation?

•Minimize as many GL calls as possible, batch where appropriate

This is a benefit if you are CPU limited. BTW, are you sure that no core is running at 100%? All it takes is one to become likely CPU limited. The taskmanager reports the idleness of ALL cores.
> 5 votes

# Answer
Look into macro-optimizations.

* Don't render details you don't notice anyway. Sounds obvious? Well, if your game is a spacesim, an optimization could be scaling the level of detail, where you have different models for different distances. If your game is a closed-quarters first person shooter, you can use a BSP tree to only render the rooms that are in range.
* Removing duplicate calculations. Animations can be shared and textures can be pre-blended.
* Is the bottleneck in lighting? You could try reducing the number of lights or even do lighting deferred. Is the bottleneck in shader code? Try simplifying them and hardcode values.
> 3 votes

# Answer
You will probably not get any further without serious GPU profiling. gDEBugger is indeed an excellent start. However, chances are that your design is simple enough that you are indeed maximising the GPU's capabilities.

I also strongly suggest you start thinking about simplifying the geometry, for instance with LODs. At the moment you have 10 to 15 times more triangles than real pixels on the screen. That doesn't make much sense to me. You should start thinking about which triangles could be merged or even completely removed.
> 2 votes

# Answer
You can also explore some data types and traffic optimizations - you can for example use half float instead of float (if you don't need really accurate positions). If it's not enough and you want to decrease traffic, you can use ARB\_vertex\_type\_2\_10\_10\_10\_rev, which is even smaller (4 coordinates - xyzw - in 32 bits).

If you have more models with few vertices (few indices), you can also use ARB\_draw\_elements\_base\_vertex (you can find some material here), you can send unsigned short or byte indices instead of unsigned int (you will save 3/4 or 1/2 of its size).

If you have more VBOs and you frequently use glBindBuffer, you can use NV\_vertex\_buffer\_unified\_memory (there is also example on that site).

These OpenGL extensions don't increase performance too much if you have just few vertices, but you have a lot of triangles, so it could be worth a try.

There is also more such extensions, like Vertex array range. You have to search.
> 2 votes

---
Tags: opengl, c++, performance, optimization, sdl
---


title: Render rivers in a grid

text:
# Question
Title: Render rivers in a grid
I have created a random height map and now i want to create rivers. I've made an algorithm based on a\* to make rivers flow from peaks to sea and now i'm in the quest of figuring out an elegant algorithm to render them.

It's a 2D, square, mapgrid. The cells which the river pases has a simple integer value with this form :rivernumber && pointOrder. Ie: 10, 11, 12, 13, 14, 15, 16...1+N for the first river, 20,21,22,23...2+N for the second, etc. This is created in the map grid generation time and it's executed just once, when the world is generated.

I wanted to treat each river as a vector, but there is a problem, if the same river has branches (because i put some noise to generate branches), i can not just connect the points in order.

The second alternative is to generate a complex algorithm where analizes each point, checks if the next is not a branch, if so trigger another algorithm that take care of the branch then returns to the main river, etc. Very complex and inelegant.

Perhaps there is a solution in the world generation algorithm or in the river rendering algorithm that is commonly used in these cases and i'm not aware of.

Any tips? Thanks!!

# Answer
This tutorial/game dev blog provides an excellent method for generating rivers, and they render very nicely. I'm not sure if this can be applied effectively in your situation, as you've taken a different approach (and have a grid-based map) but it's worth looking into, for sure.
> 1 votes

# Answer
One thing you could do is have each individual node handle itself. Make a pass over it when after generation but before displaying and give each river square a list of entrances (lower number, same river) and exits (higher number, same river).

From this data you should be able to figure out where the entrance(s) and exit(s) are (storing relative location would probably help) and you can from there render that square's river based on the connections. The simplest way to do a branch is to connect the entrances/exits to the center of the square.

The graphical representation of this could be taken many different ways, and you haven't given enough information about it's use for me to recommend one directly; so instead I will just mention *a* way involving a particleish system where each segment of water flows dynamically "downhill".

Have the root square start some number of "water pieces" at each of it's entrances and have them randomly decide from the available exits at creation. When it hits the exit, spawn one at the tile it hit's entrance and return the water piece to the start of it's square. Since it has already spawned into the next square (only do this once per piece in a square), and you already know the settings and calculations (don't re-randomize), you can let this piece loop in it's square with very little calculation, and if you wanted, likely using a shader.

This has the advantage of also letting your rivers go to smaller rivers after branches, and the two resulting rivers do not have to be the same size. It will take a moment for the river to populate fully from the top to the bottom, but the resulting effect should be rather pleasant as you could end up with something like this simply based on which nodes have rivers.

```
10--10--6--6--2--2
    |      |
    4--4   4
       |   |
       4---6--6--6
       |
       2

```

It would also, depending on seed and code, have the potential to look different each time you ran it, even if the node placement was the same.

Hope this example is somewhere along the lines you are looking for.
> 0 votes

---
Tags: algorithm, procedural-generation, terrain-rendering
---


title: Casting ray from 2D to 3D

text:
# Question
Title: Casting ray from 2D to 3D
As an exercise in trying to learn 3D math, I've been experimenting with hit-testing by casting a ray from 2D screen space into 3D world space. My first attempt was as follows:

```
Matrix m = Matrix.Invert(
    this.scene.Camera.ViewMatrix *
    this.scene.Camera.ProjectionMatrix *
    homogeneousToViewportTransform());
Vector3 rayOrigin = Vector3.TransformCoordinate(new Vector3(p.X, p.Y, 0), m);
Vector3 rayVector = Vector3.TransformCoordinate(new Vector3(0, 0, -1), m);

```

This gets the ray origin correct, but not the ray vector. My reasoning was that the vector \[0, 0, -1\] is facing into the screen when in screen space, so transforming that into world space would give the correct vector. But that doesn't seem to be the case. Looking around, I've found that the correct way to calculate this is by doing:

```
Vector3 rayVector = new Vector3(
    m.M31 - (m.M34 * rayOrigin.X),
    m.M32 - (m.M34 * rayOrigin.Y),
    m.M33 - (m.M34 * rayOrigin.Z));
rayVector.Normalize();

```

Can anyone explain what's wrong with my original reasoning, and what the actual algorithm for calculating the ray vector is doing?

# Answer
> 6 votes
*EDIT*

Please note that the following answer does not take into account several things, and is more of an attempt to visualize differences in picking between parallel and perspective projection, and probably not a great one at that. Please read all the comments for more details.

*-----------------------*

I believe that your original reasoning would be correct if you were using parallel projection. But since (I believe) you're using perspective projection, it doesn't work.

Imagine you have two planes that are perpendicular to the camera (both facing the camera). The green plane is closest and the red plane behind that. From the camera view it looks like this:

Now when I cast a ray out to the black dot, to do so correctly in perspective projection, I have to cast from where my camera is (which is the sharp point on the left) out to the dot. That's what the extra math does when creating the vector for the ray.

If I were to do the same in parallel projection, I can pretend that my camera is not a pin-point, but a huge plane. Here is where I can use the vector\[0,0,-1\]:

Here's the same view as the top image, but in parallel projection.

Anyway I'm pretty sure that's your issue. It's not a mathematical answer, but I hope it helps you understand the difference in what you were thinking and how it's supposed to work. There is of course the Math SE that you could get more details on the math.

# Answer
> 2 votes
Assuming you have a good understanding of how a point is transformed, the difference is that a vector is always defined as the vector to a point relative to some point of reference (e.g., the origin). When you transform the point to which a vector points, the point of reference is not transformed with it, so the vector changes and you get incorrect results.

To transform the vector v by matrix M as you would expect, transform M(v), and the point of reference/origin M((0,0,0,1)) (i.e., the - vector). Then compute M(v) - M((0,0,0,1)) to get the correctly transformed vector. Obviously, transforming by M((0,0,0,1)) zeroes out most of the components of a matrix, so you land up with just the translation components remaining and the matrix homogenous component, which with some minor math transforms into the code you have as a fix.

# Answer
> 0 votes
Perhaps this would be of use? It's (probably the best) article on mouse picking.

# Answer
> 0 votes
Long ago I developed an multiprocessor raytracing renderer for an old supecomputer in my college.

I addressed this problem by defining an observation point and the screen plane in world coordinate. The screen was defined as the coordinate for the upper-left pixel in world coordinate and the *U*, *V* direction pointing toward the left and lower pixel respectively.

In this way the pixel (x,y) is centered on *P* \+ x·*U* \+ y·*V*.

If the view point is *W* then you can cast a ray *W* \+ (*P* \+ x·*U* \+ y·*V*)·t that is in world coordinate.

I think that in your case the trick is to put the screen in world coordinate i.e. find the coordinate for the top-left, top-right and bottom-left pixels. With those vectors and the world coordinate view point you can cast a ray through any pixel and rely in a world coordinate parametric formulation.

---
Tags: 3d, mathematics
---


# Question
Title: When and how should I apply forces in a Cocos2D + Box2D game?
I have some small circles just rolling across the bottom of the screen in my Cocos2D/Box2D iOS app. The bodies are dynamic... so I make them roll by applying a horizontal force to the center of mass (when the linear velocity is below the max velocity).

Currently I apply this force in `-(void) tick: (ccTime) dt`. Is this the best place to apply it? Or should I subclass something and implement an update function somewhere? Please keep in mind I'm very new to Cocos2D/Box2D.

# Answer
> 3 votes
To achieve a *constant acceleration*, apply a force every frame some time before you call `b2World::Step`. To achieve *constant velocity* (in the absence of friction and damping), apply a force for one frame.

You should definitely not be subclassing anything in Box2D. None of its classes are designed to be base classes. You can subclass CCNode/CCSprite/etc. to help manage your b2Body pointers.

Incidentally, applying a force to the exact center of a circle will cause it to slide, not roll. To roll, apply the force above the center.

# Answer
> 1 votes
The `tick` method is called on every frame. So this is actually what you call your `update` function.

So calling the apply force method in the tick method is right, since the force has to be applied continuously (every frame) to make the object move.

As a contrast you could try the apply impulse method that accelerates your object. But you should not call this method in the tick method because the impulse would be added many times.

---
Tags: physics, box2d, cocos2d-iphone
---


# Question
Title: How to create a camera hack for a Torque 2D game?
first I’m not programmer, I’ve been using a popular game for some time and I think it would make a great medium for machinima. Problem is that it’s a top down view startegy game and it doesn’t give control of the camera other than pan map with arrow keys, drag with left mouse and zoom on cursor with mouse wheel.

I’ve got the demo of Torque 3D and I found the documentation on creating different camera modes but I don’t want to spend hours to find out in the end that I can’t do it.

Ideally I’d like a console command to switch between the default camera mode and the machinima one. The machinima one should focus on the centre of the map OR (toggle) on a selected unit and basically let me rotate the map like a sphere but never get below it or alter its horizontality. (hope you get the picture)

So can anyone write me the code to add ?

EDIT: I just learned that it uses Torque 2D but renders things in 3D.

# Answer
> 0 votes
I find myself confused by your question. So you want to use a "popular game" that is a "top down view RTS game" for machinima. But it doesn't give you enough camera controls.

That's fine. Where it gets confusing is where you start talking about Torque 3D. The document you found pertains to Torque 3D users and possibly games made with Torque 3D. And I don't know of any "popular" RTS game that was made with Torque 3D. So the fact that Torque 3D has the ability to create camera modes has *nothing* to do with this anonymous RTS game.

If the game itself does not give you camera controls, whether directly or via scripting, then you don't have camera controls, period.

BTW, if you're talking about StarCraft 2, just *say* so; Blizzard's wrath will *not* be upon you. Also, SC2 has lots of camera controls in its scripting system; people have made third and first-person shooters in the engine. I could point you to all kinds of SC2 map editing resources you could use to make Machinima if I knew what game you were talking about.

---

I wanted to know what game it was so that I could go look it up. And now that you have revealed that it uses T2D instead of T3D, what you want is simply impossible. T2D renders 3D objects the way it renders sprites: each one has its own space. There isn't a global camera for T2D unless the game creates that concept itself. And if it does, that global camera can only be changed via a mod if the developer specifically exposes it.

---
Tags: camera, torque
---


# Question
Title: Stitch a collection of images into a tileset
I have a number of tiles as standalone files that I would like to stitch together into a single tileset. Are there any tools that can quickly do this?

# Answer
I like Texture Packer. http://www.texturepacker.com/
> 1 votes

# Answer
ImageMagick has a useful append command that does exactly what you want.
> 3 votes

# Answer
use http://slick.cokeandcode.com/demos/packer.jnlp.
> 1 votes

---
Tags: tiles
---