# Question
Title: A simple map, four biomes, and how to distribute them
Here's the basic idea: I've got a Rogue-ish, perhaps Dwarf Fortress-ish game, with a randomly generated overworld and several dungeon entrances scattered around it. I already have the dungeons *basically* covered, but I'm stuck on an aspect of the overworld.

Said overworld, considered as a 2D map of screens, should have a perhaps blob-like distribution of four different themes or biomes -- grasslands, desert, snow and swamp, each with their own total amount of screens. Let's say the map is 8x8, which gives 64 unique screens. Half of those could be grasslands, a quarter desert, and swamp and snow get a quarter each:

It seems palette reduction has made snow the same color as swamp. Originally, there were eight snow screens in the bottom corner, and a slightly staggered eight-screen swamp area in the middle. Sorry 'bout that, and please ignore the location markers.

The best I could get was some snaking shapes, and often enough with nonsensical combinations like desert snaking through snow (or vice versa). I can't for the life of me figure out how to get it nice and blobby, let alone having it make climatical (?) sense. So how do I generate a biome map like in the mockup?

Okay, by request: the world really isn't much bigger than that example, and what I need is just a way to spread some blobs that determine thematic appearances, with the extra limitation that snow can't touch desert. Screens don't scroll, and if a screen is set to "desert", there'll be no grass anywhere on it.

# Answer
There are many ways to skin this cat, however one of the more interesting is using cellular automata. Begin with your empty grid and add a few seed starting cells in random locations. These should be of some basic non-mixed types of biomes. Say: Grass, Desert, Snow, Ocean.

