# Question
Title: Is my understanding of designing games in layers correct?
I have started explaining how a game is designed in layers to a friend of mine. I want to make sure that I explained things, correctly, so I wanted to verify my thoughts.

Basically, the way I understand it, games are designed with the following layers, in the following order:

1. Rendering Engine
2. Physics Engine
3. Game Engine
4. Scripted Game

Is this correct? Am I explaining this right?

# Answer
Everytime someone uses the word "engine" in relation to a component of a game, the word loses a little meaning. The term was invented in the Doom days; imagine how much meaning it has left.

Right. Not much.

"Game engine" used to have a well-defined meaning. Nowadays, "engine" is just an overblown synonym for "library" or "module".

The "Rendering engine" is nothing more than that part of a codebase which is told where to draw stuff, and that stuff gets drawn there. The "Rendering engine," in a well-architected game (hard to come by, I know) has no knowledge of who tells it what to render or where to render it. All it cares about is doing the rendering.

The "Physics engine" is again simply the part of the codebase that decides how things move around and whether they collide. It should not know or care how this information is conveyed to the user. A well-architected physics engine should not have any particular dependencies on the rendering engine, or even know that it's feeding a rendering engine. It just moves stuff around.

The "Game engine" is a concept so nebulous as to be non-existent.

A "Scripted game" (one of these things is not like the other) is a game that has scripts that control some aspect of it. Which aspects is up to the game developer. Some games expose the renderer directly to the script, thus coding most of the game in the script. Others only expose basic things like the ability to spawn entities at fixed, predefined locations to scripts. Most are inbetween. Obviously, some don't even have scripting to begin with.

Ultimately, none of these modules needs to have any relationship to one another. They can be said to be hierarchically composited, but none of them needs to know that the other exists in order to do their jobs.
> 13 votes

# Answer
This screen from Game Engine Architecture (ISBN 1568814135) provides a pretty good overview on what components you may find in a typical game engine.
> 4 votes

# Answer
I'm not sure you can explain it in terms of layers. A game engine has a lot of components, some of which you mentioned, but they are interconnected in several ways.

First of all, #3 in the list is pretty meaningless I think.

Second, Rendering and Physics may or may not be directly connected (most of the time the renderer depends at least a little bit on physics for object placement, etc.), and they may or may not be controlled by a custom scene manager. This also involves controlling the scripted entities.

I would say the components are equals that act mostly independently but can access each other's data if they need to.
> 3 votes

# Answer
Well, not quite. The process is not necessarily so linear, and what you have listed here is mainly what is required from programmers.

Depending on requirements, some of these things are not necessarily needed. Rendering engine is needed for 2d or 3d games, but for games that only rely on sound or some peripheral device output or such it might not be needed. Physics is not necessary for a broad range of games. Game engine is something that sits on top of the architecture and is compiled. Scripting is not absolutely necessary for games, and most games do not have any scripting support. Scripting is to avoid having to recompile on every small change, which will help, but for smaller games the compilation times may be so negligible that it doesn't matter.

The order in which these are built not necessarily strict. But since "Game engine" is essentially on top of the structure, it is beneficial to have the interfaces of the graphics engine and physics engine consistent during the development. Usually you would use existing solutions for graphics and physics, because the available solutions are generic enough, usable and robust and it saves a lot of time.

What you have ignored to mention here is that you need a lot of assets created too. Sounds, music, models, textures, maps, items, etc. depending on game.
> 2 votes

# Answer
Not really layers, more like parts.

There is part that deals with drawing to the screen. Another part deals with collisions. Another part deals with physics, that is, how objects get moved around in the game. Another part deals with sound and music. Another part deals with input. Another part deals with in game events. Then there is the part that contains all of the actual game content; IE the enemies, items, whatever that makes the game. You could have another part solely dedicated to AI.

All of these parts have jobs to do. Ideally, they don't care who is talking to them. All they care about is doing their job. They get something, process it, then spit something out. They don't care who sent it to them or where its going. All they care about is their job.

A game engine could be considered all the parts that are not the game content. The game content would be the assets specifically unique to a particular game; the art files, sound files, music files, and code files that get processed by the other parts into output on the screen. They are two halves of a whole.
> 2 votes

---
Tags: game-design
---


# Question
Title: Which natural language, other than English, will be most beneficial to an aspiring game developer?
Which natural language, other than English, will be most beneficial to an aspiring game developer? French, because of the Canadian game industry, or Japanese, maybe? Will AAA studios consider it an important plus point in an employee?

I understand that this is quite an open-ended question, but the FAQ states that it is okay to ask game industry related questions, including trends. Sincere apologies if I'm breaking any guidelines.

# Answer
> 4 votes
**Arabic**. It was the fastest growing language on twitter last year (tech users? revolution users?) and the country with the highest per capita GDP is Qatar, which speaks Arabic. So, lots of tech users and lots of money.

**Chinese**. Very large user base already in place with more growth expected. Fastest growing number of internet users (and already at 500 million).

# Answer
> 0 votes
Well, languages are relevant in three cases I can think of:

1. Communication within development team and associated parties during development.
2. When doing localization of product.
3. Customer service.

So, I don't know what you really want to do, but any extra languages will help in latter two. My personal view is that knowing chinese will probably get you lots of kudos.

---
Tags: game-industry
---


# Question
Title: How to set blur on mouse over and remove on mouse out in AS3?
How can I do it? I want to active glow when the mouse is over a Sprite and remove it when the mouse is out. Is it possible?

---

I have the following code:

```
var myGlow:GlowFilter = new GlowFilter();
myGlow.color = 0xFFFFFF;
myGlow.blurX = glowMobilha.blurY = 20;
var miniatura:MovieClip = _scene.d1[link];
miniatura.addEventListener(MouseEvent.CLICK,
                           function(e:Event):void {
                               MainSoundManager._sm.stopAllSounds();
                               GameManager.loadSection(link, false);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                               miniatura.filters = [myGlow];
                               miniatura.gotoAndStop(2);
                               _control.visible = true;
                               _controle.gotoAndPlay(2);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                           function(e:Event):void {
                               miniatura.gotoAndStop(1);
                               _control.visible = false;
                               _control.gotoAndStop(1);
                           });
miniatura.buttonMode = true;

```

I set the blur at:

```
miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                               miniatura.filters = [myGlow];
                               miniatura.gotoAndStop(2);
                               _control.visible = true;
                               _controle.gotoAndPlay(2);
                           });

```

How can I "hide" the blur at:

```
miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                           function(e:Event):void {
                               miniatura.gotoAndStop(1);
                               _control.visible = false;
                               _control.gotoAndStop(1);
                           });

```

---

UPDATE I think I found the solution in the following code:

```
miniatura.addEventListener(MouseEvent.MOUSE_OVER,
                           function(e:Event):void {
                           glowMobilha.alpha = 1;
                           miniatura.filters = [glowMobilha];
                           _controle.visible = true;
                           _controle.gotoAndPlay(2);
                           });
miniatura.addEventListener(MouseEvent.MOUSE_OUT,
                             function(e:Event):void {
                             glowMobilha.alpha = 0;
                             miniatura.filters = [glowMobilha];
                             _controle.visible = false;
                             _controle.gotoAndStop(1);
                           });

```

is it the best solution?

# Answer
> 1 votes
To remove the filter you need to assign to the `.filters` property:

```
miniatura.filters = [];

```

Put that in your `MOUSE_OUT` handler.

# Answer
> 1 votes
Sure it's possible. Just convert it into a button. For your four states:

* Up will be just your sprite (as usual)
* Over will be the sprite, with a glow sprite underneath

That should be it. FYI, you can put `MovieClip`s inside; so your "glow" doesn't have to be a sprite, but it can be a pulsating glow `MovieClip` that contains some sort of animation.

Just make sure the last state on the button (the one that determines the "mouse over" area) is accurate and covers the area for all four states; that is, it shouldn't include the glow area, but just the core sprite area.

---
Tags: actionscript-3, mouse, glow
---


title: Where to promote your indie game?

text:
# Question
Title: Where to promote your indie game?
> **Possible Duplicate:**
> Where to advertise my game?

Let's say I have developed a game and I want to "get it out there". What I have in mind is open-source, non-commercial games.

What websites do you know of where you can promote your newly developed game, rather than simply posting it on your blog?

# Answer
http://www.indiedb.com/ has just been created, and might be an excellent choice, in addition to David McGraw's recommendation.

http://www.igdb.com/indie Internet Game Database is a good place to add your indie game.
> 20 votes

# Answer
How-to:

www.gamasutra.com/view/feature/4117/building\_buzz\_for\_indie\_games.php

How to deal with the press:

gillen.cream.org/wordpress\_html/?page\_id=693

List of PC game reviewers:

fallout.bethsoft.com/eng/links/fallout3-reviews.php

Marketing Book:

www.sellmorevideogames.com

Viral Marketing

www.gamasutra.com/view/feature/4210/building\_the\_foundation\_of\_a\_.php

Marketing for Indie Games

www.slideshare.net/simoniker/igs-gdc-austin-john-graham-effective-marketing-for-indie-game-developers?src=related\_normal&rel=2670032

Indie Press Release service

www.gamerelease.net
> 19 votes

# Answer
I would create a post in several forums that I know of -

* gamedev.net
* devmaster.net
* tigsource.com
* igda.com

Essentially any game related forum. It's not easy 'getting it out there.' It's quite time consuming.

Aside from that, I would get active on http://www.moddb.com. There is a ton of activity and you can post your game, mod or add-on.

If you sign up on gamedev.net and pay a yearly fee one of the perks is listing your projects in their showcase - http://www.gamedev.net/community/gds/.

If you're working on something really really slick, you might want to think about writing in to some of these websites and see if they would write a post / review your game. That could help quite a bit.
> 8 votes

# Answer
**First, gamedev sites and forums:**