Based on growth rules of your own design, which could feature some randomness (I don't care that it technically breaks the idea of CA, do you?) have them grown each step into the map. Additional rules can be such that if you are ocean and are next to grass or swamp, you might turn into swamp. If you are next to snow, you may become ice, if you are near desert, you may dry up and become desert too.

The same might be true for other mixes, and in theory even sub-mixes like frozen swamp, or tundra, or jungle sprouting from large expanses of forests that grew from large expanses of grassland.

The possibilities are endless, and can also be continual. As these rules are all simple, you can implement environments that shift over time. Combined with height information, and rules that take it into account, you can grow lakes and rivers, block the growth of forests over mountains and other fancy things.

That height map can be the result of perlin noise, or diamond square, or even whole other CA models. In fact, you could modify that map as time goes on as well by modelling plate tectonics, pushing up mountains, sinking in trenches, and even let rivers lower the landscape creating canyons.

This rabbit hole extends forever.
> 8 votes

# Answer
Short answer but you should really check this article out- www-cs-students.stanford.edu/~amitp/game-programming/polygon-map-generation/ It explains one algorithm on the generation of the random generation of dry land and biomes based on designated humidity zones and altitude regions. But in your case, just set your own values for the distribution that you want.

**(big edit)** I will make this a much more clear for what map-generation concepts you need to apply. Use a coordinate system with 1 unit per screen, in floating point values. Generate a small random set of points within these coordinates, as if you were making a Voronoi diagram but we won't actually make the random shapes. Instead the diagram will be *implied* and approximated by the map after the biomes are set.

Each point is the center for each biome area. Set your own rules to associate a point with a biome. For instance if you want a desert to the east and not too far south or north, all points which are greater than a certain X value and within a certain Y range will have desert surrounding them.

Associate each screen with one of these point, which is done by taking the center of the screen in XY coordinates (say 4.5, 8.5) and returning the point closest to the screen's center.

Here's a rough drawing of a shape diagram on the grid of screens. We aren't really concerned with the lines surrounding the shapes, but they're there to illustrate how the screens start to approximate the shape regions.

Repeat for each screen, giving each one its own biome.
> 11 votes

# Answer
Answer 1:

grow snow and desert, when that is done, seek the (forbidden) intersections and grow (more or less big) swamp there.

Rince and repeat.

Answer 2:

For the 'blob' part, I moved my comment (as requested) to the post:

If you grow around by iteration, ie. set out 1 point of desert and then randomly grow around any desert point (each time randomly take one of the existing desert points and add 1 point on one of its sides (where there are nothing yet)) then you should get a blobby effect (no long lines for example).

You can also add a rule so you can't create a desert tile if there is snow on any tile nearby it.
> 1 votes

---
Tags: c#, maps, procedural-generation
---


# Question
Title: What is the Stencyl and StencylWorks business model?
Not sure how many of you have heard of Stencyl as a low-barrier-to-entry game development platform, but for those of you that have worked with it - what is their business model? Nothing is free (unless it is open source and this is not), so what's the catch? How do they make their revenue?

EDIT: I *have* emailed them and have not heard back. Will certainly update when/if I do, though they will probably point me to the blog post that @thedaian found.

Got a response from Jonathan Chung @ Stencyl:

> We're starting off with the tried and true model of selling subscriptions to export games to mobile platforms and HTML5. That will be our bread and butter for a while.
>
> We expect though, that we'll end up making more off of other revenue streams, such as running a carefully curated marketplace and other kinds of online services in which we share revenue with users.

# Answer
They have a Roadmap on their site with a list of what their plans are. However, people that have worked with the engine wouldn't know the business plan is anymore than the average Facebook user would know what the business plan is/was. It's unlikely that a random person making a game is going to know what the business plan of a new company is (unless it's obvious, like selling the software)

That said, if I had to guess, it's likely that they will charge something for the iOS and android versions, and the "Stencyl Market" could easily be another source of revenue. If 10% of everything sold on the market goes to them, then hey, they've got a source of income.

Edit: Turns out they have a very obvious business model. Lite and Pro versions, as described by this blog post. It seems like publishing anywhere will require the Pro version, which is $149/year.
> 4 votes

---
Tags: business-model
---


# Question
Title: Fitting 3D points representing bones to a BVH animation file
I am developing a motion capture animation system and I want my data to be stored within a BVH file. At the moment I have measured the size of the actor so I can create the hierarchy of the BVH file. I also have points in 3D representing the relative positions and orientations of the middle of certain bones such as the lower leg, foot e.t.c.

I was wondering what the best approach would be to map the bones into the BVH motion frames. I have to take into account slight inaccuracies in the 3D positions, for instance the foot might be plotted in 3D space 1cm off the actual location in the realworld.

Furthermore I was wondering how to recover lost 3D points. For instance if I have the left foot and left thigh, is it possible to recover the estimated position of the left shin?

Any help would be greatly appreciated.

Thanks

# Answer
> 0 votes
For the first part, the BVH file's header sets up the skeleton with hierarchy and location offsets. I could easily see you scaling that to your needs (normalize vector "locParent-locChild" then scale at will), and the second part of the .bvh file (frame bone coordinates) would accordingly be scaled as well (a little trickier). You can check if scaling is done without conflict by adding collision data to body parts and have system tweak or stop rotations when parts of body are overlapping.

source:BVH file specs

For the inaccuracies you'll have to interpolate the x,y,z coordinates of locations and rotations (whatever is used in the animation). You can try best fit whenever there is noise in the data or a too high of a delta change given a small amount of time. For example:

if the location-x coordinate goes from 0 to 10 in less than 3 frames and goes back to 1 on 4th frame, then you can smoothen that out by averaging the frames so it would increase at a smooth rate.

You can easily write an alogrithm and tweak it per animation with threshold controlling a (deltaChange / deltaFrame) ratio.

Hope this helps.

Here are some resources for animation/interpolation:

Interpolation of irregularities

Interpolation example

---
Tags: graphics, animation, skeletal-animation
---


title: Quad Tree with a lot of Moving Objects

text:
# Question
Title: Quad Tree with a lot of Moving Objects
I have a Quad Tree implementation that is very useful for what I am trying to do. My problem is that when my viewport has a lot of objects, the Update for the Quad Tree takes a very long time.

It is a known fact that Quad Trees are slow for non-static objects. I tried a few methods to try to speed things up, but the fact is, I need to update a large number of objects very often.

Is there a better algorithm I should be looking at instead? Are there some derived Quad Tree implementations you know about that might be useful to me?

# Answer
> 16 votes
How are you moving Quad Tree objects? The simplest (and slowest) method is to remove the object and re-insert it. The open-source XNA Quad Tree me and a friend made does a little bit of logic when an object moves:

```
If the object is still inside the same quad
    if the object fits into a child quad
        Add to child
Else
    move the object to the parent(s) until it fits, and optionally going back down into children

```

If you're already doing something like that, it could be worth looking into other spatial index methods like Spatial Hashing.

# Answer
> 5 votes
I use bounds for objects, and insert them in the deepest quad that contains them. (I've never been comfortable with treating things as points)

For fast-moving objects, which are also typically small e.g. bullets, I compute the bounds of their path for some number of timesteps or maximum size, so I'd bound a bullet by a larger rectangle rather than a smaller square and not need to move them nearly as often.

Also, you can optimise the moving code itself to move the object intelligently rather than removing it and reinserting it.

---
Tags: xna, c#, data-structure, quadtree
---


# Question
Title: Which of these two approaches to particle generator design is preferable?
What is a better idea for a particle generator (bearing in mind the intention to instance the draws to all the particles in the future)?

1. A particle emitter that maintains its own list of particles and calls their update.
2. A particle emitter that is passed through a global list of all particles in the world, adds the necessary particles to it and lets one global particle update take care of the rest.

# Answer
The first option seems overwhelmingly preferable: it allows for the particles owned by a given emitted to be processed in bulk, and it allows you to do better broad-phase culling of objects. It provides locality of reference to your particles and implies far less per-frame maintenance of the same.

The second "global particle list" option is a bad design because it relies on a global unnecessarily and implies that culling non-visible clusters of particles involves inspecting every particle, or at least re-associating every particle with an emitter every frame, which will be inefficient.
> 5 votes

# Answer
As with all other "preferable" or "best" approaches, it depends on what your end goal is.

For example, if you associate the particle list with it's emitter, this means that the emitter must continue to live until the particles have all decayed away. So your emitter needs to have more state. It needs to know whether it should be actively emitting more particles or in a "wait until all particles are gone" state. The latter doesn't make new ones. If you don't have this multi-state system, then the particles will all vanish the moment the particle system gets rid of them.

"Global" particle systems (it doesn't have to be "global" in the strictest sense. Just not bound to an emitter) allow you to de-couple emitters from the particles they emit. So your emitters can be very simple. Even better, you now have the ability to do different things you couldn't before. For example, you might want particles to respond to forces, like having particles near an explosion be pushed away by the impulse. Doing that with an emitter-based approach would be painful; you'd have to iterate through every particle emitter to make it work. With a "global" approach, you don't.

Then, there's the question of depth sorting. If multiple particle emitters start to interact, how do they sort with one another? Obviously this requires some level of 3D for it to matter. Again, the "global" approach makes this easier. Of course, you may not care about depth sorting between particle emitters, particularly considering sorting cost. But you have the option of caring with the "global" approach.
> 5 votes

# Answer
I would go for the first option:

1. It sounds simpler.
2. It adheres to encapsulation principle better.
3. It is likely that you will have to optimize the particle emitter. One of the common ways to improve speed is to have an array for particles and reuse the "dead" ones. I think it will be easier to handle if each emitter will be dealing with its own data.
> 4 votes

# Answer
After having read all of the excellent answers here, I'm actually now inclined to disagree with most. Nicol Bolas makes the point that every case is different and it might very well be useful to have all the particles in one place in order to exert global forces on them such as wind.

It has also been mentioned in other comments that this global approach may well be detrimental as you cannot refer to the particles as grouped by emitter, which can be very useful. However, I disagree with this. Nicol goes on to say in his comments that emitters should just emit - I agree with this.

So I have resolved to solve this problem by having emitters that do just that, emit particles that are added to a global list of all particles so that they can be affected by a number of global effects.

However, I propose a system where the particles have an additional index added to them, in the form of an integer, which represents their emitter so that they may be referred to in groups. Either that, or simply refer to them either globally in one big array of references, or through their emitters which maintain the smaller lists - depending on what you want to do.
> 1 votes

---
Tags: architecture, particles
---


# Question
Title: Why do console versions of multiplayer games support fewer players than PC versions?
source http://answers.yahoo.com/question/index?qid=20111205162848AAb1sl9

> 64 Players on P.C ( 32vs32)
>
> & bigger maps with more vehicles & buildings.
>
> 24 on Consoles ( 12vs12) ( It was planned to have a 32 player limit, but was later reduced to 24).

Why does the console version have a maximum of 24 players? Is it hardware related?

One of the reason was that players can host games themselves. If thats true its very sad that you cannot play 32x32, because one or two guys want to host games.

# Answer
> 12 votes
Well, I know on Xbox LIVE Indie Games, they have certain standards that they want you to follow. For example, they recommend that your game can run with a transfer speed of 8kb/s. This is because many people own Xboxes and not all of them have high-speed connections or even live in places where high-speed internet is available (what a nightmare! :-) ). So, in order to support as many players as possible, they have these, I guess you could call them quality of service guidelines.

Now, due to these limitations in bandwidth, obviously that limits the number of players that can connect. Especially since many games are host-based (i.e. one player hosts a game on their console and others join). PCs, on the other hand, are individually so different and unregulated, that it's really up to the player to take care of their own "quality of service".

There is another restriction on processing power, if a host console has to do all the work figuring out where people are, running the physics simulation, etc., it's possible that it can only handle a certain number of players before it starts adversely affecting the host's gameplay. This, of course, depends on the game.

On PC, often the server (especially for large 32x32 games) will be a dedicated server, meaning that no one is playing the game on the same PC running the server (hopefully), so the entire processing power of that computer (more or less) can be dedicated to running the game.

That said, big AAA titles on the consoles do have their own servers for high-player-count gaming and it's not impossible for a console game to support 64 players or even more. But they may still have the up/down speed restrictions for each player.

So I think, for the most part, it's wanting (or having) to provide a consistent feel for their games across as many countries and regions as possible.

---
Tags: multiplayer, xbox360, playstation3, pc
---


# Question
Title: building a game for different resolution phones
I am starting some tests for building a game on the Android program. So far everything is working and seems nice.

However I do not understand how to make sure my game looks correct on all phones as they all will have slightly different screen ratios (and even very different on some odd phones)

What I am doing right now is making a view frustum (could also be ortho) which I set to go from -ratio to +ratio (as I have seen on many examples) however this causes my test shape to be stretched and sometimes cut off by the edge of the screen.

I am tilting my phone to landscape to do my tests (a bit extreme) but it should still render correctly if I have done things right.

Should I be scaling by some ratio before drawing or something?

An example would be greatly appreciated.

PS. I am doing a 2D game .

# Answer
From a high-level perspective there's only a handful of options, depending on which is more important, maintaining a consistent aspect ratio, or ensuring that no one to see more than someone else just because they have a wider or taller screen.

Your options are:

1. Cropping the parts that don't fit.
2. Stretching the screen to fit, which has the issue you're seeing of stretched images.
3. "Letterboxing" which maintains both aspect ratio and ensures that no player sees more than any other player because of their screen size,
> 4 votes

# Answer
The 3 options from Davy8's answer are:

* Cropping the parts that don't fit.
* Stretching the screen to fit, which has the issue you're seeing of stretched images.
* "Letterboxing" which maintains both aspect ratio and ensures that no player sees more than any other player because of their screen size

I would add a fourth option, which is my preferred approach. It's really a variation on letterboxing; traditional letterboxing fills the extra space with black, whereas this approach fills the extra space with extra graphics. You could simply extend the background color/image and possibly show an extra logo.

Another way to think about it is that I always crop the screen for every display, and the full display is purposely designed to be bigger than all mobile displays/aspect ratios. Thus there's always extra graphics to fill out the letterboxed area.

In addition, depending on the nature of your game (ie. would this change give certain players an unfair advantage?) and on how your UI is designed you could even shift over some UI elements to fill the extra space. Think of it like a fluid website design, where the right menu stays on the right no matter how wide the window is.
> 3 votes

# Answer
The ratio you're referring to is called the 'aspect ratio'. It is usually calculated as the 'width / height' (although if you arranged your viewport differently that could be 'height / width')

Remember to cast the divisor to a float!

```
float aspect_ratio = width / (float) height;

```

HTH
> 0 votes

---
Tags: mathematics, android, opengl-es, rendering, resolution
---


title: Score Based on Game play Time and a Int

text:
# Question
Title: Score Based on Game play Time and a Int
I'm trying to do a score that is based on the time taken and number of manipulators used. The faster you do it, with the fewest manipulators, the higher the score. I've managed to get it working with you get the lowest score but not the highest and i can't think how to do it. Any help would be appreciated.

I have a play time `(GameTime.TotalGameTime.TotalSeconds - startTime.TotalSeconds)` and a count of the manipulators used `(grid.NumberOfManipulatorsInGrid(TextureList.GameplayTextures))` to work with

# Answer
> 5 votes
I think this is a place where a **power function** may be ideal. If the best score `S` is achieved with `N` manipulators, you can have `N+1` manipulators yield a score of `S * 0.9` (ie. 90% of the best score), then `N+2` manipulators yield `S * 0.81` (ie. 90% of 90% of the best score), and so on.

This is generalised by the following formula:

```
score(num_manip) = S * pow(0.9, num_manip - N);

```

The advantage of this method is that you don't need any clamping: progressively bad performance will tend towards a score of zero.

The general score formulas can be:

```
TimeScore = TimeScoreBase * pow(A, BestPlayTime - PlayTime);
ManipulatorScore = ManipulatorScoreBase * pow(B, BestManipulatorCount - UsedManipulators);

```

You then need to choose `TimeScoreBase` and `ManipulatorScoreBase` (these are probably global to the game), tune `A` and `B` by how much you want the score to decrease for each additional second spent or each additional manipulator used (again, global to the game) and choose `BestPlayTime` and `BestManipulatorCount` (these, however, should be specific to the level being played).

Note that if by chance the player managed to finish the level in less time than `BestPlayTime`, it wouldn't be a serious problem, the score would simply be higher than `TimeScoreBase`. You may accept this, thus rewarding outstanding players, or clamp the total play time to avoid cheating.

Then you need to choose how to combine the scores:

```
Score = TimeScore + ManipulatorScore;
Score = sqrt(TimeScore * ManipulatorScore);

```

Each formula will have a different asymptotic behaviour, but the general idea is that the worse the play, the lower the score. The first one will give points for using few manipulators even in case of a bad time. The second one will give a bad final score if any of the two scores is bad.

# Answer
> 2 votes
You could possibly invert it, a lower score could be what players could try to achieve: as another example your score isn't the number of live you have, but rather the number you lost - I think Touhou works like this. Therefore your score calculation would be:

```
score =
  (GameTime.TotalGameTime.TotalSeconds - startTime.TotalSeconds) * TimeScalingFactor +
  (grid.NumberOfManipulatorsInGrid(TextureList.GameplayTextures)) * ManipulatorScalingFactor;

```

However, if you really want a bigger score to be better you will need to have a time and manipulation limit; you could either end the game if the limits run out or go into negative values. This would imply:

```
score =
  (TimeLimit - (GameTime.TotalGameTime.TotalSeconds - startTime.TotalSeconds)) * TimeScalingFactor +
  (ManipulatorLimit - grid.NumberOfManipulatorsInGrid(TextureList.GameplayTextures)) * ManipulatorScalingFactor;

```

---
Tags: algorithm, scoring
---


# Question
Title: Where can I find free motion capture footage?
Are there any repositories of free motion capture footage? Or maybe just libraries of animations.

# Answer
This & This page contains some more links/info.

You should also check out, Mixamo
> 12 votes

# Answer
You can find a lot of free motion capture clips on these websites:

1. Cgspeed
2. Animstreet
> 4 votes

---
Tags: animation, assets
---


# Question
Title: Heightmap Physics Optimization/Improvement
I'm working on implementing the physics surrounding a player walking on a heightmap. A heightmap is a grid of points which are evenly spaced on the x and z axes, with varying heights. The physical representation of my player (what is exposed to my physics engine/manager) is simply a point-mass where his feet are, rather than complicating the problem by treating him as a sphere or a box.

This image should help further explain heightmaps and show how triangles are generated from the points. This picture would be looking straight down on a heightmap, and each intersection would be a vertex that has some height.

Feel free to move this over to math, physics, or stack overflow, but I'm pretty sure this is where it belongs as it is a programming question related to games.

Here's my current algorithm:

1. Calculate the player's velocity from input/gravity/previous velocity/etc
2. Move the player's position (nextPos = prevPos + velocity * timeSinceLastFrame)
3. Figure out which triangle (all graphics is done in triangles!) of my heightmap the player's new position is vertically aligned with
4. Use the three vertices of that triangle to calculate the equation for the plane which that triangle lies in
5. Plug in the player's x and z coordinates into the plane's equation to get the y coordinate for the player's position on that plane
6. Set the y coordinate of the player's position to this (if newPos.y \< y)

This is all fine and dandy, but I'm wondering if there's anything that I can optimize. For example, my first thought is to store the plane's equation with the triangle's vertex information. This way all I have to do is plug in the x and z values to the equation to get the y. However, this would require adding 4 floats to every vertex of the heightmap which is a little ridiculous memory wise. Also, my heightmaps are dynamic (meaning the heights will change at runtime), which would mean changing the plane equations every time a vertex's height changes.

Is there a faster way to calculate that point than digging up the plane's equation and then plugging in x and z? Should I store the plane equations and update them on vertex height change or should I just regenerate the plane equations for every triangle every time the player moves on that triangle? Is there a better way to do heightmap physics that maintains this simplicity? (this seems very simple to me as far as physics engines go)

# Answer
> 2 votes
It's easy to improve on the height computation. For simplicity I will consider that the size of a square is `1`; you can always get back to this case by switching coordinates:

```
                x A
  ^ z         ,'|
  |         ,'  |
  |       ,'    | M'
  |     ,'  M   x
  |   ,'   x    |
  | ,'          |
  x'------------x-----> x
 B               C

```

Let `M` have coordinates `(x,z)`. First, project `M` onto the `AC` edge along `BM`. The coordinates of `M'` are `(1,z/x)`. Linear interpolation gives the height of `M'` as `yM' = yC + (z/x)(yA-yC)`. Finally, the height of `M` is `yM = yB + x(yM' - yB)`. Or:

```
yM = yB + x(yC-yB) + z(yA-yC)

```

Also, I see several problems with what you are doing.

* `nextPos = prevPos + velocity * timeSinceLastFrame` is most certainly wrong, you should be integrating velocity over the whole elapsed frame rather than using only the current velocity value. Averaging the new velocity with the previous frame’s velocity is **almost always** a better approximation, and is even *the* right thing to do in the case of constant acceleration (such as gravity), because it exactly simulates newtonian mechanics.
* the kind of heightmap triangulation will probably give rendering artifacts because triangle subdivisions are always in the same direction; one way to compensate for this is to switch the direction of the diagonal every odd and even cell. Another solution is to use a regular hexagonal/triangular mesh rather than a square pattern.
* you do not seem to be taking the vertical component of the player velocity into account; the walking distance varies with elevation variations, so if the triangle you land on has a different slope than the one you left, you may end with an error in the linear momentum. Actually this is best illustrated by your clamping of the `y` value: when doing this, you're modifying the energy of the player, without compensating elsewhere. One solution for this would be to perform your physics step several times per frame in order to compensate as soon as possible for the slope variation.

---
Tags: opengl, c++, collision-detection, physics, heightmap
---


# Question
Title: Making smooth walk/jump/fly etc animations
i am soon gonna start with developing my own game for the iOS, i have the plan and idea of the game ready. BUT i have 1 question. How do people make such a smooth animation? Lets take for example: Angry Birds, if you pull on the rope to shoot the bird everything looks so smootthh or take Tiny Wings for example.., how did they make this? Did they made an image for every frame of the animation in photoshop and putted it in a plist? or how?

Ty in advance!

# Answer
(Warning, I am a programmer, not an artist. Results may vary)

In order to get smoother animation, regardless of method you use to put them on screen, you generally want more frames. A good piece of advice I was shown a while ago is to subdivide your animations.

Making every frame perfect from start to finish is hard, no matter what program or system you use. Instead focus at first on making the gross movement look decent. One, *maybe* two frames on each discrete part of the motion.

Once you've got your basic animation complete, now comes making it smooth. Go between each of your frames you've created and add another frame between those two of the state between them. Once you are done, go watch it again. Still not smooth enough? Go through and add more frames between the other frames.

You may find yourself deleting some frames that are no longer necessary in this process or adding some to one location and not another, just remember to keep checking the animation to see how it looks. Also remember that if you add frames to one part but not another, even if you keep the entire animation the same length of time you will skew how much time the individual parts of the animation take. This can be useful if one part of the animation is going too quick or too slow.

Once you are happy with your animation, compile it into your method of choice for animation drawing (Sprite Sheets are easy and almost always a good choice for 2D games) and voila! You've got your smooth animation!

(Note: if your smooth animation concerns for motion are in regards to a relatively static sprite being moved across the screen, take the same concept and apply it there. Less distance traveled per frame looks smoother than the alternative)
> 2 votes

# Answer
The "animations" in Angry Birds are not animations but either preset movements stored in vectors or part of the physics engine. It just has a sprite being moved around.
> 3 votes

# Answer
To make an animation more smooth, your animation needs more frames. So, e.g. person standing -\> person taking a stride would become person standing -\> person lifting leg a bit -\> person lifting leg some more -\> ... -\> person taking a stride. How you make your frames, e.g. draw them by hand or use a technic like rotoscoping or render them, is up to you. Then, you'd load theese images into your game and play/display them one at a time. So far for characters or objects changing their pose or form or whatever. If you want to move your characters/objects realistically, that's more related to physics/movement. E.g. when your characters speed is \> 0, you'd play the walk animation. When your character jumps, you'd play the jump animation and give your character an impulse and the physics engine makes your character move in a parabolic path. Physics and animation are often pretty interwined in games, so you might want to look into both.
> 2 votes

---
Tags: 2d, animation, cocos2d-iphone, ios
---


title: 3d platformer with 2d point of view

text:
# Question
Title: 3d platformer with 2d point of view
I made my first 2d platformer game using java + swing.

Now I want to achieve the same gameplay adding 1 dimension. I think this will require opengl knowledge.

I know the basics but i don't consider myself an expert.

This is an idea of how the game should look like.

So the question is, what will i need in order to do this(libraries,programs etc)?

Please do not start writing answers and comments on how hard this will be. I know that it will take me some time but i am willing to finish the project.

# Answer
Yes, you need libraries and other things that handles the low level stuff for you so you can work on the core game play and game assets. LWJGL is the natural choice if you want to do something with OpenGL + JAVA. But, its low level. You want something that more focused towards game, not pixels of your display.

jMonkeyEngine is the perfect choice for this. It handles all the high level stuff for you. It is a shader based engine. So, unlike most of the engines out there you wont be working with old feature & functionality. It comes with SDK, which features update center and pre-configured project setup with many examples. Plethora of documentations. Very active community. Most importantly its development is progressing like a bullet train.

Recently its beta version has been announced, (fear not, its very stable) that's why a game development competition is being help over there. So, jump in with your eyes closed!

If you want to know what are the others options(libraries) and why I suggest you jME over those, read this answer.
> 1 votes

# Answer
If you want to use OpenGL, it should be enough to use some library like SFML or GLUT or FreeGLUT or something like that. It will give you all you need to "render" things. But for example physics is on your own - collisions, models, animations (if your hero will be only 2D, you can use just sprites - animated pictures). You may want also create some level editor, export levels from it and import them to game.

I think, that the hardest part is levels and collisions with environment (and if you want 3D character, then maybe also animations).
> 0 votes

# Answer
You should use LWJGL which is a java implementation of OpenGL that is very good for beginners and professionals as it does the basic setup of the OpenGL components for you and it is much simpler than using OpenGL by itself.
> 0 votes

---
Tags: 3d, java, platformer
---


# Question
Title: Gluing Model and View Data Together But Separating Concerns
I've built a couple of 2D games that are roughly MVC; that is, the main game data and logic are separated into the model (and possibly controllers), and I have a bunch of screens/states that just pull stuff from the model class and draw that on screen.

This is not a complete separation, because things like size, collision detection, etc. tend to be view concerns and not model concerns.

**In any case, I have a difficult time "gluing" together models and views. Is there a good way to do this, while still preserving the separation of concerns?**

Let's say I'm working with a `Sprite` class to represent an image, and I have a `Player` class representing my player (X, Y, number of lives, running/walking, etc.). How do I associate them together?

For example, `Player` can be a subclass of `Sprite`, or can contain an instance of `Sprite` (or vice-versa), or I can have a third class (PlayerModelView) that contains an instance of both `Player` and `Sprite`, or something else entirely.

(I've tried the latter approach, but it usually ends with a lot of type conversions and the model checking with the view about collisions.)

# Answer
When doing MVC-style architecture (not just in gaming!) it can be helpful to remember that there is often *more* than one model. Besides the (usually) obvious model of the `Player`'s state (his position, life, and so on), there may be models (dependant on language and engine) for `Sprite`, or other 'display' classes.

For instance in Valve's Source engine, the 3-dimensional art (and animations) are encapsulated in their own files (representing the mesh, current animation, a few other things, but **not** the object's position), and have absolutely *no* relation to an entity's data (which contains position, orientation, and so on).

Because the two models usually don't (or aren't supposed to) have much to do with each other, they can (or possibly should) be wired together with seperate controllers: One for `Player` model to `Sprite` model updates (setting the currently playing animation, display position, etc), and one from the `Sprite` (for what, and where *relative to other display elements*) model to the view.

Here's a quick (Java-based Psuedo-code) example with attributes:

```
public Beast {
    private String name;
    private List<Behaviour> behaviours;
}

public Player {
    private List<Beast> paddock;
    private List<Beast> leashed;
    private List<Beast> hospital;

public BeastAnimation { // One per beast!
    private Map<Behaviour, Animation> animations;
    private Animation current;
}

```

With these entities, you'd want a controller that would set the `BeastAnimation`'s `current` based on whatever `Behaviour` was being executed - depending on game type, you usually need to start the animation even if the object is otherwise not (at least initially) visible, you don't want the entity doing *nothing* the first time he's seen (especially if the animation is long). Please note that this doesn't necessarily mean *rendering* the animations or (depending on display type) even applying transforms.
You're also going to want a controller that takes the 'current' `BeastAnimation` when actually rendering out the animation. Please note that the various animations only their *relative* positions, and shouldn't really know **where** the camera is - this controller acts as the necessary translation bridge. It's good to note that a fair number of graphics engines essentially take care of this *for* you - you only have to hand it the necessary models/animations, and say where the camera is - they're a controller/view package in one. Otherwise, how (and what the necessary translations are) varies by case
> 4 votes

---
Tags: 2d
---


# Question
Title: Is glEnable obsolete/unneeded in OpenGL ES 2?
In an iOS app I am writing I am now culling all the GL 1 crap from my GL 2 code. Can I safely remove `glEnable`?

# Answer
> 14 votes
`glEnable` and `glDisable` are still present in GLES 2, but a lot of boolean states are deprecated or even removed (for instance, `GL_TEXTURE_2D` or `GL_ALPHA_TEST`).

According to the manual page, the following boolean states can still be enabled or disabled using these functions:

* `GL_BLEND`
* `GL_CULL_FACE`
* `GL_DEPTH_TEST`
* `GL_DITHER`
* `GL_POLYGON_OFFSET_FILL`
* `GL_SAMPLE_ALPHA_TO_COVERAGE`
* `GL_SAMPLE_COVERAGE`
* `GL_SCISSOR_TEST`
* `GL_STENCIL_TEST`

---
Tags: opengl, ios
---


title: On Creating a D3DX10 texture atlas

text:
# Question
Title: On Creating a D3DX10 texture atlas
I have a DirectX10 texture (ID3D10Texture2D) that I load from disk with the following code:

```
CComPtr<ID3D10Device>   spD3D; // Initialized correctly elsewhere

hr = D3DX10CreateTextureFromFile(
        spD3D.p,
        wsFilename.c_str(),
        NULL, NULL,
        &spTextureResource,
        NULL
    );

if( FAILED(hr) || ! spTextureResource.p )
    return false;

spTextureResource->QueryInterface <ID3D10Texture2D> ( &m_spTexture );
if( ! m_spTexture.p )
    return false;

```

The texture loads fine, I can blit this onscreen.

Later, I want to use that texture as an atlas. To do so, the first thing I want to do is to call ID3D10Texture2D::Map() in order to get at the texels and parse them (to determine where my tiles are).

The following call fails with E\_INVALIDARG:

```
D3D10_MAPPED_TEXTURE2D mapped;
HRESULT hr = spTexture->Map( 0, D3D10_MAP_READ, 0, &mapped );

```

So I'm thinking that this fails because the texture can't be read from by the CPU. So in order to get a texture that is CPU readable, I tried setting the D3DX10\_IMAGE\_LOAD\_INFO structure to include D3D10\_CPU\_ACCESS\_READ. This fails on D3DX10CreateShaderResourceViewFromFile() with E\_INVALIDARG.

So I guess I've given up trying to load in a texture and be able to read its data from on the CPU.

So I thought, what about making a texture with the following D3D10\_TEXTURE2D\_DESC flags:

```
    D3D10_TEXTURE2D_DESC    desc;
    ZeroMemory(&desc, sizeof(D3D10_TEXTURE2D_DESC));
    desc.CPUAccessFlags     = D3D10_CPU_ACCESS_READ | D3D10_CPU_ACCESS_WRITE;
    desc.Usage              = D3D10_USAGE_DYNAMIC;
    desc.BindFlags          = D3D10_BIND_RENDER_TARGET | D3D10_BIND_SHADER_RESOURCE;

```

Step 2 of my plan is to use CopyResource or CopyResourceSubregion to copy data from the disk file into my dynamic texture, so I can use the dynamic texture as a source to read texel data from.

Will this approach work? Am I barking up the wrong tree and missing an obvious simpler route?

I'm worried that CopyResource won't work either, since the original texture was loaded from disk without the D3D10\_CPU\_ACCESS\_READ flag.

God, I've got to write this for OpenGL too, I hope it's easier with GL!

My plan is to parse this texture and determine where my tiles are, so I can use the texture as an atlas for generating sprites.

# Answer
In order to read texel information from a texture, we need a texture with Usage = D3D10\_USAGE\_STAGING.

This allows the D3D10\_CPU\_ACCESS\_READ flag to be set.

I loaded this texture a second time (as a temporary, or "staging" resource, so that I could read the texel information).

So to get read access to a texture, we must fill in this IMAGE\_LOAD\_INFO structure, which is passed to the D3DX10CreateTextureFromFile() call.

```
    CComPtr<ID3D10Device>       spD3D       = RenderMgr::I()->D3DDev();
    CComPtr<ID3D10Texture2D>    spTexture;
    CComPtr<ID3D10Resource>     spResource;

    D3DX10_IMAGE_LOAD_INFO  loadInfo;
    loadInfo.Width          = D3DX10_FROM_FILE;
    loadInfo.Height         = D3DX10_FROM_FILE;
    loadInfo.Depth          = D3DX10_FROM_FILE;
    loadInfo.FirstMipLevel  = 0;
    loadInfo.MipLevels      = D3DX10_FROM_FILE;
    loadInfo.Usage          = D3D10_USAGE_STAGING;
    loadInfo.BindFlags      = 0;
    loadInfo.CpuAccessFlags = D3D10_CPU_ACCESS_WRITE | D3D10_CPU_ACCESS_READ;
    loadInfo.MiscFlags      = 0;
    loadInfo.Format         = m_pTexAtlas->Desc().Format;
    loadInfo.Filter         = D3DX10_FILTER_NONE;
    loadInfo.MipFilter      = D3DX10_FILTER_NONE;
    loadInfo.pSrcInfo       = 0;

    hr = D3DX10CreateTextureFromFile(
        spD3D,
        wsTexture.c_str(),
        &loadInfo,
        NULL,
        &spResource,
        NULL
    );

    if( ! SUCCEEDED(hr) )
        return false;

    spResource->QueryInterface <ID3D10Texture2D> (&spTexture);
    if( ! spTexture )
    {
        spResource.Release();
        return false;
    }

    spTexture->GetDesc( &desc );

    ZeroMemory(&mapped, sizeof(D3D10_MAPPED_TEXTURE2D));

    hr = spTexture->Map( D3D10CalcSubresource(0, 0, 1), D3D10_MAP_READ, 0, &mapped );
    if( ! SUCCEEDED(hr) )
        return false;

```

Okay, so now the Map() call succeeds. I hope it helps someone out there !!! I wasted an entire day on this. I wish there was better documentation for dealing with textures. I was working from Luna, which like many sources, only deals with textures as they can be mapped to models :S
> 1 votes

---
Tags: c++, textures, windows, directx10
---


title: Dual Stick Shooter in XNA (trig)

text:
# Question
Title: Dual Stick Shooter in XNA (trig)
Honestly I have never taken a trigonometry class, but I am trying to create a dual stick shooter in XNA, can someone please look at my code and look to see if there are things that can be fixed, The image facing is off? Why?

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace DualStickPC
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            //set window size
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 720;
        }

        protected override void Initialize()
        {

            base.Initialize();
        }

        Texture2D mytexture;
        Texture2D curTexture;
        Vector2 sPos = Vector2.Zero;
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            mytexture = Content.Load<Texture2D>("Arrow");
            curTexture = Content.Load<Texture2D>("Cursor");
        }

        protected override void UnloadContent()
        {

        }

        protected override void Update(GameTime gameTime)
        {
            if (Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            sPos.X = GraphicsDevice.Viewport.Width/2;
            sPos.Y = GraphicsDevice.Viewport.Height/2;

            base.Update(gameTime);
        }
        protected override void Draw(GameTime gameTime)
        {
            int x2 = Mouse.GetState().X;
            int x1 = (int) sPos.X;
            int y2 = Mouse.GetState().Y;
            int y1 = (int) sPos.Y;
            float rotation = (float)Math.Atan2(Mouse.GetState().Y - sPos.Y + (int)mytexture.Height / 2, Mouse.GetState().X - sPos.X + (int)mytexture.Width / 2);
            float slope = 0;
            try
            {
                slope = (y2 - y1) / (x2 - x1);
            }
            catch
            {
                slope = 180;
            }
            double angle = 100 * Math.Tan(slope);
            float radians = MathHelper.ToRadians((float)angle);

            int msX = (int)(Mouse.GetState().X - sPos.X - mytexture.Width/2);
            int msY = (int)(Mouse.GetState().Y - sPos.Y - mytexture.Height / 2);

            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
            Vector2 mousePos = Vector2.Zero;
            mousePos.X = Mouse.GetState().X;
            mousePos.Y =Mouse.GetState().Y;
            spriteBatch.Draw(curTexture, mousePos,Color.White);
            spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X, (int)sPos.Y, mytexture.Height, mytexture.Width), null, Color.White, (float) (rotation), new Vector2(mytexture.Width/2, mytexture.Height/2), SpriteEffects.None, 0);

            //Testing projectile
            spriteBatch.Draw(mytexture, new Rectangle((int)sPos.X + msX/2, (int)sPos.Y + msY/2, mytexture.Height, mytexture.Width), null, Color.White, 0, new Vector2(mytexture.Width / 2, mytexture.Height / 2), SpriteEffects.None, 0);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

# Answer
> 0 votes
If you want to set your ship at the center and face to the mouse you have to use something similar to this.

Keep in mind that maybe you need to add some angle offset (90º, º180 or 270º) to your ship to face in the right direction.

```
protected override void Update(GameTime gameTime)
    {
        if (Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        sPos.X = GraphicsDevice.Viewport.Width/2;
        sPos.Y = GraphicsDevice.Viewport.Height/2;
        mPos.X = Mouse.GetState().X;
        mPos.Y =Mouse.GetState().Y;

        rotation = (float)Math.Atan2(mPos.Y-sPos.Y, mPos.X-sPos.X);
        sOrigin = new Vector2(ship.Width, ship.Height) * 0.5f;
        pOrigin = new Vector2(projectile.Width, projectile.Height) * 0.5f;

        pPos = sPos + Vector2.Normalize(mPos-sPos) * 100;

        base.Update(gameTime);
    }
    protected override void Draw(GameTime gameTime)
    {

        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

        spriteBatch.Draw(curTexture, mPos,Color.White);
        spriteBatch.Draw(ship, sPos, null, Color.White, sOrigin, rotation, 1, SpriteEffects.None, 0) ;
        spriteBatch.Draw(projectile, pPos, null, Color.White, pOrigin, rotation, 1, SpriteEffects.None, 0) ;

        spriteBatch.End();

        base.Draw(gameTime);
    }

```

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