> (warning: their site is REALLY slow, the forum may take 20 minutes to load... don't give up as it takes a long time).

**Then, indie communities:**

**Important blogs to send your PR stuff:**

**Shareware distribution sites:**

**Advertising services:**

**PR services:**

> I will add more stuff as I remember (most of those are post-its glued to my monitor)
> 5 votes

# Answer
Two more sites for promoting are http://www.gametunnel.com/ and http://www.gamerelease.net/
> 3 votes

# Answer
Gamedev has a board on it's forum for game announcements (the Your Announcements board), which is pretty active.
There's also word of mouth - distributing it to friends, work colleagues, family. It doesn't HAVE to be on the web, though this isn't going to be as effective. On the other hand, it's a gurantee that someone will play it.

There's also forum signatures for most general use forums; especially gaming forums.

Devmaster is also a popular site.
> 3 votes

# Answer
Don't forget those high traffic sites.

CNets Download.com, tucows.com, www.brothersoft.com, etc.
> 3 votes

# Answer
Dont forget you can also write a press release, there are many sites out there that let you publish them for free, then many companies have the chance of seeing your press release.

Also send out free copies to review sites or lone reviews (individuals) If they like your game they may put it up and if you get lucky and get onto something like kotaku.com your sales could be greatly improved.

Regards

Mark
> 2 votes

# Answer
Visit www.altergamer.com - I'm the admin&manager there, use the contact form and give us some details - if we are interested, we will be happy to review your game. We are strong supporters of new and fairly ambitious projects.

Cheers, Adam
> 0 votes

---
Tags: marketing
---


# Question
Title: Facial expressions capabilities in various engines
For a research project, I am developing a small game focused on non-verbal communication clues, like facial expressions (smiling, frowning, looking bored, etc), eyegazing, proxemics, etc. My main issue is facial expressions, as I can't find detailed info on various engines capabilities on that point.

I usually believe that the engine/language used doesn't matter, as you can more or less do anything with any engine/language, but in this case I need something as efficient as possible (I am time limited).

I have reduced my options to 4:

* UDK
* Unity
* Skyrim Creation Kit
* Source Engine

So, what are the capabilities of these 4 regarding facial expressions? And let's be honest, in which of them are they the easiest to implement/manipulate?

If there is another engine more appropriate, I'll be glad to hear about it too.

Thanks!

# Answer
> 2 votes
I can't answer your question directly but I can offer some suggestions and questions to ask yourself to narrow it down...

1. Depending on your research goals, **ask yourself if you really need a realistic facial animation in the first place**. Computer faces will never be as good as the real thing. Can you literally take photos/videos of real people and use them? Image morphing? Can you use abstracted facial expressions? See http://scottmccloud.com/2-print/1-uc/index.html for a lot of interesting insights into character expression.
2. If you aren't in need of complex animations, check out http://scottmccloud.com/2009/02/25/27/ for a post about **an interactive comic-style facial expression generator**. Scott McCloud is not in the game business, but he's in the story and expression business.
3. If you're still convinced you need a game engine, do you want to create a commercial product? If yes, then do you have the budget for licensing an engine? If no, you're probably going to be struggling to make this work with something more general like Unity.
4. If you are not creating a commercial product, use one of the commercial game engines - Source, Crytek or UDK and create a mod. All of them support good facial animation. These developers are pros, and the quality of what they use (or license) will show.
5. To help you decide on which engine you'd like to use, **go play games** that use it, and decide if you like how they look. Especially play games created by the developer of the engine (e.g., Half-Life 2/TF2/L4D and Crysis). Assume that the developer of the engine may be the one who can best show off what it can do.
6. Look at the tools required, and their documentation. You are doing a "small" project, and I'm guessing don't want to get hugely involved with a massive learning curve for this. Do they make sense?
7. Pick your top 3 (mine would be Source, CryTek and UDK), and spend a day or two at most trying them out. Pick the one you got the most out of after that.

**Links to facial/animation info**

**The Grimace Project** \- http://grimace-project.net/

**CryTek** \- http://mycryengine.com/index.php?conid=17

**UDK** \- http://udk.com/features-facefx.html

**Source** \- https://developer.valvesoftware.com/wiki/Faceposer

---
Tags: face
---


# Question
Title: XNA Vertex buffer/Index buffer high memory usage?
I've got about 120mb of vertex and indices data, but when I set the data in the vertex and indices buffer it ramps up to about 300mb of memory used, this isn't really acceptable and I don't know why it is, my code to set them is:

```
        vertex_buffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, chunk_vertices.Count, BufferUsage.WriteOnly);
        vertex_buffer.SetData(chunk_vertices.ToArray());
        index_buffer = new IndexBuffer(device, IndexElementSize.ThirtyTwoBits, chunk_indices.Count, BufferUsage.WriteOnly);
        index_buffer.SetData(chunk_indices.ToArray());

```

# Answer
> 1 votes
You are storing the vertices and indexes in the chunk\_ variables to start with, which have what I'll call X amount of memory.

You then call new VertexBuffer() and new IndexBuffer() with a count and data types. These new() calls have to allocate memory to hold count\*sizeof(data type) that will be stored in the buffer plus have some overhead for their own class members. So you now have at least 2X.

Further, the calls to ToArray() as noted by David in the comments also make copies of this data, so we are now looking at 3X.

We can probably assume that your project consists of more than just this one set of data and these calls so the original value of X should be something close to half the amount of change between 120 and 300 (since we copy it twice, one copy would be about the size of X) so the original data size would be something like (300 - 120) / 2 or 90 MB.

If we split this between your Vertex and Index buffers, and noting that your vertices are 16 bytes each and your indexes are 4 bytes each (from your code above) we can figure that your original data would be something like 72 MB of Vertex data and 18 MB of Index data with 4 million+ vertex and index records. This seems a bit high to me but who knows what you are rendering.

If these seem like the correct numbers, then this explains it. If not, then you are looking at a memory leak somewhere else in your application and may need to do a little more advanced digging.

If you really want to dig into this I would suggest a tool like ANTS memory profiler. They have a free 2 week trial to get you started.

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


title: Moving a rotated model in XNA

text:
# Question
Title: Moving a rotated model in XNA
This seems like a simple problem with an equally simple solution that is invisible to me.

I have a model that spawns at the origin and looks at my player model wherever it goes.

I would like it to move forward where it's going. Whenever I try to translate it, it disappears. What am I doing wrong and how do I fix it?

```
public override void Update()
{
    //Glo is a global class, where I store the player's world.
    targetShip = Glo.world.Translation;
    targetShip.Normalize();

    //Rotates the model to face the player's position
    rotation = RotateToFace(targetShip, pos, Vector3.Up);
    pos += Vector3.Normalize(targetShip - pos) * 20f;

}

public override Matrix GetWorld()
{
    // return  rotation * translation * world ;
    return Matrix.CreateFromQuaternion(rotation) * Matrix.CreateTranslation(pos);
}

```

---

UPDATE: When I replace:

```
translation *= Matrix.CreateTranslation(direction);

```

with

```
translation *= Matrix.CreateTranslation(Vector3.Forward);

```

It now moves forward.

It does not correctly face me, however. It still thinks it's at the origin, and is rotating accordingly.

---

Here is the edited RotateToFace function The original just returns a Matrix.

```
Quaternion RotateToFace(Vector3 O, Vector3 P, Vector3 U)
{

    //The direction we're facing.
    Vector3 D = (O - P);
    //Our relative Right.
    Vector3 Right = Vector3.Cross(U, D);
    Vector3.Normalize(ref Right, out Right);
    //Our back
    Vector3 Backwards = Vector3.Cross(Right, U);
    Vector3.Normalize(ref Backwards, out Backwards);
    //Our relative up
    Vector3 Up = Vector3.Cross(Backwards, Right);
    //Make a matrix out of all of these.
    Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
    Quaternion rot2 = Quaternion.CreateFromRotationMatrix(rot);
    return rot2;
}

```

---

Draw code:

```
public void Draw(Camera camera)
{
    Matrix[] transforms = new Matrix[model.Bones.Count];
    model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (BasicEffect be in mesh.Effects)
        {
            be.EnableDefaultLighting();
            be.Projection = camera.projection;
            be.View = camera.view;
            be.World = GetWorld() * mesh.ParentBone.Transform;

        }

        mesh.Draw();
    }
}

```

# Answer
I can't figure out your code, a lot of parts in it don't make sense, such as normalizing the position. But if I understood the problem, you want to make the model to always be looking and moving in the direction of a certain target. And you already have an helper method called `RotateToFace` that takes care of the rotation part.

Then moving the model should really be as simple as taking the direction between itself and the target, and adding that direction to the model's position multiplied by a certain speed factor. Something like:

```
public class Entity
{
    public Vector3 Position { get; set; }
    public Quaternion Rotation { get; set; }
    public Vector3 Target { get; set; }
    public float Speed { get; set; }
    public float MinChaseDistance { get; set; }

    public void Update(float elapsed)
    {
        Rotation = RotateToFace(Target, Position, Vector3.Up);
        if(Vector3.Distance(Target, Position) > MinChaseDistance)
            Position += Vector3.Normalize(Target - Position) * Speed * elapsed;
    }

    public Matrix GetWorldMatrix()
    {
        return Matrix.CreateFromQuaternion(Rotation) *
               Matrix.CreateTranslation(Position);
    }
}

```

Note: Missed it earlier, but the distance check is actually essential, because if you don't have that and `Target` happens to match `Position`, you'll get a call to `Normalize` on a zero vector, and the `Position` becomes corrupt (i.e. filled with NaNs).
> 3 votes

---
Tags: xna, 3d, models, matrix, rotation
---


# Question
Title: Implementing an existing (but out of print) game electronically
One of my favorite games is the old Avalon Hill class, PanzerBlitz.

I would like to implement it electronically, and have a couple questions related to that:

1. Would I be in *legal* trouble if I do this? (note - this is not for sale or distribution)
2. How would I go about implementing the hex grid and piece database most effectively (each piece has a variety of 'factors' (movement, carryability, attack, defense, unit type)?

The game play and mechanics are already well-defined in the written rules - so I'm *not* writing the game from scratch - just programming it to follow the board game.

# Answer
> 2 votes
For question 1, see How closely can a game legally resemble another?

For question 2, you might find some past questions tagged with Hexagon useful. It's not clear whether you have referenced them yet. See https://gamedev.stackexchange.com/search?q=hexagon

# Answer
> 0 votes
Even if you can make a similar game, do not use the name, their assets(images++) or copy anything else directly without their approval.

---
Tags: legal
---


# Question
Title: Turn-based JRPG battle system architecture resources
The past months I've been busy programming a 2D JRPG (Japanese-style RPG) in C++ using the SDL library. The exploration mode is more or less done. Now I'm tackling the battle mode.

I have been unable to find any resources about how a classic turn-based JRPG battle system is structured. All I find are discussions about damage formula. I've tried googling, searching gamedev.net's message board, and crawling through C++-related questions here on Stack Exchange. I've also tried reading source code of existing open source RPGs, but without a guide of some sort it's like trying to find a needle in a haystack.

I'm not looking for a set of rules like D&D or anything similar. I'm talking purely about code and object structure design. A battle system asks the player for input using menus. Next the battle turn is executed as the heroes and the enemies execute their actions.

Can anyone point me in the right direction? Thanks in advance.

# Answer
I have never seen much resources on this subject either, but the best one I've found is probably the:

It provides insight into the enemies AI such as this:

```
AI: Setup
{
   TempVar:TurnsUntilGrenade = 3
   TempVar:GrenadeAmmo = 4
}
AI: Main
{
   If (Stage == 0) Then
   {
      If (TempVar:TurnsUntilGrenade == 0) Then
      {
         If (TempVar:GrenadeAmmo > 0) Then
         {
            Choose Random Opponent with Lowest HP
            Use Hand Grenade on Target
            TempVar:GrenadeAmmo = TempVar:GrenadeAmmo - 1
            TempVar:TurnsUntilGrenade = 3
         } Else {
            Choose Random Opponent with Lowest HP
            Use <Machine Gun> on Target
         }
      } Else {
         Choose Random Opponent
         Use <Machine Gun> on Target
         TempVar:TurnsUntilGrenade = TempVar:TurnsUntilGrenade - 1
      }
   } Else {
      If (TempVar:GrenadeAmmo > 0) Then
      {
         Choose Random Opponent with Lowest HP
         Use Hand Grenade on Target
         TempVar:GrenadeAmmo = TempVar:GrenadeAmmo - 1
      } Else {
         Choose Random Opponent
         Use <Machine Gun> on Target
      }
   }
}
AI: Counter - General
{
   If (Grenade Combatant's HP <= 3 * [Grenade Combatant's Max HP / 4]) Then
   {
      Stage = 1
   } Else {
      Stage = 0
   }
}

```

With this you can see that your enemies will probably need a state machine to manage the different states they can be in, and each state will have its own behavior to execute each turn, either hardcoded into the enemy, or data-driven by a scripting language.

There's a lot of variation even between turn based JRPGs, so there is no set of rules for all of them. For instance, you can issue *all* party commands before any of them taking place, or they can take place immediately after choosing. Attack order might be random, or more often determined by the Speed stat.

But for instance, let's say you have a purely turn based battle system, where you issue all party commands first, and then all the action happens at the end of the turn. You could approach it like:

* Store all entities (players + enemies) participating in the battle in a list.
* For each player in the list get input and store it.
* Sort the entity list by the Speed attribute.
* For each entity in the list, if it's a player execute the stored action, otherwise run the AI script for the current state.
* Advance turn and repeat.

The Battle Mechanics FAQ also has a lot of useful information, in particular about time management in the battles. But unfortunately this system (aka ATB or Active Time Battle) is patented so you can't make anything similar.

**EDIT** I also recently found this website which provides a lot of technical information about the implementation of FF7. Unfortunately the battle module sections does not seem to be completely written yet.
> 9 votes

---
Tags: c++, 2d, architecture, sdl, rpg
---


title: Android and iPhone Global Market Share

text:
# Question
Title: Android and iPhone Global Market Share
I made the mistake of making my game Android only (via libGDX). A lot of people are asking me for an iPhone/iPad version. Sigh. (Next time, I'll use Unity or Corona SDK.)

I've searched high and low, and cannot find much (relevant or recent -- beyond 2010) about market share of these two phones, globally.

**Where can I find the relative market shares of these phones, globally, to some degree of accuracy?** It doesn't have to be 100% accurate, as long as it remains recent (i.e. updated every few months). Ideally, this is something like Android's Platform Versions, albeit it tells me about different OSes.

I really want to know, because when I choose a development platform, it might matter (if I make the mistake of not using a cross-platform development tool).

# Answer
> 2 votes
Here's a chart about mobile OS market-share. The current world-wide situation is described as follows:

> At the worldwide level, Android OS and to a lesser extent Samsung are eating market share away from Symbian OS and even iOS. Nevertheless, for the time being, Symbian succeeds in keeping the leadership, followed by iOS with a narrow margin on Android. Blackberry's happy days seem however over.

The chart also allows you to see market-share by region which might be interesting if you're targeting a certain audience (for example U.S. or the Asian market). EU and U.S. seem to have a high iOS/Android market-share while Africa, South America and Asia seem to favor Symbian.

As with all statistics, this should be taken with a grain of salt, as it's not clear in what context the data was gathered. Especially in regard to game-development where a market-share in terms of app-sales would be much more interesting.

# Answer
> 1 votes
A simple google search turned up this: http://marketshare.hitslink.com/operating-system-market-share.aspx?qprid=8&qpcustomd=1 I can't vouch for its validlity though.

# Answer
> -1 votes
Here is another source: http://www.androidguys.com/2012/05/01/comscore-android-now-on-more-than-half-of-all-u-s-smartphones/

# Answer
> -3 votes
the only reason that market share should matter is if your end goal is profit. many people who make games are in it for more then just profit which is the same distinction as a "job" and a "career". It should be your decision, and you decision alone of what platform to target based on what you want to do. not what has the higher market share. this is the same decision that sometimes triple-A title developers have to make, and because of this they have to leave out market share.

you should focus on what you know, and not what has the largest market share. if you want to target multiple platforms then do it, but I don't think market share should make the decision for you.

---
Tags: operating-system
---


# Question
Title: Dynamic vertex buffer mapping call order
From the book *Introduction to 3D Game Programming with DirectX10*:

```
 // Update the vertex buffer with the new solution. Vertex* v = 0;
 HR(mVB->Map(D3D10_MAP_WRITE_DISCARD, 0, (void**)&v ));

 for(DWORD i = 0; i < mNumVertices; ++i) {
     v[i].pos = mCurrSolution[i];
     v[i].color = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f); }

 mVB->Unmap();

```

> The `ID3D10Buffer::Unmap` function must be called when you are done updating the buffer. The argument `D3D10_MAP_WRITE_DISCARD` passed into the first parameter of the Map function instructs the hardware to discard the buffer and return a pointer to a newly allocated buffer; **this prevents the hardware from stalling by allowing the hardware to continue rendering from the discarded buffer while we write to the newly allocated buffer.**

The bold text says that it's supposed to render while we are writing to the buffer. Doesn't that mean that the Draw() call should happen right after we called the Map() function?

If not, why not?

EDIT:

A second question about dynamic vbuffers: When we don't only want to change the vertices inside the buffer, but we also want to create additional vertices, would it be more performance-friendly to just create a static buffer and recreate the buffer?

# Answer
> 2 votes
The key here is that the CPU and GPU are running simultaneously, not sequentially. Typically, while the GPU is rendering frame n, the CPU (your application code) is already preparing frame n+1. When the GPU starts working on frame n+1, the CPU can start on n+2, etc.

Therefore, with dynamic resources such as vertex buffers, you really need (at least) two copies of the buffer: one copy for the GPU to render, and another for the CPU to write data into for the next frame. The CPU can't write into the same buffer the GPU is currently reading, without spoiling the concurrency between the two. At the end of each frame the two copies swap roles, so the GPU gets the buffer the CPU just finished writing, and the CPU gets back the buffer the GPU just finished rendering from.

In D3D, double-buffering of dynamic resources is hidden under the hood. The way you let D3D know it can do this is by using MAP\_WRITE\_DISCARD, which says you don't care about the previous contents of the buffer. Actually, what happens is that when you use MAP\_WRITE\_DISCARD you get the *other* buffer - the one the GPU is not currently reading. Although the book claims it's a "newly allocated" buffer, that's not really true - typically there will just be two buffers swapping roles. The "newly allocated" language really just means you can't depend on any of your old data still being in the buffer (though it might be there anyway).

---
Tags: directx10
---


title: Camera target point based on angles

text:
# Question
Title: Camera target point based on angles
I'm working on a test project to learn some basic OpenGL. Right now I'm trying to work on a "camera" with gluLookAt. My camera object is really simple, I have two vectors, one for the position and the other for the rotation (x, y and z on both). I'm having trouble with the target point gluLookAt receives, how can I find a target point using only the position and camera angle?

# Answer
> 2 votes
If you have desired rotation angles for your camera, then `gluLookAt` is not really the appropriate function to use. Instead, use `glRotate` three times, once for each axis of rotation (typically in roll, pitch, yaw order) using the negative of the desired camera angle on each axis, then `glTranslate` with the negative of the camera position.

(Why the negatives? Because you're constructing a matrix to go from world space to camera space, so everything's opposite to the transformations that go from camera space to world space.)

# Answer
> 0 votes
The position passed to `gluLookAt()` is relative to the origin. Since you have one point relative to another point, then get that point relative to the origin by subtracting the second point from it, i.e.

```
V1 - V2 = (v1.x-v2.x,v1.y-v2.y,v1.z-v2.z)

```

And pass the result to `gluLookAt()`.

After calling `gluLookat()`, call `glTranslate()` to "move" the camera to its position vector.

---
Tags: c++, mathematics
---


title: Web-based micro-transaction API

text:
# Question
Title: Web-based micro-transaction API
I am currently making a browser-based game and I would like to integrate micro-transactions. However I would prefer not to have to implement my own storefront. Does anyone know of an available framework/API? I've been looking at commonly used ones and most of them seem to be in-house work, i.e. EA's FTP games use http://www.play4free.com/en/ I'm looking for something like this but available to third parties.

The project is built on the python framework Django with a heavy Javascript frontend if that helps.

Thanks in advance.

# Answer
> 4 votes
It appears that the following three might meet your needs:

all from A look at micro-transactions services for my next game by Dave Toulouse, who covers his view of the pros and cons of these and a couple others in that post.

# Answer
> 4 votes
Another one to consider is Stripe. They have an excellent debug mode that will let you test your forms out without charging anybody anything, and they do not require you to store payment information on your own servers, which is a real win.

---
Tags: javascript, python, browser-based-games, microtransactions
---


# Question
Title: How do I get the width of a string as it would be displayed on screen?
What is the best and easiest way to get the width of a String using Slick2D?

I'm working on the achievement interface menu in my game that displays some images. On each image I need to draw a string such as "Reach Level 5.". Only problem is that I don't know how to get the string width to properly center the string on the image.

# Answer
> 3 votes
The Font class is the base class for all the fonts used in Slick2D. It has a method called `getWidth(string)` (documentation). This function returns an integer the represents the width of the string as it would be drawn. This goes for the main two classes that extend `Font`

If using TrueTypeFont you can use `getWidth(string)`, documentation.

If using UnicodeFont you can use `getWidth(string)`, documentation.

---
Tags: slick
---


title: Odd offset bug in Farseer/XNA/C#

text:
# Question
Title: Odd offset bug in Farseer/XNA/C#
So I'm using Farseer to create an immovable object:

```
[...]
private Body body;
public Immovable(World world, ContentManager c, String s, int posx, int posy, int w, int h, String user_data)
{
    texture = c.Load<Texture2D>(s);
    float converted_width = ConvertUnits.ToSimUnits(w);
    float converted_height = ConvertUnits.ToSimUnits(h);
    float converted_posx = ConvertUnits.ToSimUnits(posx);
    float converted_posy = ConvertUnits.ToSimUnits(posy);
    body = BodyFactory.CreateRectangle(world, converted_width, converted_height, 1.0f, new Vector2(converted_posx, converted_posy), user_data);
    body.BodyType = BodyType.Static;
    width = w;
    height = h;
    x = posx;
    y = posy;
}

```

What I'm trying to do is keep separate my values for screen units (here, width, height, x, and y) and my values for simulated units (here, stored in body). This way, later, when I draw the object to the screen, I can:

```
public virtual void Draw(SpriteBatch sb)
{
    sb.Draw(texture, new Rectangle(x, y, width, height), Color.White);
}

```

This way, when I instantiate things, I can visualize them as screen coordinates, which should hopefully keep me sane during all this! Theoretically (especially as these objects don't move), these two coordinate pairs should be in the same spot (or off by a maximum of one pixel if I'm truncating floats to an int somewhere).

However, for some reason, my rectangles are being offset by ~25 pixels up and to the left. Here's a screenshot:

You can see that he has "landed" just above where the rectangle is being drawn. I can float around the box to explore where the physics engine believes it is, and I find that it's up and left about 25 pixels.

Any ideas on what could be causing this?

# Answer
> 2 votes
I think when you create a physics body, the body's position is considered to be at its center of mass - which in this case since it's a rectangle, the center of mass is exactly in the middle of the rectangle. But you're drawing the sprite using the physics body position as if it were the top left corner of the sprite, instead of its center.

For starters you should use another overload of Draw, the one that takes a Vector2 position and a Vector2 origin, and set the origin to be `new Vector2(width/2, height/2)`. The one you're using is only really useful when you want to directly specify a sprite size.

---
Tags: c#, xna, 2d, farseer-physics-engine
---


title: How to mix effects together?

text:
# Question
Title: How to mix effects together?
Lets say I have got terrain effect, contains multitexturing, light. Now water effect. It must be different, but must be also affected by light. Other one, player effect, must also be affected by light, but doesn't share much stuff with others.

How all of these should be mixed together to create proper effect? Should I write multiple techniques in single effect file, or should I split it to as many as possibile and choose which are needed when rendering?

# Answer
> 3 votes
There are many ways to do it; you can write different techniques which stitch together many different shaders (you can use multiple passes to get what you want), you can write lots of pixel/vertex shaders and call lots of common functions and you can also write one massive pixel/vertex shader and use your fields to determine the flow through the algorithm (for example having a flag to determine if it should add lighting and water effects in the pixel shader). Not to mention the fact that you can apply lots of effects post process, even lighting (check out deferred rendering / deferred shading / deferred lighting, I guess deferred is the key word there). Post process effects involve rendering to a render target then running pixel shader passes on it like you would with a sprite.

However, if you want to just play around with a few different effects you can try rendering the object multiple times with different effects. To combine them all you have to do is render the first one normally and perform each subsequent render with blending turned on. It's not efficient at all, nor entirely accurate in all cases. But it's a good way to play around.

---
Tags: shaders, hlsl
---


title: C# 2D Game Library?

text:
# Question
Title: C# 2D Game Library?
I'm looking for a C# 2D game library based on something like OpenTK which wraps OpenGL for C#

Basically something like Slick2D (2D game library for Java) which is based on LWJGL which is an OpenGL wrapper for Java.

Is there something like this for C#?

# Answer
> 1 votes
There's MonoGame, I believe it is an XNA implementation that works on Mono by using OpenGL.

# Answer
> 1 votes
There's a little library called AssortedWidgets which is a GUI application using OpenTK. You can read a bit about it here.

It allows GUI interfaces like this:

# Answer
> 0 votes
Probably not exactly what you're searching for, but still.

http://www.gamedev.net/topic/602858-first-duality-demonstration/

---
Tags: c#, opengl, opentk, slick
---


# Question
Title: How do I implement smooth movement in a Box2D platform game?
I have implemented a character in JBox2D which moves with the help of a wheel rotating at the bottom of it. The movement is the best result I've had 'till now but it's a little glitchy when the character stands on the edge. So I am thinking should I use five smaller wheels instead of a big wheel. The wheel/wheels will not be visible in the finished product, now they are drawn for debugging. Here is a video. Is there a better way to do this using JBox2D?

# Answer
When using a physics system, you need to use the physics system. The way to move things around is to apply forces to them.

You mention that you'll have explosions and bullets and you want them to react correctly, that's fine. You can apply a movement force and explosions and bullets will apply their own forces too.

This will actually give you better results because your physics system needs to know all the forces and velocities of the objects to properly calculate their response. If you were to leave the physics system entirely out of the movement of your characters, when one of your characters experienced the force of an explosion, it would react as if it was standing still. Even though it may be moving towards or away from the explosion. For example: if your character is running towards an explosion, they will not be thrown back as far because of their forward momentum.

Basically, if you're using a physics system, you need to keep it up-to-date with what the objects in your world are doing.
> 1 votes

---
Tags: java, box2d, platformer, slick
---


title: Primitives does not show on screen

text:
# Question
Title: Primitives does not show on screen
I'm trying to render terrain, everything compiles fine, but I can't see anything on screen. ( I'm moving camera around in case it was on the other side)

Can't figure out whats wrong.

```
public class Terrain
    {
        public VertexBuffer vertexBuffer;
        public IndexBuffer indexBuffer;
        public VertexPositionNormalTexture[] vertices;
        public int[] indices;
        //int gridSize;

        Camera camera;
        ContentManager Content;
        GraphicsDevice device;

        Texture2D heightmap;
        public Texture2D grass;

        Effect effect;

        public Terrain(ContentManager Content, GraphicsDevice device, Camera camera)
        {
            this.Content = Content;
            this.device = device;
            this.camera = camera;

            heightmap = Content.Load<Texture2D>("Gfx//heightmap");
            grass = Content.Load<Texture2D>("Gfx//grass");

            effect = Content.Load<Effect>("Effects//terrain");

            CreateVertices();
            CreateIndices();
        }

        public void Draw()
        {
            effect.CurrentTechnique = effect.Techniques["Texture1"];
            effect.Parameters["xWorldViewProjection"].SetValue(camera.worldMatrix * camera.viewMatrix * camera.projMatrix);
            effect.Parameters["xTexture"].SetValue(grass);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                device.DrawUserIndexedPrimitives<VertexPositionNormalTexture>(PrimitiveType.TriangleList, vertices, 0, vertices.Length, indices, 0, indices.Length / 3);
            }
        }

        private void CreateVertices()
        {
            vertices = new VertexPositionNormalTexture[heightmap.Width * heightmap.Height];
            for (int x = 0; x < heightmap.Width; x++)
            {
                for (int y = 0; y < heightmap.Height; y++)
                {
                    vertices[y * heightmap.Width + x].Position = new Vector3(x, 0, y);
                    vertices[y * heightmap.Width + x].Normal = new Vector3(0, 1, 0);
                    vertices[y * heightmap.Width + x].TextureCoordinate = new Vector2(y, x);
                }
            }
            //device.SetVertexBuffer(vertexBuffer);
        }

        private void CreateIndices()
        {
            indices = new int[(heightmap.Width - 1) * (heightmap.Height - 1) * 6];
            int counter = 0;
            for (int x = 0; x < heightmap.Width - 1; x++)
            {
                for (int y = 0; y < heightmap.Height - 1; y++)
                {
                    int lowerLeft = x + y * heightmap.Width;
                    int lowerRight = (x + 1) + y * heightmap.Width;
                    int topLeft = x + (y + 1) * heightmap.Width;
                    int topRight = (x + 1) + (y + 1) * heightmap.Width;

                    indices[counter++] = topLeft;
                    indices[counter++] = lowerRight;
                    indices[counter++] = lowerLeft;

                    indices[counter++] = topLeft;
                    indices[counter++] = topRight;
                    indices[counter++] = lowerRight;
                }
            }
        }
    }

```

# Answer
* Do you have lighting enabled ? If so, does the terrain have correct normals otherwise it might result in an opaque black as the color
* What was the last thing you changed, change it back see if it works, if so figure out whats wrong with the snippet / algorithm
* Are you setting the texture correctly or are you using opaque black as some sort of default color

Otherwise you might want to check errors after rendering with your index buffer, it might well be that the indices are incorrect.
> 0 votes

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


# Question
Title: std::vector performance for pixel buffers
Doing software 2d pixel buffers, blitting, etc. Someone was telling me there's absolutely no overhead involved in using an std::vector to represent objects, I was wondering if std::vector is indeed a good container for pixel buffers or if I should instead stick with a raw array like I've always used.

Thanks

# Answer
When used properly, there shouldn't be any overhead in performance. But, they aren't exactly zero-overhead compared to raw arrays.

**Size overhead**

A typical std::vector container will use 3 pointers. Since you probably already track width and height yourself, your raw array could be done in one pointer since you already know the size.

**Allocation overhead**

You will incur some overhead when allocating the memory for the std::vector. However, this is the same overhead you incur if you allocate your own memory.

**Zero-initialization overhead**

std::vector will actually zero-init your memory when using resize(), which may or may not be significant to what you're doing.

But, from a performance standpoint, accessing a std::vector is the same as accessing an array.
> 8 votes

# Answer
When you use an std::vector, it is basically a thin wrapper around an array, which itself is basically just a block of values much like any other buffer. But the real question is why you want to do this? An std::vector is an improvement over a normal array mostly in that you can resize it by adding and removing values - but this is not an operation you would normally perform on a pixel buffer. So the vector seems to give you no benefit here.

These days you rarely use an array of pixels anyway, since most graphics are handled more efficiently using a library-specific type that is suited to the underlying hardware.
> 3 votes

# Answer
It's fine to use an `std::vector` for pixel data as long as you're careful not to allocate/deallocate/copy memory unnecessarily. For example, when you create a pixel buffer, use the vector's `resize` method to set it to the number of pixels required, then don't change its size afterward. When passing buffers around from one function to another, use a pointer or reference to the vector rather than passing by value. If you need to assign one vector to another, use the `swap` method where possible to avoid unnecessary copies.

In release builds there should be no overhead in accessing individual pixels using the vector's `operator[]`; as xcrypt mentioned in his comment, there could be some overhead in debug builds since the vector might insert range checks.
> 0 votes

---
Tags: c++, performance
---


title: GameObject and Components

text:
# Question
Title: GameObject and Components
I am creating a relatively simple game engine in C++ and Qt. I am using Irrlicht for graphics, and as of now, I will not be using any physics or audio libraries. For time's sake, I am using Irrlicht's built-in bounding-box for collision detection and neglecting audio.

Here is what I would like:

*GameObject*: An update-able container that has guaranteed components. Note that an update-able object simply means there exists a virtual function, update, that allows the object to update with respect to the time from the last rendered frame. *Updateable* is an Abstract Class.

* *TransformComponent*: Encapsulates the responsibility of storing position, rotation and size. Whenever a property is changed, *TransformComponent* emits a signal, informing its listeners that the property has changed by a given delta-value. *GameObject*'s *TransformComponent* keeps its other components aligned. For example, changing the position of a *GameObject*'s *TransformComponent* will change the position position of the *GameObject*'s graphical representation and its physics-related information. This information is relayed via signals and slots that *GameObject* handles at instantiation-time. Note that the components know nothing of each other -- *GameObject* simply handles the following task: signals from a given component need to talk to slots of another component.
* *GraphicsComponent*: Encapsulates the responsibility of rendering and playing animations. *GraphicsComponent* has a *TransformComponent*, which stores the graphical object's (Irrlicht-functionality) position, size and rotation. Note that updating a *GameObject*'s *TransformComponent* will update the *GameObject*'s *GraphicsComponent*'s *TransformComponent*. However, these \*TransformComponent\*s are loosely coupled in the sense that it is possible to update the position of *GraphicsComponent*'s *TransformComponent* without updating the position of the GameObject's *TransformComponent*. Again, this is all done via event-listeners.
* *PhysicsComponent*: Encapsulates the responsibility of determining when it has collided with another *GameObject*. This is where I am having trouble.

In order to do this, *GameObject* must know about *PhysicsComponent*, and *PhysicsComponent* must know about *GameObject*. Not only is this is a circular reference, which denotes strong coupling, but one of my Components must know about its aggregate class, which contradicts the entire purpose of black-box reuse.

For the curious, here is some example code for how my GameObject works:

```
class Player : public GameObject
{

    Q_OBJECT

    public:
        Player();
        ~Player();
    protected slots:
       void onUpdate(float deltaTime); // virtual function from GameObject
       void onEnteredCollision(GameObject* gameObject) // An imaginary function that I would like to have.
};

Player::Player() : GameObject() {
    // Initialize player-specific member variables here.
    // Here is where I would setup some specific signals and slots.
    // Below I show how I would connect Player to PhysicsComponent's onEnteredCollision signal.
    connect(getPhysicsComponent(), SIGNAL(onEnteredCollision(GameObject*), this, SLOT(onEnteredCollision(GameObject*))); // Now our method, onEnteredCollision(GameObject* gameObject) is called whenever a GameObject collides with Player.
}

void Player::onUpdate(float deltaTime) {
    // An example of how to move the character:
    getTransform()->translate(0, 10 * deltaTime, 0); // Moves Player 10 units per second in the positive y-direction.
    // An example of how to move the character's graphical object:
    getGraphics()->getTransform()->translate(10 * deltaTime, 0, 0); // Moves Player's graphical object 10 units per second in the positive x-direction.
}

void Player::onCollisionEntered(GameObject* gameObject) {
    // Collision-code goes here.
}

```

(Note that I could continue using component-based paradigms to encapsulate the idea of capturing *Player*'s collision into a *PlayerCollisionComponent*. However, the above code more than exemplifies what I would like to do, and I left that further abstraction out for simplicity.)

The issue with how this works is as aforementioned. *PhysicsComponent* must have some logic that calculates when its physics object (*Collider*, for example) has collided with another *GameObject*'s *Collider*, and then inform (through signals) which *GameObject* is being collided with. This makes *PhysicsComponent* strongly coupled with *GameObject* and also creates an ugly C++ problem with circular dependencies. In a way, it makes sense that the two are coupled, but I am convinced there must be a better alternative.

Does anyone have any feedback or experience?

Thanks in advance,

# Answer
What you're looking for is a messaging system that can communicate between components and objects, I've detailed such a system already, here:

Interaction between engine parts

The structure here is a Scene Manager that contains all Objects in a scene. Objects have a list of components that can listen for messages. Both the object and its components have a chance to listen for each message. The following code sample is generic (engine-agnostic).

**Here's the code:**

```
#include <iostream>
#include <stdio.h>

#include <list>
#include <map>

using namespace std;

struct Vector3
{
public:
    Vector3() : x(0.0f), y(0.0f), z(0.0f)
    {}

    float x, y, z;
};

enum eMessageType
{
    SetPosition,
    GetPosition,
};

class BaseMessage
{
protected: // Abstract class, constructor is protected
    BaseMessage(int destinationObjectID, eMessageType messageTypeID)
        : m_destObjectID(destinationObjectID)
        , m_messageTypeID(messageTypeID)
    {}

public: // Normally this isn't public, just doing it to keep code small
    int m_destObjectID;
    eMessageType m_messageTypeID;
};

class PositionMessage : public BaseMessage
{
protected: // Abstract class, constructor is protected
    PositionMessage(int destinationObjectID, eMessageType messageTypeID,
                    float X = 0.0f, float Y = 0.0f, float Z = 0.0f)
        : BaseMessage(destinationObjectID, messageTypeID)
        , x(X)
        , y(Y)
        , z(Z)
    {

    }

public:
    float x, y, z;
};

class MsgSetPosition : public PositionMessage
{
public:
    MsgSetPosition(int destinationObjectID, float X, float Y, float Z)
        : PositionMessage(destinationObjectID, SetPosition, X, Y, Z)
    {}
};

class MsgGetPosition : public PositionMessage
{
public:
    MsgGetPosition(int destinationObjectID)
        : PositionMessage(destinationObjectID, GetPosition)
    {}
};

class BaseComponent
{
public:
    virtual bool SendMessage(BaseMessage* msg) { return false; }
};

class RenderComponent : public BaseComponent
{
public:
    /*override*/ bool SendMessage(BaseMessage* msg)
    {
        // Object has a switch for any messages it cares about
        switch(msg->m_messageTypeID)
        {
        case SetPosition:
            {
                // Update render mesh position/translation

                cout << "RenderComponent handling SetPosition\n";
            }
            break;
        default:
            return BaseComponent::SendMessage(msg);
        }

        return true;
    }
};

class Object
{
public:
    Object(int uniqueID)
        : m_UniqueID(uniqueID)
    {
    }

    int GetObjectID() const { return m_UniqueID; }

    void AddComponent(BaseComponent* comp)
    {
        m_Components.push_back(comp);
    }

    bool SendMessage(BaseMessage* msg)
    {
        bool messageHandled = false;

        // Object has a switch for any messages it cares about
        switch(msg->m_messageTypeID)
        {
        case SetPosition:
            {
                MsgSetPosition* msgSetPos = static_cast<MsgSetPosition*>(msg);
                m_Position.x = msgSetPos->x;
                m_Position.y = msgSetPos->y;
                m_Position.z = msgSetPos->z;

                messageHandled = true;
                cout << "Object handled SetPosition\n";
            }
            break;
        case GetPosition:
            {
                MsgGetPosition* msgSetPos = static_cast<MsgGetPosition*>(msg);
                msgSetPos->x = m_Position.x;
                msgSetPos->y = m_Position.y;
                msgSetPos->z = m_Position.z;

                messageHandled = true;
                cout << "Object handling GetPosition\n";
            }
            break;
        default:
            return PassMessageToComponents(msg);
        }

        // If the object didn't handle the message but the component
        // did, we return true to signify it was handled by something.
        messageHandled |= PassMessageToComponents(msg);

        return messageHandled;
    }

private: // Methods
    bool PassMessageToComponents(BaseMessage* msg)
    {
        bool messageHandled = false;

        std::list<BaseComponent*>::iterator compIt = m_Components.begin();
        for ( compIt; compIt != m_Components.end(); ++compIt )
        {
            messageHandled |= (*compIt)->SendMessage(msg);
        }

        return messageHandled;
    }

private: // Members
    int m_UniqueID;
    std::list<BaseComponent*> m_Components;
    Vector3 m_Position;
};

class SceneManager
{
public:
    // Returns true if the object or any components handled the message
    bool SendMessage(BaseMessage* msg)
    {
        // We look for the object in the scene by its ID
        std::map<int, Object*>::iterator objIt = m_Objects.find(msg->m_destObjectID);
        if ( objIt != m_Objects.end() )
        {
            // Object was found, so send it the message
            return objIt->second->SendMessage(msg);
        }

        // Object with the specified ID wasn't found
        return false;
    }

    Object* CreateObject()
    {
        Object* newObj = new Object(nextObjectID++);
        m_Objects[newObj->GetObjectID()] = newObj;

        return newObj;
    }

private:
    std::map<int, Object*> m_Objects;
    static int nextObjectID;
};

// Initialize our static unique objectID generator
int SceneManager::nextObjectID = 0;

int main()
{
    // Create a scene manager
    SceneManager sceneMgr;

    // Have scene manager create an object for us, which
    // automatically puts the object into the scene as well
    Object* myObj = sceneMgr.CreateObject();

    // Create a render component
    RenderComponent* renderComp = new RenderComponent();

    // Attach render component to the object we made
    myObj->AddComponent(renderComp);

    // Set 'myObj' position to (1, 2, 3)
    MsgSetPosition msgSetPos(myObj->GetObjectID(), 1.0f, 2.0f, 3.0f);
    sceneMgr.SendMessage(&msgSetPos);
    cout << "Position set to (1, 2, 3) on object with ID: " << myObj->GetObjectID() << '\n';

    cout << "Retreiving position from object with ID: " << myObj->GetObjectID() << '\n';

    // Get 'myObj' position to verify it was set properly
    MsgGetPosition msgGetPos(myObj->GetObjectID());
    sceneMgr.SendMessage(&msgGetPos);
    cout << "X: " << msgGetPos.x << '\n';
    cout << "Y: " << msgGetPos.y << '\n';
    cout << "Z: " << msgGetPos.z << '\n';
}

```
> 3 votes

---
Tags: c++, collision-detection, architecture, physics, component-based
---


# Question
Title: Is there a book describing how old-school 2D games were programmed?
This fellow over on Stack Overflow has many questions on how 8/16-bit era games were programmed. I'd like to point him at a basic primer on how game loops worked, static entity arrays and rendering loops and the like; but I don't know of any such book. (And it's been so long since I was there that I've totally forgotten how I learned in the first place.)

Is there any book describing how those old cartridge games were built; or in general any single resource I can point people at for native game programming basics?

# Answer
> 6 votes
The same way they do it today. Nothing has changed about the basics of a game loop. The only difference is the language used to do it, and modern games typically access the hardware through an API like DirectX instead of speaking to the hardware directly. This is a great leap forward and gone are the days of "selecting your soundcard"

because games don't have to know the hardware anymore - they leave that to the O/S layer (eg windows), and the Windows O/S interacts with the hardware for you.

There's more though. Are you sure you want to know this?

\[Continue\] \[Cancel\]

Tricks of the Game Programming Gurus is from 1994. It talks about how games of it's time were made (like Doom 1 and Heretic). Andre Lamothe also released The Black Art of Video Game Console Design in 2005. I haven't read it.

If you want to go further back, Jordan Mechner recently released the Prince of Persia source code on github. Mechner also wrote a book about his experience developing it. There also is a pdf brief explaining the source, with diagrams and the like.

# Answer
> 3 votes
Above and beyond the answers in the question Tetrad points to in comments, there's also Racing The Beam, which takes a look at the coding and culture of the 2600 - it's by no means a perfect book, but it's well worth a look.

# Answer
> -2 votes
Well I haven't really found any good books describing it, but basically there were musicians, artists using things like deluxe paint or other custom/proprietary tools. Then the game was written in assembly using the platforms SDKs or available assemblers. Then, the game was packaged and sent off to a publisher. Anyway, if you want to be able to write them, find a book on assembly for a specific platform and learn how to program in that language.

---
Tags: education
---


# Question
Title: How to disable Y-axis movement in the Bullet physics engine
I want to create an object than only moves along the the X and Z axes, while keeping the Y-axis disabled (it's like movement in 2D, and the object wont fall down).

I'm currently using a 6 dof constraint to restrict movement in the Y-axis, but it's not working:

```
btRigidBody* zeroBody = new btRigidBody(0, NULL, NULL); // Create the body that we attach things to
btRigidBody* robot = mCarChassis->getBulletRigidBody();

btGeneric6DofConstraint* constrict = new btGeneric6DofConstraint(*robot, *zeroBody, btTransform::getIdentity(), btTransform::getIdentity(), false);

constrict->setLinearLowerLimit( btVector3( 1, 1, 1));
constrict->setLinearUpperLimit( btVector3(-1, 1,-1));

constrict->setAngularLowerLimit( btVector3( 1,  1,  1) );
constrict->setAngularUpperLimit( btVector3(-1, -1, -1) );

mBulletWorld->getBulletDynamicsWorld()->addConstraint(constrict);

```

Thanks!

# Answer
> 24 votes
The preferred way to achieve this in Bullet is to set the *linear factor* and possibly the *angular factor* for the body in question. This method is presented as a Code Snippet at the Bullet Wiki page.

In order to allow movement along only the Y-axis, you would use something like this:

```
body->setLinearFactor(btVector3(0,1,0));

```

If you additionally wish to disable rotation around any particular axis, you use the same procedure, but using the `setAngularFactor` function instead.

In this simple example video I have used the following two calls in order to disable movement along the Y-axis and to allow rotation around only the Y-axis. This effectively forces the body to remain in the XZ-plane in which it was initially created.

```
body->setLinearFactor(btVector3(1,0,1));
body->setAngularFactor(btVector3(0,1,0));

```

# Answer
> 2 votes
One way to do this is to create a physics tick callback. This will be called every time bullet ticks internally. In this call back you can set the Y velocity to 0, effectively disabling Y movement. It would look something like this:

```
void myTickCallback(const btDynamicsWorld *world, btScalar timeStep) {
    //robotBody is the btRigidBody you want to constrain the movement of
    btVector3 velocity = robotBody->getLinearVelocity();
    robotBody->setLinearVelocity(velocity.x, 0, velocity.z);
}

```

You can read more about simulation tick callbacks here.

---
Tags: c++, bullet-physics
---


# Question
Title: How do I deploy my JavaScript/HTML 5 to desktop and smartphone?
I'm looking for framework that will let me code on JS for HTML5 canvas and then will let me deploy to desktop and Android. I'm not looking to learn new stuff like Haxe or Lua. I want to do it in plain JavaScript. Is there a frame work that will allow me to do this?

# Answer
For the deploy part you can use phonegap (now called Cordova). It is an Open Source library that pt provides a framework to create "native" mobile applications using only web tecnology (HTML5, CSS3, etc)

It has two parts:

* A library for the platform's native framework that provides an special WebView class.
* A javascript library file to be included in the HTML file for each platform (\*) that serves as a bridge with the special WebView exposed by the native library above. This bridge allows accessing hardware and platform special functions (e.g. accelerometer data, camera, etc) using javascript code.

That way, you can build a "native" application which is in reality a web view that loads an URL to your local data.

So now your question is hopefully reduced to just selecting and testing an HTML game engine / library. Unfortunately I can not help you with that as I've never use HTML5 to create games (yet) but to get you started, here you have two HTML5 engines:

Beware of performance though, it varies a lot even between different OS versions.

(\*) Each platform uses a different javascript file. Just remarking it so nobody else hit the same wall I did.
> 3 votes

---
Tags: 2d, html5
---


# Question
Title: Stuck trying to decompress sections in Minecraft Anvil files (.mca)
I've been trying to write some Java code to read .mca files, based on the information at http://wiki.vg/Map\_Format and http://wiki.vg/User:Sprenger120 . I am at the point where I can read in the header correctly, and read the header for each section, telling me its compression mode and size. I am now trying to inflate the NBT blob that is the actual section, but it's not working at all. I just get "java.io.IOException: Not in GZIP format".

I'm starting the deflation stream five bytes into the memory segment specified by the header, and given that I am consistently getting sane section sizes and compression types, it seems like I'm managing to parse correctly up to this point, but now I'm stuck.

The code is at: https://github.com/Zarkonnen/Ager/tree/master/src/ager

I don't know if this is the correct forum to ask this kind of question - if it isn't, I apologise and would be very thankful if someone could direct me to a good place to ask it.

# Answer
> 0 votes
OK, so the immediate answer to this turns out to be that JNBT internally tries to decompress the stream using GZIP, so I was decompressing it twice.

In the end, the better way of going about it was to use the code supplied by Mojang at http://www.mojang.com/2012/02/new-minecraft-map-format-anvil/ .

---
Tags: java, minecraft-modding
---


# Question
Title: multiply matrix by vector: what to do if need to change y-up to z-up?
I multiply a matrix with a position vector to get a new position, however, now I need to change my matrix from y-up coordinate space to z-up. Changing only the matrix won't work: how to apply the change to the vector (change position vector from y-up to z-up)?

# Answer
You need to be more clear about the coordinate systems you're converting from and to (for instance, when Y is up, in which direction does Z point, etc). But either way it's simple to derive your matrix. I'll just do an example using this assumption:

```
   Y                 Z / Y
   |__ X      =>     |/__ X
  /
 Z

(1. Y Up)           (2. Z Up)

```

Think what happens to each axis on the left side, when it's converted to the right side:

* X in (2) is the same as X in (1)
* Y in (2) is the same as -Z in (1)
* Z in (2) is the same as Y in (1)

One idea is to encode the changes above in a simple matrix, such as the one below. It should be easy to understand the correlation between the matrix and the description above, but I've also added the multiplication so you can see the way in which it modifies the result.

```
[ 1  0  0 ]   [ x ]   [  x  ]
[ 0  0 -1 ] * [ y ] = [ -z  ]
[ 0  1  0 ]   [ z ]   [  y  ]

```

This is actually just a 90 degrees rotation matrix. You could concatenate this matrix at the end of your previous transformation, so that the conversion is done automatically as part of the matrix multiplication.

Or, alternatively you can just do it manually at the end like:

```
float y = position.Y;
position.Y = -position.Z;
position.Z = y;

```
> 3 votes

---
Tags: 3d, matrix, vector
---


# Question
Title: How to create tilted (height) isometric tiles
This is perhaps best explained pictorially. I am trying to create a 2.5D isometric game. My vision is for the game to look something like my goal:

I am not a graphics artist, so I'm having some trouble creating the "tilted" tiles to simulate terrain of different height. Creating the basic isometric tile was easy using the following steps:

1. Create a 64x64 square version of the tile
2. Rotate by 45 degrees
3. Scale the height down by a factor of 2

Creating the "tilted" tiles is more of a challenge. At my disposal I have Photoshop, but I am far from an expert at using it. Here is my current problem:

I am not sure how I can manipulate vertices, otherwise this would be easy, but basically, to get a "tilted" tile from my basic isometric tile, all I need to do is to shift the bottom and the right vertex down by 16 pixels, while fixing the other two vertices. This would generate the tile I want.

What is an easy way to accomplish this. Is Photoshop the right tool for this? Any suggestions?

# Answer
> 3 votes
You can create the tiles if you want - using Photoshop or something else. I would recommend a vector drawing program, not a pixel drawing program (I don't know enough about Photoshop etc, to know what it provides nowadays).

Personally I would suggest you don't bother creating tiles, instead have the game actually draw them using your drawing API, it's going to be a lot easier (especially if you realise how many different slanted tiles you'd need).

# Answer
> 3 votes
Keep the square 64x64 image as source, to get slanted versions you would first skew the image down on the right side (to match your image example), then rotate 45 degrees and scale it down in height. The result would be the slope you were looking for (with a bit of trial-and-error for how much to skew).

Seeing as all steps (changing the shading, skewing, rotating, scaling) besides creating the initial square are fairly simple, you might want to look into doing these steps with openGL either in startup of your game, or as an automated step in the build process (simply make a small program that can do all the skewing/rotations you need and add it to the build script).

Using vector graphics would probably be an idea if you want to continue manually making each sloped tile. Photoshop has support for vector layers so you won't need to learn a new program to try this.

---
Tags: tiles, isometric
---


title: Editing dds mip maps?

text:
# Question
Title: Editing dds mip maps?
What free software can do this? There's the Nvidia plugin for photoshop but I don't have photoshop :/.

# Answer
This isn't as easy as just having it integrated into the editor (ala their Photoshop plugin), but check out nVidia's legacy tools, which include command line utilities for manipulating DDS files.

They are at http://developer.nvidia.com/legacy-texture-tools
> 1 votes

---
Tags: textures, dds
---


title: Mathematics for Game Development Book

text:
# Question
Title: Mathematics for Game Development Book
For someone with some background in maths, what is a good book about:

* The **core mathematics** for game development
* How these techniques are **applied to common problems** in game development

In particular, I am going to finish my degree in *Physics & Computer Science* this summer, and afterwards will start an MSc. in Games Development. So I am looking for an informative read over the summer.

I know that there are a lot of books about this out there. However, I am particularly looking for a book that does *not* waste 300 pages on re-explaining what Trigonometry, Vectors or Matrices are...

Is there any book that is written for people like me with some background in maths? Something that explains the less-obvious techniques and how to apply them to solving problems in game development? Topics could include for example 3D Maths, Collision Detection / Physics, AI.

# Answer
Ok, one thing I learned about *efficient* learning is, **don't just read**. Program. The problems with "just reading" are twofold:

1) It's not very interesting, so progress can be slow

2) The knowledge evaporates quickly, unless you do activities which make it stick

So get a good book *as a reference*, so you have something to refer to, **but above all start building a game** that will use basic physics. Read when you encounter a problem you cannot solve on your own. The book's material will be that much more interesting to you then.

Some great books I used when I was starting (even though I knew vector math etc) were:

1) 3d math primer

2) Cg tutorial \- now available online for free. I wouldn't recommend using Cg as a shading language at all these days, but the first few chapters are excellent, and the basic ideas of Cg (uniform parameters etc) have their analogs in other shading languages

3) Shirley's fundamentals of computer graphics \- contains concepts such as barycentric coordinates projection and rasterization

4) Real-time collision detection for collision detection
> 6 votes

# Answer
Commenters have given many helpful tips, but so far no one has actually answered my question (apart from one person saying there is no such book).

Well, I think Mathematics for 3D Game Programming and Computer Graphics seems to be about what I had in mind when I wrote my original question. It seems to have good reviews, so that might well be it. It even has a short chapter about fluids (just saying...)

Any feedback on this book?
> 1 votes

---
Tags: mathematics, books
---


# Question
Title: XNA Calling Variables from separate Classes
I'm having some issues in XNA. I have a Player class and I would like to call a foreach function from a list which has been declared in the Game1 main class, which is below:

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

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    // Player
    Player player;
    // Landscape
    public List<Tile> tiles = new List<Tile>();

```

The following is the code I'm using and within it is the foreach:

```
if (isJumping == true)
        {
            foreach (Tile tile in tiles)
            {
                if (recTopBot.Intersects(tile.rectangle))
                {
                    position.Y += velocity.Y * curTime;
                    velocity.Y += gravity * curTime;
                }

                else
                {
                    position.Y = 320 - texture.Height;
                    velocity.Y = 0;
                    isJumping = false;
                }
            }
        }

```

It says that the name "tiles" does not exist in the current context. Now, I understand why it doesn't work, but what's the best way to fix it without modifying the classes and ruining my algorithms?

That chunk is used for detecting bottom collision for the tiles that are added in my world to make jumping + gravity work as intended.

Thank you very much!

# Answer
> 1 votes
You can make it static:

```
 public static List<Tile> tiles = new List<Tile>();

```

In your player:

```
 if (isJumping == true)
    {
        foreach (Tile tile in Game1.tiles)
        {

```

Although is not an elegant solution... I'd prefer to store the Game1 instance in your Player class

```
public class Player()
{
   public Game1 Game;
   ....

   if (isJumping == true)
   {
      foreach (Tile tile in Game.tiles)
      {
       ....
}

Player player = new Player() { Game = this; }  // From the game class

```

And you should at the end use a Environment or World class:

```
publica class Environment
{
    public static readonly Environment Instance = new Environment();

    public Game Game;
    public LevelCollection Levels;
    public PlayerCollection Players;
    public Level CurrentLevel;
    ....

}

```

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


# Question
Title: Keeping the camera from going through walls in a first person game in Unity?
I'm using a modified version of the standard Unity First Person Controller. At the moment when I stand near walls, the camera clips through and lets me see through the wall. I know about camera occlusion and have implemented it in 3rd person games, but I have no clue how I'd accomplish this in a first person game, since the camera doesn't move from the player at all.

How do other people accomplish this?

# Answer
It's probably an issue of your near clipping plane of your camera being further away than the radius on your character controller.

Either make the collision radius bigger or make the near clipping plane smaller.

If you look in the editor at the camera frustum you can easily tell if it's too far out compared to your collision radius. Here's an example:

Notice how the rear plane is clipping through the wall.
> 8 votes

# Answer
+1 to Rubber Mallet.

In "Unity 3.x Game Development Essentials" I saw the same example. Just put the camera on the top of sphere object(with collider). Also you could try to disable mesh renderer on it if you do not want to see the sphere.
> 0 votes

---
Tags: c#, unity, camera
---


# Question
Title: Clever way to do the Sonic 2 Bonus Stage effect saving memory
What would be a good way to save memory to achieve an effect like this one? http://www.youtube.com/watch?v=K89LkvL9JZ0

##

We're using pre-rendered 3D.

I'm asking this because this naive approach of just rendering all frames and putting them into a single file (sprite sheet) is producing a gigantic file, would we have to manage this loading creating multiple files?

If it helps, we are using Flex SDK.

# Answer
I dont know how technically Sonic 2 bonus stages are done, they could be computed by the cpu/special custom chip (and thus realtime) or totally precalculated and stored inside cartridge (like a very low resolution movie).

If you are using same color range, resolution and low framerate as sonic example you give, you should be able to get really lower than those 200MBs.

Here is what you could do to help to reduce the size:

* reduce color palette size as much as possible (eg: to 8 bit) (i dont know if its possible in Flex)
* use vertical/horizontal symmetry to only store the half/quarter.
* If you look closely at the first animation you provided (the straight tube) : only light yellow parts change, blue/dark yellow regions are static. To show the animation, you could use more than one layer : one that is static, one that is animated, on the top of the first one (this one will compress very well since it contains lot of transparent pixels)

Of course if your animation is running at 30 fps, and contains complex details (eg : not using flat shaded, but textured polygons) it won't help. Maybe you should give a little more information about animation you want to store ?

It your animation looks like a movie (like those laserdisc racing games in the 80's) you should check if its possible to store your animation as a H.264 file movie and play it inside Flex (dont know very well that platform so i dont know if its possible).

---

EDIT : I recently had a chance to take a look at a **Sonic 2 disassembly**.

Here is how special stage is done :

* there is no realtime rendering, everything has been precalculated and is stored in ROM
* it run at a very low frame rate : around 8 frames per second
* the internal resolution of each frame is 128x112 (when in game, it is played double size (256x224)). that's why you have vertical black borders when playing special stage (megadrive resolution is 320x224).
* it use a 8 colors palette (3 shades of blue, 4 shades of yellow and one transparent color) this mean a single pixel can be stored in only 3 bits.
* some frames are re-used in a single animation. an animation is stored as an array of frames indexes. eg for turning : 0, 1, 0, 1, 2, 3, 4, 5, 4, 5, 6.
* it use horizontal flipping for left animations (eg : left turn animation is just a h-flip of right turn)
* each frame is compressed. compression scheme is unknow (RLE maybe?) but it must use a very simple algorithm to allow megadrive to decompress frames on the fly. there is not enough RAM to store all frames uncompressed.

some stats for special stage :

* there is 56 frames in total.
* there is only a few animations : slope up, straight, slope down, curve right, begin curve right. during special stage, the game then play theses in a predefined sequence eg : straight, curve right, straight, curve right (h-flipped), straight, slope up, straight, slope down, etc...
* all frames (when compressed) take only **72.3 KB** (around 1500 bytes per frame). this is pretty small compared to size of ROM (which is 1 MB)
> 7 votes

---
Tags: 3d, flash, rendering, loading
---


title: Loading large bitmaps in Android

text:
# Question
Title: Loading large bitmaps in Android
In a few games in the Android Market/Google Play Store, huge bitmaps are drawn onto the screen.

For example, the game Unicorn Dash:

and Robot Unicorn Attack:

I'm assuming the entire island (which is multiple screens long) is loaded into memory. With probably around 10 different islands, how can something like this be possible? I've attempted to do something similar in one of my games, but I always ran out of memory. The bitmaps are (estimated) at around ~2000px x 500px at the largest which comes out to about 4mb each uncompressed? If you had 10 of them it would require 40mb of memory! So obviously I'm missing something. Is it plausible to be loading and unloading bitmaps into memory while the game runs? Or is there some other technique that I'm not aware of?

---

EDIT:

I extracted the images from Robot Unicorn Attack and saw that they were indeed whole images (not split up) of around 2000\*500 pixels.

# Answer
> Is there some other technique that I'm not aware of?

You could use OpenGL to use compressed/palletized textures (see this thread for tips) -as others pointed out in comments.

> I'm assuming the entire island (which is multiple screens long) is loaded into memory

Not necessarily.

> Is it plausible to be loading and unloading bitmaps into memory while the game runs?

Definitely. If your textures don't fit in memory, even compressed, you have to use some kind of texture streaming. In a nutshell:

* When loading the level, load only the textures necessary for the first few screens;
* Find a working heuristic to determine when to unload/load textures (e.g unload textures that are further than N screens back, and load textures that are at most N screens upfront);
* Load your new textures in a separate thread (so the game keeps running while you do so).

Be aware though that like any multithreading technique, this is error-prone and you need to design you process carefully to avoid nasty issues.
> 3 votes

# Answer
Look at how libgdx manages bitmap data to get an idea of how to get around the Java OOM Exception that you're running into. Basically, what they do is use a native backing store for the bitmap data in Gdx2DPixmap.java which is gl bound in Texture.java. I've used libgdx to bind 10-15 512x textures with no memory issues on 1st gen devices. If I tried to manage the bitmaps in Java memory, it would fail like you are seeing.
> 1 votes

---
Tags: android, resource-management
---


# Question
Title: Rotating a model AND translating it forward in XNA
I have this enemy class, and I want it to

1) Spawn at a certain place `Vector3 pos`

2) Rotate to face my player position

3) Move forward

As this code is now, it will appear at it's specified place: `pos`, and attempt to rotate to face it's target: `targetShip`. It fails to correctly face it's target, because of this offset.

If I remove the code that assigns a value to `translation`, or if I normalize `pos` then the model will appear at the origin and rotate to face it's target correctly.

If I try to move it at all using any of the comment out code regarding `translation`, It appears to start someplace else and I never can find it.

However, if I remove the code relating to `rotation`, and uncomment the code relating to `translation`, then I can get it to move forward.

The trick is doing it all together.

```
    class Enemy : BasicModel
    {

        Matrix rotation = Matrix.Identity;
        Matrix translation = Matrix.Identity;
        public Vector3 pos, up, right, targetShip,dir;

        public Enemy(Model m, Vector3 pos)
            : base(m)
        {
            up = Vector3.Up;
            //sets the position to the Vector3 as it's spawn point.
            translation = Matrix.CreateTranslation(pos);

        }

        public override void Update()
        {
            //Glo is a global class, where I store the player world.
            targetShip = Glo.world.Translation;
            targetShip.Normalize();

          pos = transform.Translation;

          rotation = RotateToFace(targetShip, pos, Vector3.Up);
          //Attempt at moving the model forward. Causes it to go out of view
          //translation *= Matrix.CreateTranslation(this.GetWorld().Backward);
          //translation *= Matrix.CreateTranslation(pos);
        }

        public override Matrix GetWorld()
        {
            return rotation * world * translation ;

        }

        /*Params: O = Our target
         * P = Our position
         * U = up.
         *
         * Code from some site I googled up.
          */
        Matrix RotateToFace(Vector3 O, Vector3 P, Vector3 U)
        {

            //The direction we're facing.
            Vector3 D = (O - P);
            //Our relative Right.
            Vector3 Right = Vector3.Cross(U, D);
            Vector3.Normalize(ref Right, out Right);
            //Our back
            Vector3 Backwards = Vector3.Cross(Right, U);
            Vector3.Normalize(ref Backwards, out Backwards);
            //Our relative up
            Vector3 Up = Vector3.Cross(Backwards, Right);
            //Make a matrix out of all of these.
            Matrix rot = new Matrix(Right.X, Right.Y, Right.Z, 0, Up.X, Up.Y, Up.Z, 0, Backwards.X, Backwards.Y, Backwards.Z, 0, 0, 0, 0, 1);
            return rot;
        }

    }
}

```

## ----

---

This is fixed now, and all this code is mostly obsolete.

# Answer
The model's position was coming up as invalid because it's position, {0,0,0} was being normalized.

Also, I changed the RotateToFace method to return a Quaternion.
> 0 votes

# Answer
```
Matrix PlayerAbsoluteTransform;

void UpdatePlayer( Vector3 EnemyPosition, float PlayerVelocity, float Seconds)
{
     Vector3 PlayerPosition = PlayerAbsoluteTransform.Translation;
     Vector3 Forward = EnemyPosition - PlayerPosition;
     Forward.Normalize();

     // This moves your player towars the enemy
     PlayerPosition += Forward * PlayerVelocity * Seconds;

     // This create the transform matrix for your model,
     // note that maybe you have to rotate the model before to face right
     PlayerAbsoluteTransform = Matrix.CreateWorld(PlayerPosition, Forward, PlayerUp);
}

```
> 1 votes

# Answer
You can try to use other way: if you know direction of enemy and position of ship, you can compute angle between current direction of enemy and new direction (ShipPosition - EnemyPosition): `angle = acos(dot(dir,newdir))`, dir and newdir should be normalized. Also compute "up vector" of this rotation by cross product: `up = cross(dir, newdir)`.

Then try to make rotation matrix according to this page in section Rotation matrix from axis and angle.
> 0 votes

# Answer
*Some remarks which won't fit in a comment; low quality answer here because it's bed time.*

That code looks nearly right.

I don't like the manual matrix creation (especially if you got it from an OpenGL website: OpenGL uses a different 'hand' for the co-ordinate system to DirectX): instead use the built-in `Matrix.CreateLookAt`.

You might try fiddling with the order of multiplication of the matrices: `a * b != b * a` with matrices.

In addition you are not looking for `Backward`, instead `Matrix.Invert()`. However, again, it doesn't work like elementary algebra so `a * b * c * Inverse(a) != b * c` \- so you will need to recalculate the entire chain of matrices again. Camera classes usually have this information baked in, which you should find extremely useful for your entity class. Basically:

```
// Fiddle with the order; it should give you the general idea though, you
// can't simply UNDO multiplication in matrices.
var world = Matrix.LookAt(pos, up, ...) * Matrix.Translate(translation, ...) * Matrix.Scale(...);
var wvp = world * view * projection;

```
> 0 votes

---
Tags: xna, models, matrix, movement, rotation
---


title: How to make a 2D Terrain with opengl?

text:
# Question
Title: How to make a 2D Terrain with opengl?
I want to make a simple 2d terrain with just a few bumps and height changes:

I thought about just using random numbers to describe the height of a certain vertex, but I don't see how I can make one mesh from this. I'm looking for a way to find the vertex and indices buffers for the terrain.
How do I do this?

# Answer
> 11 votes
Create a triangle strip. You could have your random heights at intervals equal to t. So the triangle strip would then consist of you alternating between the height vertices (with y being random and x equal to t * iteration) and vertices that go along the bottom (with y being constant and x also equal to t * iteration).

Naturaly, the distance between each vertex pair doesn't have to be constant, this is just an example of the implementation.

---
Tags: opengl, 2d, libgdx, terrain-rendering, vertex
---


# Question
Title: How are advanced graphics effects implemented?
I'm curious how 3D effects like spells in Warcraft or Torchlight are implemented graphically. I just finished a book on Direct3D and feel pretty comfortable with it and 3D graphics in general, but I am not sure how I'd do something like have a character 'cast a lightning bolt' or some other spell graphically. I would assume it has to do with particle effects or animated texture coordinates, anybody able to give me some more specific insight? Thanks

# Answer
In terms of what you are trying to accomplish you are more likely looking for an answer that relates more to game architecture.However, the rendering techniques for effects in games vary enormously, but here are a select few of those that I have come across for beginners:

* Particle Effects: These usually consist of some alpha blended or masked texture mapped to a series of quads. These quads can have any number of tranformations applied to them including gravity, wind and lifetime.
* Meshes: Loaded meshes are the bread and butter of any 3D game. Tven simple mesh with a texture moving in the right way can make for an awesome spell. For example if I had a mesh that looks like a blob with a firey texture alpha blended in and when I clicked my fire button it lobbed this blob at an enemy with an arc and random rotation I have a basic fireball.
* Simple Textured Quads: Never under estimate the power of a alpha masked texture on a quad that is drawn from the caster to the enemy and billboarded to the camera.

There are an enormous number of other techniques including even using pixel and vertex shaders but this should get you started.
> 6 votes

---
Tags: graphics, directx, graphic-effects
---


title: How to draw text on a 3d sphere?

text:
# Question
Title: How to draw text on a 3d sphere?
I am facing a problem in mapping 3d co-ordinate to screen co-ord . I require it because i want to draw text on the model . model is drawn at the 3d-cordinate, so if i know the position of that co-ord on the screen i can draw text at that position.

my view is on z axis test position is on x axis

In the follwing code I did what i said above but the transformation is not happening the way it should i.e, text should appear on the model

```
float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
Vector2 screenOrigin = new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2);
Vector3 testPosition = new Vector(10,0,0);
Vector3 cameraPosition = new vector(0,0,50),

Matrix world = Matrix.Identity;
Matrix view = Matrix.CreateLookAt(cameraPosition,Vector3.Zero, Vector3.Up);
Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), aspectRatio, 1.0f, 10000.0f);

Matrix totalEffect = world * view * projection;

Vector2 spritePos = getXYPosition(vecAndMatMultiplication(testPosition, totalEffect))+screenOrigin;

```

Where `vecAndMatMultiplication()` multiplies vector with the matrix and `getXYpostion()` should be fairly obvious.

# Answer
> 0 votes
**Short Answer**

Use the `Viewport.Project` method that already does the work for you (link to documentation):

```
Viewport viewport = GraphicsDevice.Viewport;
Vector3 screenPosition = viewport.Project(worldPosition, projection, view, world);
Vector2 spritePosition = new Vector2(screenPosition.X, screenPosition.Y);

```

So, just call it with the correct matrices, and ignore the Z value of the result.

**Long Answer**

If you want to understand what you are doing wrong in your example, it's basically because the correct procedure is not just to multiply the position by the WorldViewProjection matrix and add the screen origin. There's a little bit more to it than that.

The actual procedure is to:

* Expand position into a `Vector4` such as `(x,y,z,1)`
* Multiply that `Vector4` by the `WorldViewProjection` matrix.
* Homogenize the result back into a `Vector3` by doing `(x/w, y/w, z/w)`
* Apply the viewport transformation to map from `(-1,-1,1,1)` range to the the viewport and flip the `Y` axis so that it runs top-bottom instead of bottom-up:

```
screenX = viewportX + viewportW * (x + 1.0) * 0.5
screenY = viewportY + viewportH * (1.0 - y) * 0.5

```

I have not tested the following bit of code, but I think the implementation should be something like this:

```
public static Vector2 ConvertWorldToScreen(Vector3 source, Matrix world, Matrix view, Matrix projection, Viewport viewport)
{
    Vector4 result = Vector4.Transform(new Vector4(source, 1), world * view * projection);
    result /= result.W;
    float screenX = (float)viewport.X + (float)viewport.Width * (result.X + 1.0f) * 0.5f;
    float screenY = (float)viewport.Y + (float)viewport.Height * (1.0f - result.Y) * 0.5f;
    return new Vector2(screenX, screenY);
}

```

---
Tags: xna, text
---