# Question
Title: What are the steps to get sound from reality into a game?
As we all know, the game is not only about gameplay, sound effects add a lot to the production value. The more unique, the better the result.

What are the steps to get a decent quality sound from reality into a game environment?

And some tips probably, as whether I should cover multiple cases of the "sound": normal, echo and other. Or this can/should be done within the engine itself, or post-processed after normal sound?

# Answer
> 12 votes
Sound production for games is not that much different from film or animation. While the game isn't chronological (which poses a bigger challenge to music composers) the sound effects are usually short and played at certain events.

In most of the cases, you don't want to record your sounds outside. A studio environment is preferable where you can align your recording devices perfectly and where you're sure there won't be any background noise. A lot of sounds in films and games are actually faked (mimicked) and not recordings of the "real" object. This is usually done by a Foley artist.

Usually it's cheaper to buy existing sound-effects, as recording your own with decent quality requires good equipment and experience. Creating your own sound-effects *can* make your game stand out, so if you feel comfortable doing so, go ahead!

As for the different "states" of a sound-effect (eg. echo, etc.): I'd say it depends on your target-platform and the type of game. It's always cheaper (in terms of processing power) to have your assets ready without the need for further processing.

If your game runs on a mobile device, then there's a high probability that you can't do much realtime sound processing. Things look different on a modern desktop PC though. But it also highly depends on the type of game and the use of sound-effects within. If you have very dynamic effects that sound differently in almost every scene, then it's probably better to try to calculate the effects in real-time or pre-process them at loading of the level. But if your game isn't revolving around the sound-effects (eg. sound-effects are an important part of gameplay), most people won't notice the nuances in the sound and you can boil it down to 1-2 pre-fabricated assets.

---
Tags: sound
---


title: XNA model texture from file

text:
# Question
Title: XNA model texture from file
Is there any way to have the texture of a model loaded from a Png ?

I have a simple prism to test it on, but i just want to be able to edit an image and have the model's texture change.

Thanks!

# Answer
You can use a png as a texture. First you have to add it to the game project content :

http://msdn.microsoft.com/en-us/library/dd282477(v=XNAGameStudio.40).aspx

And then you call Load method of ContentManager :

http://msdn.microsoft.com/fr-FR/library/bb197848(v=XNAGameStudio.40).aspx

You can access the ContentManager through the Content properties of Game class :

http://msdn.microsoft.com/fr-FR/library/microsoft.xna.framework.game.content(v=XNAGameStudio.40).aspx
> 1 votes

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


title: Game logic on the server! Good or bad?

text:
# Question
Title: Game logic on the server! Good or bad?
I'm currently planning a simple online multiplayer game. And here is the question. Does it make sense to make the whole game logic on the server and just send the input from the client to the server? Which are the pros and the cons or are there any reasons why I shouldn't do that?

# Answer
> 38 votes
You don't want to send player input to the server. What you probably want to do is send an abstracted representation of what the player wants to do to the server, and then run the logic on there.

Likewise you don't necessarily want to send back everything the client needs to do. For example, you can send some kind of message saying "NPC X died", and the client determines what animation/sounds to play. Stuff like that.

The trick is to find the line where bandwidth and processing power (on the server) is trumped by preventing people from cheating. Usually you make any kind of game-changing authoritative decision on the server only, and leave all the ancillary visual stuff to the client.

There are a lot of more specific questions on this topic all over the site. For example:

Should collision detection be done server-side or cooperatively between client/server?

Who does the AI calculations in an MMO?

Should the game host be the authority, or another dumb client?

# Answer
> 17 votes
Well, you got answers but your real answer is at "try yourself". The things differ from game to game.

I did couple of multiplayer games for some distributed network game design course. The most challenging was doing a realtime action game where many players involved and sending inputs like hell. When it comes to that point, everything becomes problem. As you see the first link Tetrat sent, even determining a collusion becomes a problem. And you will read-hear terms like lag, interpolation, extrapolation, prediction... But if you never tried yourself coding from scratch, you will just accept these words and wouldn't know what they really mean.

My recommendation is:

**Step 1**
Just start with fully authorized server based design for now. As you said, just send user inputs to server and let server do everything and clients get the results. Your game will work fully consistent. But when you look at your clients, you will notice some lags, some teleport problems, not smooth movement...ect.

**Step 2**
Start fixing the issues on client side. The teleporting problems for example. Your character was at (0,0) and server said now you are at (100,100). Your character will just teleport to (100,100) which is not nice. There comes the interpolation. You should have a code in client side which will slide the character from (0,0) to (100, 100) in a smooth way. Yes, you will move your character from (0,0) to (100,100) but how fast? For now you can just use the time difference between each server update. If your server sends 10 packets in a second which means 100 ms delay between each packet.

**Step 3**
Now your game is already good for fast networks where there is delay of (1-50)ms. But it gets doomed if there is a packet loss, high latency or calculation takes long in server...ect. In those situations you will notice when you press left arrow, you will see your character moving left with a delay of 200 ms. The delay between your packet goes to server, calculation time and comes back to you with your last position. This is bad, the worst disadvantage of server authorized design. Player wants his character move left as soon as he presses left, you can't make him wait. Luckily client also have the same code as server, so why not execute it on client immediately and fix the final result with the answer from server? Thats what basicly input prediction is. Client presses left, the code in his side will move him to left, after some time lets say 200 ms, the real position comes from server and client corrects its position with it. If everything went allright, client won't notice anything, "step 2" will also help us with this.

Well, net has many tutorials and things about this subject. But there are 2 I really like:

Really good, covers dark spots: Valve-Source Engine Multiplayer Networking
Kind of history, fun to read and worth it: 1500 Archers on 28.8 ,

# Answer
> 3 votes
Pros:

* this approach is more (most) piracy proof
* you can apply updates more easily
* centralized community

Cons:

* huge bandwidth requirements
* some users can hate that approach (privacy and stuff)
* problems with local gameplay (LAN parties), singleplayer

# Answer
> 2 votes
Server side logic also creates scalability problems - you have to do all the work for all the clients on your server - verses letting each client do his own share of the total work.

# Answer
> 2 votes
Depends on what game you want to create and what part of the game. If developing an RTS (or any game with a lockstepped model), then you definitely should only send the input and which simulation step the input was recieved.

If you want to do a shooter you could use both input and abstract functions. If you take Unreal Tournament 3 as the case, they created the multiplayer mainly via replicated function calls.
For movement they take the player input( compressed into a single bit for each action) delta rotation, acceleration & timestamp and send it to the server.
For other purposes like weapon they synchronize when you shoot (AFAIK, havn't looked into this part in depth yet).
For more static / less often changed values like health they send the variable to the client or server depending on what the programmer specified.

And for non-RTS games, remember client prediction.

---
Tags: multiplayer, server, logic, online
---


# Question
Title: How can I orient a projectile along its flight path?
I have a projectile that is moving around the world (in a ballistics trajectory right now). I am currently keeping track of its position and velocity. I want to draw it oriented to its velocity, so that it is facing the direction it is going. This seemed like as good of a time as any to try to understand quaternions so I was attempting to solve the orientation problem using them.

Here is my drawing code:

```
var alignmentVector = Vector3.Normalize(velocity);
var rotationAxis = Vector3.Cross(Vector3.Up, alignmentVector);
var rotationAngle = (float)Math.Acos(Vector3.Dot(Vector3.Up, alignmentVector));
var rotationQuat = Quaternion.CreateFromAxisAngle(rotationAxis, rotationAngle);

var transform = Matrix.CreateScale(5.0f) *
                Matrix.CreateFromQuaternion(rotationQuat) *
                Matrix.CreateTranslation(position);

PresentationHelper.Draw(model, transform); //This just draws the model using the transform parameter as the world matrix

```

This kinda of works, but not really. In fact, I am having a hard time finding the words to describe what is happening with it. It looks like its tracking for a little while then it goes off course and becomes flattened(is that possible????)

Am I on the right track with the quaternions and can my code be fixed? If not what is a good approach to solving it?

# Answer
If you were to take the cross idea a step further, you could finish your desired orientation as a matrix and pass it that way (and which could be converted to a quaternion if needed).

```
Vector3 forward = Vector3.Normalize(velocity);
Vector3 Right = Vector3.Normalize(Vector3.Cross(forward, Vector3.Up));
Vector3 modelUp = Vector3.Cross(right, forward);

float scale = 5.0f;
Matrix orientation = Matrix.Identity;
orientation.Forward = forward * scale;
orientation.Right = right * scale;
orientation.Up = modelUp * scale;
orientation.Translation = position;

presentationHelper.Draw(model, orientation);

```

OR... If you want Xna to do all that crossing & normalizing behind the scenes, you could do this:

```
Matrix orientation = Matrix.CreateWorld(position, Vector3.Normalize(velocity), Vector3.Up);
Matrix transform = Matrix.CreateScale(5.0f) * orientation;
presentationHelper.Draw(model, transform);

```
> 0 votes

# Answer
Quaternions always represent a rotational transform. When you use a quaternion to specify a model's orientation, that quaternion specifies a rotation away from identity. And in XNA, a model with an identity rotation will point toward `Vector3.Forward`.

With that in mind, I believe your problem is here:

```
var rotationAngle = (float)Math.Acos(Vector3.Dot(Vector3.Up, alignmentVector));

```

You're comparing your `alignmentVector`, which is your desired *forward* vector, with `Vector3.Up`. Instead, you should be comparing against `Vector3.Forward`.

Further reading: Orienting a model to face a target
> 2 votes

---
Tags: mathematics, xna-4.0, quaternion
---


# Question
Title: Selective jogl texture transparancy depending on bitwise magic?
I have rewritten some code to allow to load bitmaps to be loaded as textures and if a pixel has a max green color component it is marked transparent. What is odd is that I cannot use the value from a ByteBuffer that holds transparency without keeping the green intact, I can however replace it with a different color component and the green goes away however then the transparency is altered in an undue way.

```
public static Texture readTexture(String filename, boolean storeAlphaChannel) throws IOException {
  return readPixels(readImage(filename), storeAlphaChannel);
}

private static Texture readPixels(BufferedImage img, boolean storeAlphaChannel) {
    int[] packedPixels = new int[img.getWidth() * img.getHeight()];

    PixelGrabber pixelgrabber = new PixelGrabber(img, 0, 0, img.getWidth(), img.getHeight(), packedPixels, 0, img.getWidth());
    try {
        pixelgrabber.grabPixels();
    } catch (InterruptedException e) {
        throw new RuntimeException();
    }

    ByteBuffer unpackedPixels = BufferUtil.newByteBuffer(packedPixels.length * 4);

  for (int row = img.getHeight() - 1; row >= 0; row--) {
    for (int col = 0; col < img.getWidth(); col++) {
      int packedPixel = packedPixels[row * img.getWidth() + col];
      if ((byte) ((packedPixel >> 8) & 0xFF) == 127) {
        unpackedPixels.put((byte) -127);
        unpackedPixels.put((byte) -127);
        unpackedPixels.put((byte) -127);
        unpackedPixels.put((byte) -127);
      }
      else {
        unpackedPixels.put((byte) ((packedPixel >> 0) & 0xFF));  //rgb...a?
        unpackedPixels.put((byte) ((packedPixel >> 8) & 0xFF));
        unpackedPixels.put((byte) ((packedPixel >> 16) & 0xFF));
        //unpackedPixels.put((byte) ((packedPixel >> 24) & 0xFF)); //this makes green come up
        unpackedPixels.put((byte) -((packedPixel >> 0) & 0xFF)); //this makes it look kinda ok, however not pixel perfect(seems different color), other options of changing this to -packedPixel >> 8 have little/no effect. using (byte) 100 makes green show up as well
      }
    }
  }

  unpackedPixels.flip();

  return new Texture(unpackedPixels, img.getWidth(), img.getHeight());
}

public static class Texture {
    private ByteBuffer pixels;
    private int width;
    private int height;

    public Texture(ByteBuffer pixels, int width, int height) {
        this.height = height;
        this.pixels = pixels;
        this.width = width;
    }
    //getters
}

//here is where all the magic happens
int loadTextureGL(String src, boolean wrap) {
    pgl = (PGraphicsOpenGL) g;
    GL gl = (GL) pgl.beginGL();
    game.glu = new GLU();

    gl.glClearColor(0.0, 0.0, 0.0, 0.0);
    gl.glColor3f(0.0, 0.0, 1.0);
    gl.glMatrixMode(GL.GL_MODELVIEW);
    gl.glLoadIdentity();
    if (settings.antialiasing) gl.glEnable(GL.GL_SMOOTH);
    gl.glEnable(GL.GL_BLEND);
    gl.glEnable(GL.GL_TEXTURE_2D);
    gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);

    int mtgl = game.mapTextureGL.length+game.sceneryTextureGL.length;

    Texture mapTextureGL = null;
    try {
        println(sketchPath+"/"+src);
        mapTextureGL = readTexture(sketchPath+"/"+src, false);
    } catch (IOException e) {
        e.printStackTrace();
        //return -1;
        throw new RuntimeException(e);
    }
    int[] tmpT = new int[1];
    tmpT[0] = mtgl;

    gl.glGenTextures(1, tmpT, 0);
    gl.glBindTexture(GL.GL_TEXTURE_2D, mtgl);
    gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);

    if (settings.textureMagNearest) {
        gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);
        gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);
    } else {
        gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
        gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
    }
    gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
    gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);

    if (settings.anisotropic && gl.isExtensionAvailable("GL_EXT_texture_filter_anisotropic") ) {
        float max[] = new float[1];
        gl.glGetFloatv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, max, 0);
        gl.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, max[0]);
    }

    try {
        game.glu.gluBuild2DMipmaps(GL.GL_TEXTURE_2D, GL.GL_RGBA, mapTextureGL.getWidth(), mapTextureGL.getHeight(), GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, mapTextureGL.getPixels());
        makeRGBTexture(gl, game.glu, mapTextureGL, GL.GL_TEXTURE_2D, true);
    } catch(GLException e) {
        System.err.println("Textures failed to bind");
    } catch(BufferUnderflowException e) {
        System.err.println("Textures failed to bind due to underflow");
  }
  pgl.endGL();

  return mtgl;
}

```

# Answer
> 1 votes
What do you mean, "**from** a ByteBuffer that holds transparency"? It looks to me like you are writing **to** a ByteBuffer. Also, what does "this makes green come up" mean?

From my understanding of your code, I can see two problems:

* The minimum value for a `byte` is `-128`, not `-127`. Lines 21 to 24 should therefore use `-128`.
* If a pixel is not transparent, then it I guess it should be opaque. So line 31 should be `unpackedPixels.put((byte) 127);`

---
Tags: java, textures, transparency, jogl
---


title: What quality should my sounds be?

text:
# Question
Title: What quality should my sounds be?
Sound and it's quality is something like religion. Never ending story.

People will say, that MP3 320kbps is lossless, while experts will say that any MP3 is crap, but in the end, no one will hear a difference in the result... unless they're in the music industry for 20 years+.

What would be the best format for video game, and what properties should be enough (Hertz, bitrate etc.), assuming that 320kbps MP3 is "heavy"?

Maybe an example or two, how some AAA titles work with their sounds.

# Answer
# Update July 2017

If you are using Unity or another big engine that has an asset management system, don't request Ogg Vorbis from your sound designers and composers. Get WAVs or AIFFs.

Unity and Unreal are structured to work with high quality bounces and then apply compression settings per-platform. Having the source asset as Ogg or Mp3 means you are double-compressing the audio and introducing additional artifacts for no benefit.

If you see that starting from ogg or mp3 reduces your build size, that's not a good reason. It likely means you are pre-exporting with different compression settings than you have applied in Unity/Unreal. Are there execptions? Yes, but you wouldn't be looking up this answer if you knew when those exceptions were applicable.

If you're pre-compressing in order to reduce the size of your repo, use LFS, use a centralized version control system, or grin and bear it.

---

# TL;DR

1. **Yes**, MP3 320k sounds great. BUT . . .
2. Don't use MP3, use Ogg Vorbis at 44.1kHz, quality 6 for music. For sound effects, just use 16/44.1 WAV unless you really feel you need the trim the fat.
3. If you have to use MP3, such as in Flash, try to use 192k-256k (VBR 1 or 2), but you may have to settle for 128k. Don't go lower than 128k (VBR 6).

# The Real Answer

> People will say, that MP3 320kbps is lossless, while experts will say that any MP3 is crap, but in the end, no one will hear a difference in the result... unless they're in the music industry for 20 years+.

Audio encoded in MP3, regardless of encoding quality, is **always** lossy. Its a perceptual codec, and therefore works by encoding properties of the sound over time in ~1152 sample chunks in a compressed form, from which uncompressed samples can be extrapolated by the decoder. Its goal is not to accurately recreate the original audio, just provide one that is "good enough".

However, like you said, 320kbps sounds very good. It's generally regarded to be as good or better than CD quality. However, it is still not possible to perfectly recreate the original samples of an uncompressed WAV encoded as a 320kbps MP3.

Generally Ogg Vorbis is a better format than MP3. It's generally agreed to give you better quality for the same size file, and unlike MP3 can be easily looped seamlessly. Those 1152-sample chunks that MP3 uses to encode audio will often leave silence at the beginning and end of a sound. Not as big a deal for basic sound effects, but a massive problem for music loops.

The Flash IDE gets around this during the .swf export, it strips out the silence manually. People using streaming audio (or pure mxmlc) achieve looping via the SampleDataEvent and manually dropping samples or preprocessing the MP3 file (see Andre Michelle's blog and the CompuPhase mp3loop utility)

Also, using an MP3 decoder technically requires you to acquire a patent license to use (since the MP3 patent is owned by Technicolor, Fraunhofer, and others). Obviously tons of people have released freeware games that used MP3, but it's best not to screw around with that.

> What would be the best format for video game, and what properties should be enough (Hertz, bitrate etc.), assuming that 320kbps MP3 is "heavy"?
>
> Maybe an example or two, how some AAA titles work with their sounds.

That depends: What are your target platforms, what other technologies are you using, how are you distributing your game, and what style are you going for? I'm going to break this down into a few categories based on platform, technology, and aesthetic.

## High-End PC and Console Titles

AAA games are going for top-of-the-line production quality, so they're recording and producing assets uncompressed 24bit/48kHz (also the standard for film postproduction). Titles with slightly lesser ambitions than say Battlefield 3 might record and produce in 16/44.1, which is the official standard for CD quality audio.

Of course you can't ship a bunch of 24/48 uncompressed WAVs with a game, it'd be too big. So ultimately there has to be some sort of compression happening. Generally the rule of thumb is, if it's a quick sound effect like a gun sound (like the Portal 2 gun fizzle in Sprunth's answer), it's fine to leave it as a WAV, possibly reducing the sample rate depending on the frequency (see the Nyquist theorem, sounds that are made up of low-frequency content can be encoded at lower sampling rates). For music, there's really no way around compression. Ogg Vorbis at CD quality is the way to go (44.1kHz, quality 5-6 or higher).

Also, AAA games will often use an intermediary tool for the compression, either an in-house tool or audio middleware like FMOD or Wwise. The way it works in FMOD and Wwise is that you import most things as 16/44.1 or 24/48 WAVs (or, if the sound is all low-frequency content, it may be imported with a lower sampling rate), then give FMOD a compression factor for each asset, choosing an encoding like ADPCM, MP3, or Ogg Vorbis.

FMOD actually recently dropped support for encoding assets in the soundbanks you export from FMOD Designer (.fsb files) as Ogg Vorbis in favor of a new codec from Xiph called CELT. Ogg Vorbis can be a little tough on the CPU, so CELT is being developed to provide an alternative. You can load the files directly, but no longer use for encoding from the Designer application.

By the way, here's a cool link about Battlefield Bad Company's audio that also goes into surround a bit. DICE is pretty much at the forefront of audio technology in games, so it's a good series for study.

Also, related to surround is the issue mono vs stereo. Just in case you didn't know, all of your sound effects should be mono, unless some of them actually make use of panning effects. Stereo's awkward to spatialize into a 3d environment, and you can pan sounds in code to place them in a 2d environment.

## Slightly-Less-High-End Titles, Indie Games

Obviously this can widely vary. A quick glance shows that Frozen Synapse uses entirely Ogg Vorbis files, for both sound effects and music. Dungeons of Dredmor on the other hand follows the scheme of Ogg Vorbis for music, and 16/44.1 WAV for sound effects.

The Dungeons of Dredmor approach is preferable. Even stored as uncompressed WAVs, the sound effects are generally short enough that they don't take up that much space, and you save a lot of CPU cycles not having to decode them. You want to be able to quickly load a sound effect into memory and play it. If you encode your sound effects in Ogg Vorbis, there's the potential for a tiny amount of delay before a player hears your sound effect for the first time.

## Browser Games, HTML5 and Flash (with a dash of Mobile)

HTML5 audio is a mess. You have to provide both ogg and MP3 versions of your sounds. Encode in the highest quality you can without your user raging at the long load time. For MP3, don't go below 128k, it's bad enough at 128.

Flash only accepts 16bit/44.1kHz MP3 unless you go nuts and write your own decoder for some other format (like the experimental Ogg Vorbis decoder in the Alchemy labs). In the past, Flash had problems with Variable Bit Rate MP3s, but I've never had a problem. The quality setting you choose for your Flash game will depend on how large you want your final .swf to be.

**Update:** As Tetrad mentioned, mobile games have to be considered with memory and storage. The way you encode your audio for mobile games is much like Flash, you want to retain as high a quality as you can, but ultimately you have to fit a memory and storage budget. Tracker music is especially good if you're on a tight storage budget for music. Tell your composer to limit his sample palette and you can fit a *ton* more music in the game.

## "8-bit" or Chiptune Type Sound Effects and Music

Most games are just going to do what Frozen Synapse and Dungeons of Dredmor do. However, you can probably get away with reducing sampling rate and bit depth. Not only might it fit the aesthetic you're going for, but it could save you some space.

Also, tracker music generally stores samples at low sample rates, just let it happen.
> 63 votes

# Answer
How the industry works with the sound, I'm not sure.

But looking through my games, most of them wrap it in some dat file or otherwise.

Here are a few bits of audio I could pull:

* Deus Ex: Human Revolution (Main Menu \[song\]) mp3 44100Hz 320kb/s
* Portal (4000 Degrees Kelvin \[song\]) mp3 44100Hz 128kb/s
* Portal 2 (Portal Gun fizzle \[soundfx\]) wav 44100Hz 16bits/sample
* Risk Factions ("NORMALLOOP\_SEGMENT03" \[soundfx\]) ogg 48000Hz 128kb/s
* Call of Juarez Bound in Blood ("COJ2\_Attack\_16" \[song\]) ogg 48000Hz 350kb/s
* Zombie Driver ("pickup\_money" \[soundfx\], "main\_menu" \[song\]) ogg 44100Hz 128kb/s
* X3 Terran Conflict ("00025" \[song\]) mp3 22050Hz 56kb/s
* Bejeweled 3 ("Coastal" \[ambient\]) ogg 44100Hz 96kb/s

Since I couldn't unpack any of the dat, etc files (except Portal 2's GCF), the results may not show the spectrum in the market. I tried to give you a sample of games, and these that don't package their audio seem to show similar results.
> 14 votes

# Answer
In my experience (mostly mobile titles), the audio quality should be as low as as possible without overt negative side effects so that you have more in memory for other things.

Keep in mind that just because there's compression involved doesn't necessarily mean that your quality is too low. Your audience isn't going to be doing side by side comparisons with the base sounds like you are, so if they're missing something through the lossy compression, they're generally not going to know about it.

For example, you have to ask yourself if there's any reason to use stereo sounds or music. Is the effect it gives you worth nearly twice the overhead? For music, depending on how it's authored, the answer might be yes. Some engines don't even support stereo sources for sound effects. That kind of thing.

Where that line is is very subjective, of course. There are other answers that go into more specific rules of thumb.

The important thing is to have standards, set them early, and try to stick to it. If you're authoring music for a game and have to half its bitrate to fit into memory, then you're going to be much worse off than if you set a low quality level in the first place.
> 6 votes

# Answer
If you're targeting a specific platform -- iPhone, Xbox 360, PS3 -- you should look into whether the hardware has an audio decoder. If so, you should use it. You'll save CPU time (and battery life!) by offloading the audio, and you'll be able to take full advantage of that platform's APIs. More importantly, that hardware acceleration will be contingent on your audio being in a specific format -- so your choice will already be made.

However, if you're targeting PC, then your options are more varied. I'd just pick the format with the smallest file size that still sounds good to your ears, and run with it.
> 4 votes

# Answer
It depends on what's going to be 'obscuring' the lossy encoding - if you look at Sprunth's answer the general trend for music is high quality for the menu, and low quality for in-game music. The reason is probably because:

* In the menus the only sound that is playing is the music - and is therefore 'in focus'; you would notice the lossy lower bitrates.
* In-game you have the sound effects (explosions etc.) in addition to the music being played at a lower volume; meaning you wouldn't notice the loss in quality.
* The call of Juarez developers seem to like overkill.

Finally another trend from his answers is that most effects are 44KHz/16bit; but some older games allowed you to run at 22KHz/16bit ('Sound quality') - in the event your sound card couldn't handle the higher sample rate.
> 4 votes

---
Tags: sound
---


# Question
Title: How do engines like Unreal relate to OpenGL or DirectX?
I'm completely new to computer graphics, and even more so, to game development. I am searching for information to learn the basics, quickly. I have one question in my head; how do engines like the Crytek Engine or the Unreal Engine relate to OpenGL or DirectX?

I'm very interested in game physics, but I can't figure out how the physics, graphics, and engine come together; there are gaps I can not fill.

# Answer
> 11 votes
TL;DR: An engine is just a collection of reusable components.

Wall of text: Games store a representation of the world, e.g. you'd have an entity like a house, which has a mesh that defines what its geometry looks like and a position.

Now, you probably have more than one entity. Let's say we've got a player controlled character and some boxes. When the player wants to move, you'd move the character and check if he collides with any boxes. That's where physics come into play. Depending on how physics are modelled, the character might just walk through the boxes, stop in front of the boxes or push the boxes.

Mind you, this only changes the internal state of the game world.

Then, after calculating movement and physics, you'd render a frame, e.g. draw the current state of the world on the screen.

OpenGL and DirectX are graphics APIs, they are only used to render stuff (e.g. the character) to the screen.

So, you're basically telling OpenGL/DirectX 'I want to draw the character at position1 and a box at position2, and ...'.

Of course, this is a gross oversimplification.

Anyway, since we don't want to walk through that procedure step by step all the time, we put that stuff into functions and classes. So, we might have a class physics which holds all the functions needed for the physics simulation, or a graphics class which interfaces with the graphics api and draws our entities. Et voila, we've got an engine.

---
Tags: opengl, physics, graphics
---


title: Do 2D games have a future?

text:
# Question
Title: Do 2D games have a future?
I'm currently working on a 2D soft-body physics engine (since none exist right now -\_-), but I'm worried that there's no point to spending what will most likely be years on it.

Although I love working on it, I doubt such an engine would get any income considering anyone willing to pay money for the library will likely to be working in 3D.

*Do 2D games have any sort of future in the game industry?<br>Should I just drop my engine and find something meaningful to work on?*

**Bonus:**

I've been trying to think of a unique way to implement my physics engine in a 2d game by looking at games that are multiple dimensions, but still in 2d perspective like Paper Mario. Any ideas?

# Answer
"People" have been declaring the death of 2D games ever since 3D games came into being. Hell, Sony even tried to outlaw 2D games of any kind on the PS1. And what's one of the most well-remembered PS1 games?

Castlevania: Symphony of the Night. A *2D game.*

2D games aren't dead; they will never be dead. Even if you wiped every 2D side-scroller off the face of the Earth, there would still be puzzle games (Tetris, etc) and other simple 2D games (SpaceChem, etc). These would gain nothing by adding a third dimension.

> Should I just drop my engine and find something meaningful to work on?

I would say that your problem probably comes from asking the wrong question.

You say you're making a "2D soft-body physics engine". That statement alone is part of the problem: you making an engine, not a *game*. Do you know what you intend to do with this "2D soft-body physics engine"? What is your gameplay? Why should people want to play your game?

If the only answer to that is that it has a "2D soft-body physics engine," then you need to rethink how you're approaching the task of making a game at all. You're thinking like a programmer: making something because it seems kind of interesting. You're not thinking like a game designer: making something because it could make for good gameplay. Programmer thinking *can* lead to good gameplay, but it's a lot less likely to.
> 65 votes

# Answer
Indeed 2D games still have a future in the game industry. I even think that 2D games are coming back in force, because of (most of the time) lower prices, because of less powerful devices, because of nostalgia.

There is plenty of 2D Indy games such as World of Goo, Aquaria, Braid, Gish, Crayon Physics etc. with a very decent number of copy sold. There is even non Indy games such as the new and very attractive Rayman Origins. I'm pretty sure there is much more to list here, but I don't get them in mind right now.

The 3D is not anymore something considered as "new", and the 2D is not anymore something considered as "old". Both of them are old, and both of them can creates something interesting that can attract players. It's up to the developers to chose the style that best deserves the game.
> 17 votes

# Answer
2D means two things - graphics and gameplay.

2D graphics are much less popular nowadays, although will never truly disappear. 2D is somewhat of an artistic choice, as many people find 2D graphics to be more beautiful than their 3D counterpart.

2D gameplay will always be going strong. The reason for this is because so many games rely on it - Tetris, Street Fighter, and Sonic are all games that work better when restricted to a 2D plane.
> 6 votes

# Answer
There may not be as many high-budget or high-profile 2D games being made for PC, Xbox or PS3 these days, but 2D games certainly do still have a future. One only has to look as far as the Apple App Store: there's an abundance of games for sale lacking a third dimension, and they're turning a profit.

The best advice I can give you in developing a 2D soft-body physics engine is to make a *game*, not an engine. You'll find that having actual game code in front of you, with actual use cases, will help design your engine and discover exactly what problems it's intended to solve. (Programmers are more likely to buy your library if they *know* it will solve their problem.)
> 5 votes

# Answer
A really short answer to debate:

Now 3D TVs are available to the masses, do you think 2D TVs have a future?

What I'm trying to say is that just because a new technology has been invented on the same platform as the one you're using, it doesn't mean it's going to replace it... I'm sure the BBC are not worrying about their investment of thousands of monoscopic cameras (single lensed).
> 5 votes

# Answer
Have you ever played this game called "Angry Birds"?
> 3 votes

# Answer
2D Game development has disappeared from large companies, but this doesn't mean that developers have stopped creating beautiful 2D games such as Angry Birds.

2D game development is the first step that we all need to go through when we want to move from classic programming to the modern game development world.

Nowadays with the power of HTML5 and the new Javascript APIs we can create 2D games for browsers without having to learn other technologies like traditional flash. With WebGL we can even create 3D games!

One could argue the answer is both "yes" and "no".

No, because every game developer no matter their age creates a 2D game for fun.

Yes, because 3D are the new standard for desktop games. Mobiles games are mostly 2D though.
> 2 votes

# Answer
2D games certainly still have their place. In the world huge bugets and large dev teams http://terraria.org thrive with over 1 million copies sold.
> 2 votes

# Answer
Most of the best game I have played where in 2D! The gameplay you can have is very different from a 3D game, and so people will still play 2D game for a long time (people still read newspaper, listen to radio and go to gigs (even classical), right?).

Take a look at Braid, Limbo and more recently Trine (not very related but mind-blowing 2D graphics, so whatever;)).

If you want to break through in the world of 2D, you have to be original. If so you'll have a sufficient income, be sure about that!
> 1 votes

# Answer
I think that 2D games will thrive for a very long time - well into, if not past, the life of your project. For the most part, 3D game graphics are still in their nascency and either require special, expensive equipment for large format games or have limited accessibility on mobile devices. On a basic physical level, complaints of headache, dizziness and nausea are common among 3D users and there is a considerable base of people who prefer 2D.

Given you are working on a physics-based game engine, I imagine that were you to decide to delve into stocking 3D games, it would be a much easier transition than were they action and graphics heavy games; rendering shapes and physical world laws into 3D is arguably much less involved than say creating a 3D environment for a first-person shooter or sport-based game.

Last, more important than 2D vs. 3D is the merit of the story line and user need. A game may be in awe inspiring 3D, but if it's not engaging, people will ultimately not be compelled to play it. Sometimes, and especially on mobile devices, simple and fast (e.g. Tetris) trumps a game full of fancy 3D effects that take a long time to load.
> 1 votes

# Answer
There will be plenty of 2D games in the future... are they going to be pixelated sprite and tiled background based... probably not.

I don't think games can simple be split on 2D and 3D. For example Xbox 360 doesn't have 2D API. Is that mean that all games on Xbox 360 are 3D? Another example is the game Chess. It's a 2D game no matter how you draw it. You can have pixalated art, vector flash art, 3d prerendered images, or a 3D rendering with all kinds of light sources and per pixel shaders. Chess is still a 2D game. I agree that if you allow some camera movement around the chess board this will add some simple 3D mechanic but I still don't want to call it 3D game.

I think we should talk about games as 2D mechanics and 3D mechanics. Your 2D soft body physics engine can easily be coupled with some fancy rendering library... as long as your gameplay remains in a plain the engine should be good.
> 0 votes

---
Tags: 2d, physics, game-industry, marketing
---


# Question
Title: Can Xcode be used to create very simple games?
I am brand new to Xcode, and I am also brand new Objective-C programmer.

I was wondering if it is possible to create simple Mac games with Xcode. If it's not possible, could you recommend me some good, cheap game engines?

# Answer
Xcode can indeed be used to create games. You can do anything a Mac/iOS device is capable of by programming in Xcode.

I think you should focus on what part of the project you want to focus on. As you state you are a brand new Objective-C programmer (welcome). In my opinion it would be quite a mouth full to try and just into Objective-C programming whilst taking on Xcode AND game development (starting with engine design continuing with game design).

If the purpose is to write great games - get a nice engine that fits your needs (3D/2D/??) - have a look at Unity if you like. If the focus is actually learning programming Objective-C and/or Xcode I'd recommend that you make some small utility programs before jumping on to game development. If the point is to simply do game programming consider the alternatives to Objective-C and Xcode - pure C/C++ or even Java.

All that said - I wish you the best of luck in your adventure!
> 7 votes

# Answer
If you'd like to learn Objective-C, I suggest you have a look at cocos2d. It's an open-source 2d engine (written in Objective-C) that allows you to write games for iOS or Mac OS using XCode.

It's not as easy to create games with as with a package like Unity, but there are lots of tutorials (and even books) for cocos2d to be found. A good place to start with lots of tutorials is Ray Wenderlichs site.
> 6 votes

# Answer
Absolutely! XCode is the standard programming IDE for the Mac and iOS. So if your goal is making a game for iOS, you will probably be using XCode along with a few other helping technologies of your choice (e.g. OpenGL ES 2.0).

But since you mentioned game engines I'd also recommend you to use one, since they'll save you a lot of time and effort:

* If you are planning to make a 2D game take a look at Cocos2D ( http://www.cocos2d-iphone.org/ ). It's quite popular.
* And if you're planning to make a 3D game, maybe Unity ( http://unity3d.com/unity/ ) would be a good bet for you. It's not Objective-C but it can publish for iOS too, if that's your goal.
> 5 votes

---
Tags: objective-c, macos, xcode
---


# Question
Title: Making abilities (Programming FFG's boardgame Descent)
I am trying to program Fantasy Flights boardgame "Descent - Journeys in the Dark", but I have hit a wall when dealing with implementing abilities, which are a crucial part of the game.

Abilities are used alot of different places, but are similar most of the time.

For a hero an ability could be: `At the start of his turn, Varikas the Dead recovers 1 fatigue`

I have written monsters with abilities like this: `Damage 2/Command`

Equipment/Treasures look like this: `When(TakingDamage):Exhaust&CancelDamage:2`, `When(MakingAttack(Type=Magic)):Gain:Surge 1` and `When(Equipped(State=StartOfTurn))):Discard&Hero.Healt=Hero.HealthMax&Hero.Fatigue=Hero.FatigueMax`

My idea is to maybe have some ability factory that will build an ability by reading the string formats, but I do not know how to implement them as a whole, and I am therefor turning to you.

Do any of you have any experience doing stuff like this, maybe when making D&D, Magic the Gathering, or maybe Descent?

Kind Regards Thediabloman

# Answer
> 2 votes
I've somewhat-implemented a solution to a similar problem to this when attempting to make a digital version of a card game, similar to Magic The Gathering. I'm also reusing a similar model to this as I attempt to implement a D&D simulator, for player Feats.

The way I handled it was to create a series of "hooks", which were points in gameplay where an ability could potentially take effect. For example, there was a hook at the start of a player's turn, before and after they drew a card, before and after they started their attack phase, etc.

I then implemented an "AbilityComponent" abstract class, which simply consisted of a single virtual function for each of those hooks. An implemented subclass would then implement the hooks appropriate to it.

From there, I created an "Ability" class which was little more than a collection of AbilityComponents, and some utility functions for managing them.

When the game ran, at each hook-point, all active effects would have their implementation of that hook called.

Following this model, you could theoretically build a string parser that, for each command, separates the command into Condition, Action, and Parameter, i.e. {Condition}:{Action1}({Parameter1},{Parameter2})&{Action2}({Parameter1}); etc.

From there, just map each parsed action string to an instance of its related Ability class, and pass through the parameters.

---
Tags: architecture
---


# Question
Title: Rendering (rasterization / ray tracing / others)
I'm completely new to this graphics and game development. I have read about Rendering (drawing a 3D graphic on a display 2D) and there are many ways of rendering, Rasterization, Ray tracing, radiosity, ray casting. And my doubt is if OpenGl implements one of these. I mean with OpenGL I can draw lines, circles and so on, so there should be a rendering algorithm on OpenGL, am I right? Which one is it?

What if I want to implement a different rendering algorithm, does this mean I'm no longer using OpenGL?

# Answer
Like Nicol said, virtually every rendering system used in modern 3D games is a rasterizer. Your graphic card is also built with rasterization in mind, so if you implement a raytracer you either have to do it on the CPU or use some more recent "general computation on GPU" technologies such as CUDA because it's not supported directly by your hardware.

With that said, you "can" implement raytracing, rasterization, radiosity, etc., in virtually any rendering system - just don't expect it to run well.

For instance, I've written (for educational purposes) a rasterizer and a raytracer from scratch on Windows Forms and the only thing I needed from the library was GDI and the Bitmap class. Everything else was calculated by the application.

So the answer to the question "Is it possible to implement a ray tracing algorithm while using OpenGL?" would be: sure, but neither the software or the hardware will be helping you, and the result might not fast enough to be used in a game or another realtime application.

What most modern games do (including those built with the enignes you mentioned) is to *fake* some of the effects of raytracing and radiosity (i.e. global illumination) by using other techniques such as shadow mapping, depth of field and ambient occlusion, which can generate visually similar results with a much smaller computational cost.
> 3 votes

# Answer
In general, you can assume that if a rendering system is not explicitly advertized as a ray tracer, then it's a rasterizer. OpenGL, D3D, REYES (much of it at least), and others are reasterizers.
> 5 votes

---
Tags: opengl, rendering
---