title: Game Messaging System Design

text:
# Question
Title: Game Messaging System Design
I'm making a simple game, and have decided to try to implement a messaging system.

The system basically looks like this:

Entity generates message -\> message is posted to global message queue -\> messageManager notifies every object of the new message through onMessageReceived(Message msg) -\> if object wants, it acts on the message.

The way I'm making message objects is like this:

```
//base message class, never actually instantiated
abstract class Message{
  Entity sender;
}

PlayerDiedMessage extends Message{
  int livesLeft;
}

```

Now my SoundManagerEntity can do something like this in its onMessageReceived() method

```
public void messageReceived(Message msg){
  if(msg instanceof PlayerDiedMessage){
     PlayerDiedMessage diedMessage = (PlayerDiedMessage) msg;
     if(diedMessage.livesLeft == 0)
       playSound(SOUND_DEATH);
  }
}

```

The pros to this approach:

1. Very simple and easy to implement
2. The message can contain as much as information as you want, because you can just create a new Message subclass that has whatever info necessary.

The cons:

1. I can't figure out how I can recycle Message objects to a object pool, unless I have a different pool for each subclass of Message. So I have lots and lots of object creation/memory allocation over time.
2. Can't send a message to a specific recipient, but I haven't needed that yet in my game so I don't mind it too much.

What am I missing here? There must be a better implementation or some idea that I'm missing.

# Answer
> 11 votes
Simple answer is you don't want to recycle messages. One recycles objects that are either created (and removed) by thousands every frame, like particles, or are very heavy (tens of properties, long initialization process).

If you have a snow particle with some bitmap, velocities, physical attributes associated that just went down below your view, you may want to recycle it instead of creating a new particle and initializing the bitmap and randomizing attributes again. In your example there's nothing useful in the Message to keep it, and you will waste more resources on removing it's instance-specific properties, than you would just on creating a new Message object.

# Answer
> 7 votes
In my Java-based game, I came up with a very similar solution, except my message handling code looks like this:

```
@EventHandler
public void messageReceived(PlayerDiedMessage msg){
  if(diedMessage.livesLeft == 0)
     playSound(SOUND_DEATH);
}

```

I use annotations to mark a method as an event handler. Then, on game start, I use reflection to compute a mapping (or, as I call it, "piping") of messages - which method to invoke on which object when an event of a specific class is sent. This works... awesome.

The piping calculation can get a bit complicated if you want to add interfaces and subclasses to the mix, but it's fairly straightforward nonetheless. There is a slight slowdown during game load when all the classes need to be scanned, but it's done only once (and probably can be moved to a separate thread). What's gained instead is that actual sending of messages is cheaper - I don't have to invoke every "messageReceived" method in the codebase just to have it check if the event is of a good class.

# Answer
> 5 votes
**EDIT** Liosan's answer is sexier. Look into it.

---

Like Markus said, messages aren't a common candidate for object pools. Don't bother with it for the reasons he mentioned. If your game sends tons of messages of specific types, then maybe it'd be worthwhile. But then at that point I'd suggest you switch over to direct method calls.

Speaking of which,

> Can't send a message to a specific recipient, but I haven't needed that yet in my game so I don't mind it too much.

If you know a specific recipient you want to send it to, wouldn't it be pretty easy to get a reference to that object and do a direct method call on it? You could also hide specific objects behind manager classes for easier access across systems.

There's one con to your implementation, and it's that there's the potential for lots of objects to get messages that they don't really care about. Ideally your classes would only receive messages that they actually care about.

You can use a `HashMap<Class, LinkedList<Messagable>>` to associate message types with a list of objects that want to receive that type of message.

Subscribing to a message type would look something like this:

```
globalMessageQueue.subscribe(PlayerDiedMessage.getClass(), this);

```

You could implement `subscribe` like so (forgive me some mistakes, haven't written java in a couple of years):

```
private HashMap<Class, LinkedList<? extends Messagable>> subscriberMap;

void subscribe(Class messageType, Messagable receiver) {
    LinkedList<Messagable> subscriberList = subscriberMap.get(messageType);
    if (subscriberList == null) {
        subscriberList = new LinkedList<? extends Messagable>();
        subscriberMap.put(messageType, subscriberList);
    }

    subscriberList.add(receiver);
}

```

And then you could broadcast a message like this:

```
globalMessageQueue.broadcastMessage(new PlayerDiedMessage(42));

```

And `broadcastMessage` could be implemented like this:

```
void broadcastMessage(Message message) {
    Class messageType = message.getClass();
    LinkedList<? extends Messagable> subscribers = subscriberMap.get(messageType);

    for (Messagable receiver : subscribers) {
        receiver.onMessage(message);
    }
}

```

You could also subscribe to message in such a way that you can split up your message handling into different anonymous functions:

```
void setupMessageSubscribers() {
    globalMessageQueue.subscribe(PlayerDiedMessage.getClass(), new Messagable() {
        public void onMessage(Message message) {
            PlayerDiedMessage msg = (PlayerDiedMessage)message;
            if (msg.livesLeft <= 0) {
                doSomething();
            }
        }
    });

    globalMessageQueue.subscriber(EnemySpawnedMessage.getClass(), new Messagable() {
        public void onMessage(Message message) {
            EnemySpawnedMessage msg = (EnemySpawnedMessage)message;
            if (msg.isBoss) {
                freakOut();
            }
        }
    });
}

```

It's a little verbose, but helps with organization. You could also implement a second function, `subscribeAll` that will keep a separate list of `Messagable`s that want to hear about everything.

# Answer
> 1 votes
*1*. Don't.

Messages are low cost. I agree with Markus von Broady. GC will collect them fast. Try not to attach much additional info for messages. They are just messages. Finding *instance of* is an info by itself. Use it (as you did in your example).

*2*. You could try using *MessageDispatcher*.

In contrast to first solution you could have centralized message dispatcher that processes messages and passes them to intended objects.

---
Tags: architecture, messaging, object-pools
---


title: Displaying text letter by letter

text:
# Question
Title: Displaying text letter by letter
I am planing to Write a Text adventure and I don't know how to make the text draw letter by letter in any other way than changing the variable from `h` to `he` to `hel` to `hell` to `hello` That would be a terrible amount of work since there are tons of dialogue.

Here is the source code so far

```
protected override void Update(GameTime gameTime)
{
    //input code removed for clarity

    if (Dialogue == 1)
    {
        Row1 = "Input Text 1 Here.";
        Row2 = "Input Text 2 Here.";
        Row3 = "Input Text 3 Here.";
        Row4 = "Input Text 4 Here.";
    }
    if (Dialogue == 2)
    {
        Row1 = "Text 1";
        Row2 = "Text 2";
        Row3 = "Text 3";
        Row4 = "Text 4";
    }

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin();
    spriteBatch.Draw(sampleBG, new Rectangle(0, 0, 800, 600), Color.White);
    spriteBatch.Draw(TextBG, new Rectangle(0, 400, 800, 200), Color.White);
    spriteBatch.DrawString(defaultfont, Row1, new Vector2(10, (textheight + (rowspace * 0))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row2, new Vector2(10, (textheight + (rowspace * 1))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row3, new Vector2(10, (textheight + (rowspace * 2))), Color.Black);
    spriteBatch.DrawString(defaultfont, Row4, new Vector2(10, (textheight + (rowspace * 3))), Color.Black);
    spriteBatch.End();
    base.Draw(gameTime);
}

```

# Answer
I won't write the code for you, but I can put forth a conceptual path forward.

Assuming your text is displayed in a string, it is possible to iterate through the character array that makes up that string. The goal here is to print each character individually (or however many at a time you want) separated by a delta time.

When you think about it, this isn't really any different than animating a sprite. Instead of moving the index into a spritesheet, you're moving the index into a string and appending that character to the displayed string.

So, for example:

```
string fullText = "Hello World";
string currentText = "";
int currentTextIndex = 0;
float timeSinceLastIncrement = 0;

update(dt)
{
    timeSinceLastIncrement += dt;

    if(timeSinceLastIncrement >= .5)
    {
         currentText += fullText[currentTextIndex];
         currentTextIndex++;
         timeSinceLastIncrement = 0;
    }
}

draw()
{
    render(currentText);
}

```

Basically, you're maintaining the full text that will eventually be displayed, the current text that is being rendered, and the current index into the full text. `dt` is the delta time since the last update and `timeSinceLastIncrement` is the time that has passed since the last time you moved to the next character in the string. When that time (here in seconds) has gone past half a second, append the character to the current text, increment to the next character, and reset the time.

```
@ time 0, currentText = "";
@ time .5, currentText = "H";
@ time 1.0, currentText = "He";

```

And so on...
> 10 votes

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


# Question
Title: XNA 2D Rotated Rectangle Collision Response
I am using Rotated Rectangles which collide using the Separating Axis Theorem and they work perfectly fine for collision detection using Intersects and Contains.

However, I am starting to use faster objects in my game now and there is the issue of the two object overlapping during collision due to their higher velocities. I would like to do a collision response where I find out how much they are overlapping in the X and Y and put position them outside of each other.

I would like to use something like this: http://go.colorize.net/xna/2d\_collision\_response\_xna/index.html.

But I am having some issues trying to adapt this to handle the rotation of the bounds.

Is this possible? Are there any resources out there that I can look at?

# Answer
> 1 votes
I found a version of the Separating Axis theorem that includes the creation of a minimum translation vector (MTV), the use of this vector allows me to place the objects that are colliding outside of the collision and generate physics properties based on the collision.

http://www.metanetsoftware.com/technique/tutorialA.html

# Answer
> 0 votes
The simple, but resource consuming solution is to calculate multiple states in a single update. Normally we calculate the positions of the object 'A' once every update. So in 3 consecutive updates, we're gonna calculate P\_A, P\_A' and P\_A''. This is fine for most game engines, but as velocities get higher, and / or objects get smaller, the difference between P\_A and P\_A' may be too big to notice a collision that actually occurs between the two.

However, nobody says that we *have* to calculate exactly once the new position of 'A' in each update. You get the elapsed game time, and use fractions of it to calculate multiple position between P\_A and P\_A': P\_A1, P\_A2, P\_A3 etc. Then you do it for the other object ('B') as well: P\_B1, P\_B2, P\_B3 etc. Once you calculated P\_A1 and P\_B1, you do a collision detection with those positions. If there's no collision, you do it with P\_A2 and P\_B2, and so on.

Yes, this can slow down your game if you have lots of objects. If you run into performance issues, then you might have to dig deep into mathematics, I'm afraid. I'm actually representing rotated rectangles as polygons in my engine. You might want to look into Polygon collision detection, and the point-in-polygon algorithm. Maybe you can find some useful ideas.

---
Tags: xna, collision-detection, rotation
---


title: Knowing state of game in real time

text:
# Question
Title: Knowing state of game in real time
I'm trying to code a tic tac toe game in java and I need help figuring out how to efficiently and without freezing the program check if someone won the game.

I'm only in the design stages now, I haven't started programming anything but I'm wondering how would I know at all times the state of the game and exactly when someone wins?

---

Response to MarkR: (note: had to place comment here, it was too long for comment section)

It's not a homework problem, I'm trying to get more practice programming GUI's which I've only done once as a freshman in my second introductory programming course. I understand I'll have a 2D array. I plan to have a 2D integer array where x would equal 1 and o would equal 0. However, won't it take too much time if I check after every move if someone won the game? Is there a way or a data structure or algorithm I can use so that the program will know the state (when I say state I mean not just knowing every position on the board, the int array will take care of that, I mean knowing that user 1 will win if he places x on this block) of the game at all times and thus can know automatically when someone won?

# Answer
The brute force approach as recommended by others is how you should proceed. Modern CPU's, even mobile ones, can check the whole board several thousand times per second, so you should not worry about game freezing.

However in your question you ask can this be speeded up, a question that will become very important if your game becomes more complex. And the answer is 'yes', it can and it should be speeded up, and indeed you should practice this on tic-tac-toe. The idea is not to brute force check the whole grid, but to check if the last move created a winning combinatin. So you start from the newly placed move, and then check in all directions if any makes a winning move.

For tic-tac-toe, this more complex algorithm will probabaly be slower then brute force one, because 3x3 grid is very small. But the algorithm scales very nicely, where brute force approach does not.
> 7 votes

# Answer
Just do a brute force check on the grid after each turn, simple. It's a 3x3 grid. Doesn't exactly require massive amounts of computational power.
> 5 votes

# Answer
I don't think you really need to worry about "freezing the program". A function to check who has won in tic-tac-toe would be able to execute very quickly.

This sounds like a homework question - I don't want to write your answer for you. But I expect you would have some kind of two-dimensional array containing the state of each square on the board. This would have to be maintained throughout the program's running
> 4 votes

# Answer
Here's some untested C++ code adapted from http://www.gamedev.net/topic/606358-how-many-games-are-possible-in-tictactoe/page\_*view*\_findpost\_*p*\_4835877 which avoids the need for any searching. It should be fairly simple to convert to Java.

Note that most of the constants are octal. Displaying the current board is left as an exercise ;)

```
static unsigned const magic[9] = {
  010010010, 010001000, 010000101,
  001010000, 001001011, 001000100,
  000110001, 000101000, 000100110
};

enum Status {WIN, DRAW, PLAYING};

unsigned p[2] = {011111111, 011111111};
unsigned unused = 0777;
unsigned to_play = 0;

Status get_status()
{
  if (p[!to_play] & 044444444)
    return WIN; // Last move was a win
  if (p[0]+p[1] == 055555555)
    return DRAW; // Full board
  return PLAYING;
}

bool make_move(int i)
{
  if (unused & (1u<<i))
  {
    p[to_play] += magic[i];
    to_play ^= 1u;
    unused ^= 1u<<i;
    return true;
  }
  return false;
}

```
> 0 votes

---
Tags: java, state
---


title: Hills in a topdown game

text:
# Question
Title: Hills in a topdown game
I'm making a top down rpg game and was wondering if it was possible to show hills on a map instead of having everything completely flat. I've thought about changing to an isometric view, but if it can be avoided, I would rather do top down. How would I do this? Would I draw the tiles on an angle or something? Or is not possible without switching levels like in dwarf fortress?

# Answer
> 9 votes
Since you're not looking to create layers, or do Isometric, my best idea would to create something similar to a topographic map. The higher the mountain, the darker it gets, and possibly adds distinct features based on your environment (Eg: Add snow the closer to the top).

# Answer
> 22 votes
Look at one of the classic-style Zelda games. You can create the illusion of hills by using cliff faces.

---
Tags: 2d, rpg, terrain
---


title: How to draw textures on a model

text:
# Question
Title: How to draw textures on a model
The following code is a complete XNA 3.1 program almost unaltered to that code skeleton Visual Studio is creating when creating a new project.

The only things I have changed are

* imported a .x model to the content folder of the VS solution.

(the model is a simple square with a texture spanning over it - made in Google Sketchup and exported with several .x exporters)
* in the Load() method I am loading the .x model into the game.
* The Draw() method uses a BasicEffect to render the model.

Except these three things I haven't added any code.

Why does the model does not show the texture ? What can I do to make the texture visible ?

This is the texture file (a standard SketchUp texture from the palette):

And this is what my program looks like - as you can see: No texture!

Find below the complete source code of the program AND the complete .x file:

```
namespace WindowsGame1 {
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game {
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

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

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize() {
        // TODO: Add your initialization logic here
        base.Initialize();
    }

    Model newModel;

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent() {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        // TODO: usse this.Content to load your game content here

        newModel = Content.Load<Model>(@"aau3d");

        foreach (ModelMesh mesh in newModel.Meshes) {

            foreach (ModelMeshPart meshPart in mesh.MeshParts) {

                meshPart.Effect = new BasicEffect(this.GraphicsDevice, null);
            }
        }

    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent() {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime) {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime) {

        if (newModel != null) {

            GraphicsDevice.Clear(Color.CornflowerBlue);

            Matrix[] transforms = new Matrix[newModel.Bones.Count];
            newModel.CopyAbsoluteBoneTransformsTo(transforms);

            foreach (ModelMesh mesh in newModel.Meshes) {
                foreach (BasicEffect effect in mesh.Effects) {
                    effect.EnableDefaultLighting();
                    effect.TextureEnabled = true;

                    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(0)
                * Matrix.CreateTranslation(new Vector3(0, 0, 0));
                    effect.View = Matrix.CreateLookAt(new Vector3(200, 1000, 200), Vector3.Zero, Vector3.Up);
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
                        0.75f, 1.0f, 10000.0f);
                }
                mesh.Draw();
            }
        }

        base.Draw(gameTime);
    }
}

```

}

This is the model I am using (.x):

```
xof 0303txt 0032
// SketchUp 6 -> DirectX (c)2008 edecadoudal, supports: faces, normals and textures

Material Default_Material{

1.0;1.0;1.0;1.0;;
3.2;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}
Material _Groundcover_RiverRock_4inch_{
0.568627450980392;0.494117647058824;0.427450980392157;1.0;;
3.2;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
   TextureFilename { "aau3d.xGroundcover_RiverRock_4inch.jpg";   }
}
Mesh mesh_0{
 4;
 -81.6535;0.0000;74.8031;,
 -0.0000;0.0000;0.0000;,
 -81.6535;0.0000;0.0000;,
 -0.0000;0.0000;74.8031;;
 2;
 3;0,1,2,
 3;1,0,3;;
  MeshMaterialList {
  2;
  2;
  1,
  1;
  { Default_Material }
  { _Groundcover_RiverRock_4inch_ }
  }
  MeshTextureCoords {
  4;
  -2.1168,-3.4022;
  1.0000,-0.0000;
  1.0000,-3.4022;
  -2.1168,-0.0000;;
  }
  MeshNormals {
  4;
    0.0000;1.0000;-0.0000;
0.0000;1.0000;-0.0000;
0.0000;1.0000;-0.0000;
0.0000;1.0000;-0.0000;;
  2;
  3;0,1,2;
  3;1,0,3;;
  }
 }

```

# Answer
Fortunately this question has been answered by another user at SO.

If your interested in the end of the story please refer to here
> 3 votes

---
Tags: xna, textures, models
---


# Question
Title: Can I sell Windows Phone 7 games on the marketplace from India?
I am a developer from India working on a game in WP7. I need to know, can I sell my game in Windows phone apps marketplace or is it like Android market where only free/ad-based is allowed?

# Answer
> 2 votes
AFAIK it's absolutely OK to sell apps on Windows Phone marketplace. However you need to pay developer membership fee (which is 99$ per year), and submit your app (i.e. game) for certification.

I recommend you to check such info before starting working on a product in a future :-)

---
Tags: windows-phone-7, marketing
---


# Question
Title: Where might a newbie programmer begin with game development?
I just started picking up programming and I'd love to learn the ins and outs of game development so if anyone could tell me where to begin I'd really appreciate it alot. I'm interested in flash games in particular for now.

I have googled it up and such but I'm honestly lost what with so much related to the subject so a pointer in the right direction would be immensely helpful. As such any site or resource for the subject would be great.

# Answer
> 1 votes
You might want to consider GameMaker: Studio if you plan on starting with simple 2D games. It is designed to be easy to get started with. my favorite engine is Unity. It is used primarily for 3D games, and has the most intuitive interface I've seen.

However, if you would like to completely code the game, and don't feel a need for a graphical interface, you might want to consider the Slick2D library for Java, or LOVE for Lua.

---
Tags: software-engineering, flash
---


title: Monogame vs ANX vs Delta engine

text:
# Question
Title: Monogame vs ANX vs Delta engine
I am looking for a Win8-Metro-friendly framework for my next game project. Two of the non-commercial options are Monogame and ANX. Both are XNA like. I am wondering which one is more mature and reliable?

And I've already just heard about the "Delta Engine" framework, which seems like another good alternative.

What are the pros and cons of these three options?

# Answer
Yes, MonoGame is the oldest and most mature project, but it is pretty low level. The DeltaEngine does not really care if you use XNA, OpenGL, DirectX or frameworks with the same API (MonoGame, ANX, it tries to work with those frameworks, not against it) or any framework on top (SharpDX).

Delta Engine is still early in beta, but for those who want to try it out a release is coming later this month, which supports Windows 8 and Windows Phone. While in beta Delta Engine is also free to use for everyone and any beta platform, so why not try it out and see if it helps you.

Disclaimer: I was an XNA MVP from 2006-2010, also some of the ANX guys are now working for the Delta Engine. And I am the CEO of the Delta Engine ^^
> 2 votes

# Answer
I guess MonoGame is definetely more mature project than both ANX and DeltaEngine combined, with a stable builds and large user base. Also DeltaEngine license prohibits free usage on platform other than Windows.
> 1 votes

---
Tags: windows-8
---


title: Limit the amount a camera can pitch

text:
# Question
Title: Limit the amount a camera can pitch
I'm having problems trying to limit the range my camera can pitch. Currently my camera can pitch around a model without restriction, but having a hard time trying to find the value of the degree/radian the camera is currently at after pitching. Here is what I got so far:

```
    // Moves camera with thumbstick
    Pitch = pController.ThumbSticks.Right.Y * MathHelper.ToRadians(speedAngleMAX);

    // Pitch Camera around model
    public void cameraPitch(float pitch)
    {
        pitchAngle = ModelLoad.camTarget - ModelLoad.CameraPos;
        axisPitch = Vector3.Cross(Vector3.Up, pitchAngle);

        // pitch constrained to model's orientation
        axisPitch.Normalize();
        ModelLoad.CameraPos = Vector3.Transform(ModelLoad.CameraPos - ModelLoad.camTarget,
            Matrix.CreateFromAxisAngle(axisPitch, pitch)) + ModelLoad.camTarget;
    }

```

I've tried restraining the Y-camera position of `ModelLoad.CameraPos.Y`, but doing so gave me some unwanted results.

# Answer
> 1 votes
I'm assuming here that you want to restrict the pitch to a range of angles above and below the horizontal.

The horizontal vector (vector parallel to ground) for the camera direction is;

```
 cameraDir = ModelLoad.camTarget - ModelLoad.CameraPos;
 horzDir=cameraDir;
 horzDir.Y=0; //assume y-axis is up

```

Now to find the angle between the horizontal vector and the camera direction vector. To do this we normalize both vectors and get their dot product. This give us Cos(angleBetweenVectors). To recover the angle use Acos (cos inverse). Once you know the angle of pitch, you can restrict it.

```
 horzDir.Normalize();
 cameraDir.Normalize();
 float dot=Vector3.dot(horzDir,cameraDir);
 float angle=Math.Acos(dot);

```

---
Tags: xna, camera
---


# Question
Title: Wrong faces culled in OpenGL when drawing a rectangular prism
I'm trying to learn opengl. I did some code for building a rectangular prism. I don't want to draw back faces so I used `glCullFace(GL_BACK)`, `glEnable(GL_CULL_FACE);`. But I keep getting back faces also when viewing from front and also sometimes when rotating sides are vanishing. Can someone point me in right direction?

```
glPolygonMode(GL_FRONT,GL_LINE); // draw wireframe polygons
glColor3f(0,1,0); // set color green
glCullFace(GL_BACK); // don't draw back faces
glEnable(GL_CULL_FACE); // don't draw back faces
glTranslatef(-10, 1, 0); // position

     glBegin(GL_QUADS);

     // face 1
     glVertex3f(0,-1,0);
     glVertex3f(0,-1,2);
     glVertex3f(2,-1,2);
     glVertex3f(2,-1,0);

     // face 2
     glVertex3f(2,-1,2);
     glVertex3f(2,-1,0);
     glVertex3f(2,5,0);
     glVertex3f(2,5,2);

     // face 3
     glVertex3f(0,5,0);
     glVertex3f(0,5,2);
     glVertex3f(2,5,2);
     glVertex3f(2,5,0);

     // face 4
     glVertex3f(0,-1,2);
     glVertex3f(2,-1,2);
     glVertex3f(2,5,2);
     glVertex3f(0,5,2);

     // face 5
     glVertex3f(0,-1,2);
     glVertex3f(0,-1,0);
     glVertex3f(0,5,0);
     glVertex3f(0,5,2);

     // face 6
     glVertex3f(0,-1,0);
     glVertex3f(2,-1,0);
     glVertex3f(2,5,0);
     glVertex3f(0,5,0);

     glEnd();

```

# Answer
The winding of faces 1,3,5 & 6 were clockwise in your code, so openGL rendered them the 'wrong' way around. They should have had anti-clockwise winding. OpenGL uses winding to determine which side of a face is a the front(outside facing) and which side is the back (inside facing). OpenGL doesn't know you are drawing a closed box, it treats each quad individually.

To give the correct winding, imagine you are looking at the quad (or triangle) from **outside** of the box you are rendering. You should list the vertices so that they form a 'circle' going anti-clockwise. In your example;

```
 // face 1 (clockwise)
 glVertex3f(0,-1,0);
 glVertex3f(0,-1,2);
 glVertex3f(2,-1,2);
 glVertex3f(2,-1,0);

```

is treated differently than;

```
 // face 1 (anti-clockwise)
 glVertex3f(0,-1,0);
 glVertex3f(2,-1,0);
 glVertex3f(2,-1,2);
 glVertex3f(0,-1,2);

```

even though the same vertices are used, the order is different. Note that vertices 2 & 4 are swapped.

to render your box correctly, your code should be; (I've fixed faces 1,3,5 & 6);

```
 glBegin(GL_QUADS);
 // face 1
 glVertex3f(0,-1,0);
 glVertex3f(2,-1,0);
 glVertex3f(2,-1,2);
 glVertex3f(0,-1,2);

 // face 2
 glVertex3f(2,-1,2);
 glVertex3f(2,-1,0);
 glVertex3f(2,5,0);
 glVertex3f(2,5,2);

 // face 3
 glVertex3f(0,5,0);
 glVertex3f(0,5,2);
 glVertex3f(2,5,2);
 glVertex3f(2,5,0);

 // face 4

 glVertex3f(0,-1,2);
 glVertex3f(2,-1,2);
 glVertex3f(2,5,2);
 glVertex3f(0,5,2);

 // face 5
 glVertex3f(0,-1,2);
 glVertex3f(0,5,2);
 glVertex3f(0,5,0);
 glVertex3f(0,-1,0);

 // face 6
 glVertex3f(0,-1,0);
 glVertex3f(0,5,0);
 glVertex3f(2,5,0);
 glVertex3f(2,-1,0);

 glEnd();

```
> 4 votes

# Answer
You should double check the winding order of your vertices. You can read more about it here: http://www.opengl.org/sdk/docs/man/xhtml/glFrontFace.xml. Maybe try enabling face culling, then setting it to back. Other than that your code looks good.
> 0 votes

---
Tags: opengl, 3d, geometry
---


# Question
Title: Drawing "Stenciled" Sprites and making them glow
Currently, in my game - I'm not using XNA's SpriteBatch to render anything(I am using Farseer Physic's Debug View), and I was wondering how I would render something like this:

only using XNA. My second question is once I have drawn these stenciled sprites , how would I give the "stenciled" lines a glow effect like so:

I haven't done anything like this before so It is a very confusing experience for me. Any pointers?

# Answer
If the line drawing in Farseer's samples is too thin, you could use something like this library to draw thick lines.

For the glow effect, check out the XNA Bloom Sample.

The basic process is to render your scene to a render target. Then render the render-target to the screen twice: once normally and once with a blur effect using additive blending.
> 3 votes

---
Tags: xna, c#, rendering, lighting
---


# Question
Title: How should I generate and store the boundries of a cave?
I am making a small cave copter game (seriously, where did this type of game come from anyway) and I am trying to figure out how to make and store the procedural generated walls. ~~I am thinking about creating the walls by randomly picking two points away from the center of the screen. They will be no closer than the height of helicopter and no further than the edge of the screen, weighted to prefer to go in the same direction as the point prior so I end up with stalactites and stalagmites and not just noise, at set intervals of distance.~~ To store, perhaps parallel arrays/lists, one for distance from center to top screen and one for distance from center to bottom.

Am I way off base with my thinking? I just want the cave to be varied and challenging, I just have never worked with generating data like this.

Edit: Woah, I just realized that my idea would lead to a player being able to stay in the middle of the screen and win. That isn't right at all. So the very basis of how I was going to generate is wrong.

Edit 2: I also realized I left out a very crucial point. Part of the mechanics of the game will let the player go backwards therefor the data structure should be continuous.

# Answer
After edits that makes things easier. Check out this topic: How do I generate a smooth random horizontal 2D tunnel?

1. Initialize paths for `SCREEN_WIDTH + BUFFER_WIDTH` pixels.
2. Every time you go further, add more curves, but don't remove old (as you can go back)
3. I suggested curves, because pixels take more memory, though they might still be OK.
> 3 votes

# Answer
Sure, two arrays are OK, but there are two problems:

1.Position of your helicopter change, so you should translate the positions to something absolute, like screen position, as you want your walls to stay in place.

```
point1Y = - 100; //100 pixels above helicopter
point2Y = 140; //140 pixels below helicopter

topPoints[i] = helicopter.y + point1Y; // we stored screen absolute position
bottomPoints[i] = helicopter.y + point2Y;

```

2.Another problem is how to efficiently store the points. In case of an array, you would have to remove first point of each array every time the helicopter moves 1 pixel right, and also add one point per array on right side. Moving all items left in an array may be slow. Instead you can use a moving offset in the arrays:

```
//initialize arrays:
for ( var i=0; i < SCREEN_WIDTH; i++ ) {
   topPoints[i] = randomTopPointY (i); //translation is already inside
   bottomPoints[i] = randomBottomPointY (i);
}

offset = 0; //leftmost points are in topPoints[offset] and bottomPoints[offset]

function scroll ( dx:int ) {
offset += dx;
if ( offset > topPoints.length ) offset -= topPoints.length; //wrap around

for ( var i=offset - dx; i < offset; i++ ) {
  var index = i;
  if ( index < 0 ) index = topPoints.length + index; //wrap around
  topPoints[index] = randomTopPointY (index);
  bottomPoints[index] = randomBottomPointY (index);
}

```

However I recommend you make it work first, and then optimize.
> 1 votes

---
Tags: java, android, procedural-generation
---


# Question
Title: Virtual Economy Setup - Virtual currencies advice
I'm trying to figure out how to build my virtual economy. It seems like some games have one currency and some of them have up to 3 and 4 different ones.

The game is an action game which is currently single player but I'm planning on adding a tournament mode that allows users to compete against each other. The virtual goods that a user would be able to purchase would be either customization to the character or powerups and utilities that give the character more abilities in the game. The character is able to gain coins during game play.

The advice I'm trying to get is whether or not it makes sense to set up more than one currency and more than two currencies? What are the pros and cons? Reference to some resources that indicate research would be great.

# Answer
There are arguments to both options.

* Single Currency - usually simpler for players to understand
* Multiple Currencies - allows more flexibility to in future optimizations

For a single player action game I don't think you need more than two. Three of four currencies is something that is usually reserved for resource management games where you actually gain different types of supplies and currencies as part of the game play.

A standard two currency model for an action game is having a 'soft currency' and a 'hard currency':

* **Soft Currency** \- Coins that a player can collect or otherwise obtain during game play
* **Hard Currency** \- Only available to users who pay real cash

The game would normally allow users to exchange hard currency to soft currency but not the other way around. To get more users to pay some virtual goods will require a user to pay with hard currency or with amounts of soft currency that are hard to collect with game play.
> 8 votes

# Answer
There are different reasons to incorporate single and multiple currencies.

1. Single currency is a simple way to trade. Just like in real world we created it not to go from vendor to vendor, because one sells carrots we want, but he wants potatoes in exchange, and we have only oranges. So we need to look for a vendor that will trade oranges for potatoes, or oranges for anything else that someone else will trade for potatoes, or for something else that another trader will exchange for potatoes or... You get the idea.
2. Multiple currencies:

* Make your game more complex. Think of a chess game with only two pawns - players will get bored quickly. With multiple currencies you make a player think what currency he might need to get for best results, e.g. should I get more imperial credits for a new ship, or rather concentrate on collecting bottle caps to get illegal upgrades from Rogue Junkers.
    * Currency is wealth, wealth is your position in society, that is, your rank. You may divide different game mechanics to multiply not exchangeable currencies to create separated rankings.
    * A popular multiple currencies system is free/premium. One currency, e.g. gold, can be achieved by trading with others, or found in game world, the other only bought.
    * You may enable multiple currencies in different countries/fractions with an option to exchange them, to simulate a high level economy like in real world, where players can make money by buying and selling in a right time.
> 2 votes

---
Tags: mobile, monetization, economy, free-to-play
---


# Question
Title: The distance to a line from a point, find the constant values?
I have 3 points, (x1, y1), (x2, y2), (x3, y3)

I should find the AH height. For this i must use:

How can i find each "a", "b" and "c" values?

# Answer
> 6 votes
`a, b, c` describe the line passing through `B-C` so `a = y2-y3`, `b = x2-x3` and `c = x2*y3 - x3*y2`

# Answer
> 5 votes
Here's a simple way to find point H (which makes finding AH trivial):

```
V1 = A - B
V2 = C - B
t = dot(V1,V2) / dot(V2,V2)
H = B + t*V2

```

Notes:

* Definition of dot product: dot(a,b) = a.x\*b.x + a.y\*b.y
* Another definition of dot product: dot(a,b) = |a|\*|b| * cos(theta), where theta = angle between a and b. This means you can get a free cosine out of a couple of multiplications and an addition if you play your cards right - or if we know theta==0 then we get an easy |a|\*|b|.
* Picture AB and CB as two line segments that meet at B. V1 and V2 are the line segments relative to B (as if B were 0,0).
* Points along the line BC can be defined by BC(t) = B + t\*(C-B), where for example BC(0) is B, BC(1) is C, and BC(0.5) is in the middle.
* If V2 was parallel to the the x axis we could get H (the projection of V1 on V2) with a simple V1 * cos(theta). But it's not so we have to do this: |V1|\*cos(theta) * directionOf(V2), where directionOf(V2) = V2/|V2|. We can add in an extra |V2|/|V2| to get (|V1|\*|V2|\*cos(theta) * V2) / (|V2|\*|V2|), which is equivalent to (dot(V1,V2) / dot(V2,V2)) * V2. Leaving out the last V2 at first gives us 't'.
* Solution taken from "Essential Mathematics for Games and Interactive Applications" by Verth & Bishop.

---
Tags: geometry
---


title: Can I use remade sprites in my game?

text:
# Question
Title: Can I use remade sprites in my game?
> **Possible Duplicate:**
> How closely can a game resemble another game without legal problems

Can I use remade sprites in my game?

I am making a game and I used some sprites, but I didn't copy them. I remade them completely the character looks nothing like the original. I only did this to get the movement of the character right (moving, running, jumping, punching). I've been working on the game for a long time, so I really need to know is it safe and legal to do this. I do intend making a small profit.

# Answer
I do not think you will be sued. Especially if you are making a small game with profits that are too marginal to interest the big companies in the business.

My advice is not proper legal advice and is purely based on history and my experience.

Look at this famous Street Fighter character:

http://streetfighter.wikia.com/wiki/Dan

It is well known that it is a parody of characters from SNK and there is a long story behind it yet no lawsuit was ever made. It is very hard to prove a case like this. In your situation where the game I'm guessing is a small indie game, the chances of the 'theft' (inspiration) being detected is unlikely and the chance for it to be reported are even lower. Now think why would they sew someone they cannot make any reasonable profit from for something this ridicules, it will only serve to put them in a bad light.

Here is another example:

Abobo's Big Adventure

This is an indie game based entirely on a stolen character and proud of it.

Another example would be dozens of games with adult content that use famous characters like Peach without proper authorization.

The likelihood of you getting sued before all those people is lower than getting zapped by lighting in a sunny day.

If you are still concerned, apply the old saying: copying from one source is stealing, copying from multiple sources is research.

This is not legal advice. I still think I make some good points. Good luck with your game and choice you make is your own responsibility.
> 1 votes

---
Tags: sprites, legal, copyright
---


# Question
Title: Get SFML to report the version of OpenGL that is being used
How can I get SFML to report the version of OpenGL that is being used by the render window?

# Answer
> 7 votes
Create an OpenGL context with sf::RenderWindow and get the context settings with window.getSettings().

```
sf::RenderWindow window(sf::VideoMode(800, 600, 32), "SFML OpenGL");
sf::ContextSettings settings = window.getSettings();
std::cout << "OpenGL version:"<< settings.majorVersion << "." << settings.minorVersion << std::endl;

```

---
Tags: opengl, sfml
---


title: Interleaving Arrays in OpenGL

text:
# Question
Title: Interleaving Arrays in OpenGL
In my pursuit to write code that matches todays OpenGL standards I have found that I am completely clueless about interleaving arrays. I've tried and debugged just about everywhere I can think of but I can't get my model to render using interleaved arrays (It worked when it was configuered to use multiple arrays) Now I know that all the data is properly being parsed from an obj file and information is being copied properly copied into the Vertex object array, but I still can't seem to get anything to render. Below is the code for initializing a model and drawing it (along with the Vertex struct for reference.)

Vertex:

```
struct Vertex {
    glm::vec3 position;
    glm::vec3 normal;
    glm::vec2 uv;
    glm::vec3 tangent;
    glm::vec3 bitangent;
};

```

Model Constructor:

```
Model::Model(const char* filename) {
    bool result = loadObj(filename, vertices, indices);

    glGenVertexArrays(1, &vertexArrayID);
    glBindVertexArray(vertexArrayID);

    glGenBuffers(1, &vertexbuffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW);

    glGenBuffers(1, &elementbuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW);
}

```

Draw Model:

```
Model::Draw(ICamera camera) {
    GLuint matrixID = glGetUniformLocation(programID, "mvp");
    GLuint positionID = glGetAttribLocation(programID, "position_modelspace");
    GLuint uvID = glGetAttribLocation(programID, "uv");
    GLuint normalID = glGetAttribLocation(programID, "normal_modelspace");
    GLuint tangentID = glGetAttribLocation(programID, "tangent_modelspace");
    GLuint bitangentID = glGetAttribLocation(programID, "bitangent_modelspace");

    glm::mat4 projection = camera->GetProjectionMatrix();
    glm::mat4 view = camera->GetViewMatrix();
    glm::mat4 model = glm::mat4(1.0f);
    glm::mat4 mvp = projection * view * model;

    glUniformMatrix4fv(matrixID, 1, GL_FALSE, &mvp[0][0]);

    glBindVertexArray(vertexArrayID);

    glEnableVertexAttribArray(positionID);
    glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
    glVertexAttribPointer(positionID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].position);

    glEnableVertexAttribArray(uvID);
    glVertexAttribPointer(uvID, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].uv);

    glEnableVertexAttribArray(normalID);
    glVertexAttribPointer(normalID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].normal);

    glEnableVertexAttribArray(tangentID);
    glVertexAttribPointer(tangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].tangent);

    glEnableVertexAttribArray(bitangentID);
    glVertexAttribPointer(bitangentID, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), &vertices[0].bitangent);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementbuffer);
    glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, (void*)0);

    glDisableVertexAttribArray(positionID);
    glDisableVertexAttribArray(uvID);
    glDisableVertexAttribArray(normalID);
    glDisableVertexAttribArray(tangentID);
    glDisableVertexAttribArray(bitangentID);
}

```

# Answer
I think you want to change your attribute pointers, specifically the offsets you have listed. `&vertices[0].position` should be `0`, `&vertices[0].normal` should be `12`, `&vertices[0].uv` should be `24`, and so on.

Since getting the address of a struct member gives you the absolute address instead of the address relative to the beginning of the struct. `glVertexAttribPointer` is looking for the offset into your interleaved set.

```
struct Vertex {          //previousfloats * sizeof(float) = offset
    glm::vec3 position;  // 0 * 4 = 0
    glm::vec3 normal;    // 3 * 4 = 12
    glm::vec2 uv;        // 6 * 4 = 24
    glm::vec3 tangent;   // 8 * 4 = 32
    glm::vec3 bitangent; // 11 * 4 = 44
};

```

See the documentation for the `glVertexAttribPointer` here. The big hint being:

> *pointer*
>
> Specifies a pointer to the first component of the first generic vertex attribute in the array. **The initial value is 0**.
> 8 votes

---
Tags: c++, opengl, vbo
---


# Question
Title: How would I balance a multiplayer competitive game
I'm looking at my first foray into developing a game, and would love to know whether you guys have any thoughts on game balancing on limited multiplayer games.

The game I have in mind involves a neutral player that has to achieve a goal, with two supporting "deity" players who are one of 'good' and 'evil' - One of the deity players would try to help the player achieve their goal, while the other would try to thwart them.

Any thoughts or pointers on how I can ensure the deities are balanced?

If you want me to expand, I will, just didn't want to give away too much of the game play before I finish it.

# Answer
> 10 votes
The simplest way to ensure things are balanced is to make them the same. Give both sides the same powers, give them different names and change their visual effects.

I agree, that's pretty boring and likely won't give you very interesting game play. However, it's a good starting point.

Once you've got a good starting point, with good and evil having very similar "base" abilities, you expand. But you always expand both good and evil, in the same ways. Either give both sides similar abilities or give them equal but opposite abilities. Giving the evil deity a ability to create walls? Give the good deity an ability to remove walls. Giving the good deity an ability to heal over time? Give the evil deity a way to harm over time.

OK, things have gotten a bit more interesting. Deities don't have the exact same abilities anymore with just different visual effects. But, still kind of boring and not really there yet.

Next up is adding unique abilities for both sides. This is where you want to do some heavy play testing. When you're adding abilities that don't have a "counter ability" on the other side, it's important to play test. Obviously you'll want to play test with all the abilities, but these are the most likely to introduce unbalanced play.

# Answer
> 7 votes
Play test. Play test some more. And keep play testing.

One good metric during play testing for balance is win ratio. A truly "balanced" game would have each side winning 50% of the time. Keep this in mind, as it can help with the "boringness" of equal-but-opposite that Byte56 suggests to a degree. Here's how to expand on his excellent answer:

By making some skills not quite equal to their opposite, but gaining a bonus elsewhere, the game can feel more strategic since certain skills have an advantage or disadvantage. Some examples: evil can make 2 walls, good can only break 1. But good can give a minor speed buff for X seconds. Evil can stun or slow for X/2 seconds. Evil's damage hurts for just a little more than good can heal, but the heal has a slightly lower cooldown or cost.

# Answer
> 2 votes
Aside from the tips in the other answers, you can add self-balancing mechanics to the game. This is not a substitute for balance, but can make the job of balancing easier.

Examples:

* Introduce prediction and bluffing. Useful if the player won't have time to react to everything, and must prepare in advance. "The opponent has multiple options, and he could do any of them, but this option is safer, and he keeps doing it. On the other hand, he's probably realised I have noticed his pattern, and may choose to do the other option to catch me off guard." See: Every good fighting game, strategy game, gambling game, ever.
* Minimise the chance of permanently locking down the opponent with an endlessly repeatable strategy, or repeatedly using what is found to be a "best strategy". I know you're not creating a fighting game, but as a great example, Guilty Gear XX and BlazBlue both have many of these mechanics, allowing their characters to be quite bizarre, but still somewhat balanced. The more hits you make in a single combo, the weaker they get. Gravity increases as you juggle the opponent. Block too much and you get weaker. Among others. All characters have access to all of these self-balancing mechanics.
* Have multiple winning conditions. This relates somewhat to the first point, but also allows you to react to poor situations by changing goals. It creates more complex resource-management decisions; go all out or save some in case things go badly? Fighting games usually have both knockout and time-out goals. It doesn't need to be built in; in StarCraft, for example, while the goal is only to wipe out your opponent, you will see top players concede and end the game early for any number of reasons.

David Sirlin has a great set of articles on balancing multiplayer games here, and an in-depth one on the self-balancing systems of Guilty Gear XX here.

# Answer
> 2 votes
Play testing is great, and not just for balance issues. It does run the risk of tuning the balance to your testers's skill level.

I am a big believer in using maths for balancing. If you can find a way to define what you want to balance as a number (often damage output) and add in a few reasonable assumptions about context (often player skill and environmental factors) then you can pull it into mathematical equations that can help you make decisions.

For some fabulous examples, check into theory-crafting done for WoW and probably other MMORPG's. (I haven't been a part of that in ages, but I believe elitist jerks is still going strong)

---
Tags: multiplayer, balance
---


# Question
Title: How would the game engine used impact monetization of games?
Does the game engine you use affect monetization of indie games? Of course, targeting difficult platforms is one of the issues.

Besides that, how would the game engine used impact monetization of games, assuming cases where the developers are going through a portal, and handling the online distribution, themselves? As an example, if I make a game in DarkBASIC, will it be harder to sell it than one made with Popcaps Framework or ClanLib etc.?

# Answer
> 7 votes
Certain engines are cross-platform, others are not. In theory, the more operating systems and devices that you can get your game on, the larger your potential audience. This is one of the great advantages of an engine like Unity3D where the theory is, you write code once and run it on PCs, Macs, browsers, iPads/iPhones and even consoles like the XBox and PS3. Engines which can do this though usually charge for each export option, and each export option has its own costs associated (like the $100 developer subscription to write iPhone apps).

You want an engine which can give you as much control as you require. If you write a game in DarkBASIC, can you implement the Steam API if you want to get it on that platform?

You mention that you will be selling through a portal, in that case, you certainly want to go for the most stable engine you can find. Casual gamers aren't the most computer savvy, you'll want your game to automatically load at the right resolution for their machine and you'll need to it 'just work'. Absolutely no error messages, otherwise the portals will get frustrated forwarding support queries to you.

So out of Popcap's Framework and DarkBASIC? Definitely go for Popcap's framework, which isn't DirectX based and is way more proven.

# Answer
> 3 votes
From a pure monetization standpoint - the answer is **THERE IS NO IMPACT**

What I mean by pure monetization is basically if you put aside the distribution challenges, the cost of making the game and things like publishing deals and funding. This means you are looking at Average Revenue Per User (ARPU) as the criteria for monetization.

**Explenation** \- It doesn't matter if you choose Unity, DarkBasic, Shiva or an open source framework like OpenGL or Cocos-2d - they all deal with the visualization of the game. All of these are exported into byte code that will work in a native environment and from that point on you can add any form of monetization. Most of them even include plugins for popular monetization options.

**What does Game Engine Impact**:

* **Game Distribution** \- Your distribution is affected by what hardware platforms you are running on and not all game engines support all hardware platforms which can limit your ability to get new users
* **Cost and ROI** \- Some game engines will cost significantly more than others. This means that you will need to make a lot more money to cover your costs and have a positive return on your investment (ROI)

# Answer
> 2 votes
The obvious answer seems to be, what are the contracts for said game engines? If they're open-source, what licence are they under? Do you accept the terms of that licence?

Some game engines cost millions of dollars to licence. So obviously thats going to effect the monetization of your game.

I don't see the engine making too much of a difference past that, though if the engine makes the game especially difficult to install or something then thats a problem.

I'd say its more a question of, can you do all that you want with that engine?

---
Tags: monetization
---


title: Color based collision detection

text:
# Question
Title: Color based collision detection
I am making a game where you fly a ship around some randomly generated planets. Since I am using a for loop to draw over 5000 planets, using the rectangle class or an oval-type class for this is not an option, since creating many objects will severely affect performance. Bitmasking each planet will likely result in performance issues too, so the only candidate is color based collision detection, because I don't need to apply some sort of object to everything I want to check for collisions. **Is any way to check the perimeter around the ship for a certain color?**

# Answer
> 3 votes
Color based checking is really slow. It is used rarely these days, and only for some specific problems like when using deformable terrain.

Probably a better approach is to minimize number of comparisons. I suggest you organize your planets in a quadtree first. Trees will quickly limit number of comparisons, because if you know that a planet fits in one quadrant, you immediately know it cannot intersect any planets in other 3 quadrants thus reducing your search space by 75% with a single comparison.

After this, you should do rough collision testing using rectangles because these are quick tests, much faster then circle or oval. Only if the hit is probable, then you do a thorough check, maybe even color or bitmask if you have to. But then the number of comparisons is really low because you have eliminated great many planets by this time.

This problem is basic scene management, and you will be well advised to use a 3rd party library rather then inventing your own.

---
Tags: java, collision-detection
---


# Question
Title: What is a library for event-driven mouse and keyboard input in Java?
The title basically says it all.

The only thing to take into consideration is it needs to be cross platform.

# Answer
While not technically a JAVA library SDL is a C library that I use extensively that does input and much more. It does however have bindings for java and can run on pretty much any platform in existence.

http://www.libsdl.org/languages.php

There is JSDL and SDLjava
> 3 votes

# Answer
Kind of depends.

Are you using JFrame without a game library or framework?

If so then you want to call the method `addKeyListener(ListenerObjectHere)` or `addMouseListener(ListenerObjectHere)` on the JFrame. Then the listeners you just created should Implement `KeyListener` or `MouseListener`.

If you're using a game framework it should have a polling system instead of events, which I'm not sure how to get around (Unless you could obtain the JFrame). If this is the case, just check each update (or tick) if a button is pressed.
> 1 votes

---
Tags: java, input, mouse, keyboard
---


title: Sprite batching in OpenGL

text:
# Question
Title: Sprite batching in OpenGL
I've got a JAVA based game with an OpenGL rendering front that is drawing a large amount of sprites every frame (during testing it peaked at 700). Now this game is completely unoptimized. There is no spatial partitioning (so a sprite is drawn even if it isn't on screen) and every sprite is drawn separately like this:

```
graphics.glPushMatrix();
{
    graphics.glTranslated(x, y, 0.0);
    graphics.glRotated(degrees, 0, 0, 1);

    graphics.glBegin(GL2.GL_QUADS);

    graphics.glTexCoord2f (1.0f, 0.0f);
    graphics.glVertex2d(half_size , half_size); // upper right

    // same for upper left, lower left, lower right
    graphics.glEnd();
}
graphics.glPopMatrix();

```

Currently the game is running at +-25FPS and is CPU bound. I would like to improve performance by adding spatial partitioning (which I know how to do) and sprite batching. Not drawing sprites that aren't on screen will help a lot, however since players can zoom out it won't help enough, hence the need for batching. However sprite batching in OpenGL is a bit of mystery to me. I usually work with XNA where a few classes to do this are built in. But in OpenGL I don't know what to do.

As for further optimization, the game I'm working on as a few interesting characteristics. A lot of sprites have the same texture and all the sprites are square. Maybe these characteristics will help determine an efficient batching technique?

# Answer
If you don't wish to make the jump to vertex arrays and a VBO just yet, there are some simple changes you can make to get more efficiency from even immediate mode.

Yes, immediate mode is still the slowest option, but it's not **THAT** slow - Quake used immediate mode back in 1996 and despite that it will get you well over 25 fps on modern hardware. So bear that in mind when considering the rest of what I have to say. Moving to vertex arrays or VBOs will (eventually) get you more speed, but unless you tackle the root cause of your performance degradation (which is actually the fact that you're doing a separate transform per-sprite) it's not going to be much more speed (it may even be slower).

So let's look at your sprite transformation. This is actually quite a simple transformation matrix that is built on the CPU (even in OpenGL with hardware T&L - it's only the final transform of position by MVP matrix that runs on the GPU) so we can take advantage of that knowledge and make immediate mode go faster.

Before I go into much more detail about how to deal with that, the first thing you need to know is that you have a classic case of an immediate mode anti-pattern at work here. It manifests as this (C/C++ code but it should be obvious what the Java equivalent is):

```
for (int i = 0; i < NUM_SPRITES; i++)
{
    glBegin (GL_QUADS);
    // glVertex/etc calls here
    glEnd ();
}

```

The simple solution to this is:

```
glBegin (GL_QUADS);

for (int i = 0; i < NUM_SPRITES; i++)
{
    // glVertex/etc calls here
}

glEnd ();

```

If you don't believe me then build it, run it, benchmark it. Ramp up the value of NUM\_SPRITES to see how each approach performs as the count increases. Each glBegin/glEnd pair counts as a "batch" in immediate mode, and by putting them *outside* the loop you get better throughput.

So how can we use this to acelerate your case? Quite easy. Instead of using the matrix stack to do transforms, let's build the matrix and apply it to each sprite in software ourselves. This seems a mite counter-intuitive, but stick with me - it's still going to be faster than breaking batches by having to do a separate transform per-sprite.

Our loop now looks like this:

```
glBegin (GL_QUADS);

for (int i = 0; i < NUM_SPRITES; i++)
{
    // evaluate transformation matrix for this sprite
    // apply transformation matrix to sprite positions
    // glVertex/etc calls here
}

glEnd ();

```

So how do we do those two new steps? Just by using the OpenGL documentation to build the matrix; e.g. the matrix for glRotate is given here: http://www.opengl.org/sdk/docs/man/xhtml/glRotate.xml and for glTranslate here: http://www.opengl.org/sdk/docs/man/xhtml/glTranslate.xml. Another, better option is to grab a matrix library; I'm not familiar with Java so I can't speak as to availability of such but a quick Google search should turn up results.

It's also worth noting that you have a potential shortcut here too - if for a given sprite the rotation angle is 0, then instead of doing a full matrix transform you can just do:

```
 glVertex2f (x + half_size, y + half_size); // and etc...

```

Once you have that part resolved, THEN is the time to consider porting to vertex arrays or VBOs, not before. Because, like I said, your *real* bottleneck here is not use of immediate mode, it's doing a separate transform per sprite. Porting the code before addressing that will *still* leave you in a position where you have to break batches at every sprite, and any performance gains will be quite marginal (a bad VBO implementation may even run much *slower*).

IMO people are often too trigger-happy about recommending VBOs as a solution as soon as they see any immediate mode code, and can sometimes fail to analyze the code properly and identify that the *real* bottleneck may be elsewhere. Of course a VBO will be the optimal solution longer-term, but address that real bottleneck first.
> 8 votes

# Answer
If your interest is in making games and not game engines, I suggest you use a game engine. Game engines are libraries which solve some of the most frequently encountered problems, like the one you are having. There are many, but if I may suggest:

Slick2D at http://slick.cokeandcode.com/. It is a very simple engine, but it lets you get started quickly and easily.

If you wish little more try http://libgdx.badlogicgames.com/. It is in active development, and an astounding number of games has already been published using it. In addition, you can port your game to Android with almost no additional work.

As for the answer behind your actual question... If you can believe it, such a simple question has a complicated answer. You would think that drawing a rectangle is easy, but in order to optimize it you need to know several advanced techniques. The shortest answer is that you need to minimize number of times the CPU is interrupting the GPU, and in addition you should maximize the number of 'things' GPU has to do with a single interruption from the CPU. In your case, every glBegin/End is a trip from the CPU to the GPU. Every time you change a texture it is a trip from the CPU to the GPU. Etc. So the idea is to pack as many sprites into a single texture, then create a buffer with coordinates for as many sprites (ten thousand is a good number), and then render them with single call. One set of functions you should look at are glVertexPointer/glDrawElements. When you start reading about them, you will see there are more ways to do this.

However, once more, I suggest you go with the 3rd party engine, as they usually have nicely wrapped this for you so you can just draw your rectangles.
> 5 votes

---
Tags: opengl, java, sprites, spritebatch
---


title: Logic behind a checkers game?

text:
# Question
Title: Logic behind a checkers game?
I'm starting to make a checkers game and I've got all my graphics + the board drawn. Before I moved on to creating the pieces I was wondering what an easy way to tackle the logic side of the movement of pieces.. Should I make a table of every square, detecting if it has a piece and if so, what color? (i.e 0=empty, 1=red, 2=black) or do you guys have a better idea to this issue? Thanks in advance.

# Answer
I'd just have a two dimensional array of Space objects. Don't know how you're rendering each space, but the Space object could say if it's occupied by a piece, and if so, what is the color, etc.
> 1 votes

# Answer
I once wrote a reversi game and I just used a table of values for each square and it worked fine assigning a number to each possible state. When you move a piece you would have a function that would check if a move is legal then erase where the piece from one square and put it in the next one. I'm sorry if I missed something applicable but I don't actually know how to play checkers.
> 0 votes

---
Tags: java, logic
---


title: Game Maker Studio Gravity Problems

text:
# Question
Title: Game Maker Studio Gravity Problems
I've started messing around with Game Maker Studio. The problem I'm having is trying to get a gravity code for orbiting.

Here's how i did it in XNA

```
        foreach (GravItem Item in StarSystem.ActiveItems.OfType<GravItem>())
        {
            if (this != Item)
            {
                Velocity += (10 * Vector2.Normalize(Item.Position - this.Position *
                    (this.Mass * Item.Mass) / (Vector2.DistanceSquared(this.Position,
                    Item.Position)) / (this.Mass));
            }
        }

```

Simple and works well, things or bit and everything is nice.

but in Game maker i don't have the luxury of Vector2's or a For-each loop to loop threw all the objects that have a mass. I've tried a few different things but nothing seems to work

```
distance = distance_to_object(obj_moon);

//--Gravity
hspeed += (0.5 * (distance) * (Mass * obj_moon.Mass) / (sqr(distance)) / Mass)
vspeed += (0.5 * (distance) * (Mass * obj_moon.Mass) / (sqr(distance)) / Mass)

```

thanks for the help

# Answer
> 1 votes
I think that motion\_add might use vector addition, which should produce an orbit effect. (you can use point\_direction and the moon's coordinates as per the direction, force is your choice). That is assuming you are using vector addition for gravity. If you aren't, I am not entirely sure what you are attempting to achieve.

As per the foreach loop, Game Maker kind of does the loops for you. As such, you can implement it like... say, have objects for an asteroid and your other specific objects, and make an object that is the parent of all of them. Then use something like:

```
with (obj_parent)
{
    //your code here...
}

```

This should go through all obj\_parent's (and thus,their descendants) and perform the code.

On a final note, hspeed and vspeed are... well, not my favorite. Note you can also use the per-object variables speed and direction, which work as you would expect. Might be more friendly than those depending on what your doing.

---
Tags: c#, game-maker
---


title: WebGL: Texture appears as black

text:
# Question
Title: WebGL: Texture appears as black
I have a simple WebGL canvas, where I'm attempting to render a texture on a square. When working with textures as local files, all is fine. But when I try to load a texture from the web, I get a black canvas.

Please see this fiddle for a demo. I have made the shaders and JavaScript very simple.

# Answer
> 3 votes
You need to set the texture parameters for non-power of 2 textures. Adding these 2 lines fixed the issue

```
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

```

---
Tags: javascript, webgl
---


# Question
Title: Uniform not being applied to proper mesh
Ok, I got some code, and you select blocks on a grid.

The selection works. I can modify the blocks to be raised when selected and the correct one shows.

I set a color which I use in the shader. However, I am trying to change the color before rendering the geometry, and the last rendered geometry (in the sequence) is rendered light.

However, to debug logic I decided to move the block up and make it white, in which case one block moves up and another block becomes white.

I checked all my logic and it knows the correct one is selected and it is showing in, in the correct place and rendering it correctly. When there is only 1 it works properly.

Video Of the bug in action, note how the highlighted and elevated blocks are not the same block, however the code for color and

My Renderer is here (For the items being drawn)

```
    public void render(Renderer renderer) {
    mGrid.render(renderer, mGameState);

    for (Entity e:mGameEntities) {
        UnitTypes ut = UnitTypes.valueOf((String)e.getObject(D.UNIT_TYPE.ordinal()));
        if (ut == UnitTypes.Soldier) {

            renderer.testShader.begin();
            renderer.testShader.setUniformMatrix("u_mvpMatrix",mEntityMatrix);
            renderer.texture_soldier.bind(0);
            Vector2 pos = (Vector2) e.getObject(D.COORDS.ordinal());
            mEntityMatrix.set(renderer.mCamera.combined);
            if (mSelectedEntities.contains(e)) {
                mEntityMatrix.translate(pos.x, 1f, pos.y);
                renderer.testShader.setUniformf("v_color", 0.5f,0.5f,0.5f,1f);
            } else {
                mEntityMatrix.translate(pos.x, 0f, pos.y);
                renderer.testShader.setUniformf("v_color", 1f,1f,1f,1f);
            }
            mEntityMatrix.scale(0.2f, 0.2f, 0.2f);
            renderer.model_soldier.render(renderer.testShader,GL20.GL_TRIANGLES);
            renderer.testShader.end();
        } else if (ut == UnitTypes.Enemy_Infiltrator) {
            renderer.testShader.begin();
            renderer.testShader.setUniformMatrix("u_mvpMatrix",mEntityMatrix);
            renderer.testShader.setUniformf("v_color", 1.0f,1,1,1.0f);
            renderer.texture_enemy_infiltrator.bind(0);
            Vector2 pos = (Vector2) e.getObject(D.COORDS.ordinal());
            mEntityMatrix.set(renderer.mCamera.combined);
            mEntityMatrix.translate(pos.x, 0f, pos.y);
            mEntityMatrix.scale(0.2f, 0.2f, 0.2f);
            renderer.model_enemy_infiltrator.render(renderer.testShader,GL20.GL_TRIANGLES);
            renderer.testShader.end();
        }
    }
}

        String vertexShader = "uniform mat4 u_mvpMatrix;                   \n"
            + "attribute vec4 a_position;                  \n"
            + "attribute vec2 a_uv;                  \n"
            + "varying vec2 v_uv;                  \n"
            + "void main()                                 \n" + "{                                           \n"
            + " v_uv = vec2(a_uv.x,1.0-a_uv.y);\n"
            + "   gl_Position = u_mvpMatrix * a_position;  \n" + "}                            \n";
        String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n"
            + " uniform vec4 v_color;"
            + " uniform sampler2D tex;"
            + " varying vec2 v_uv;     \n"
            + "void main()                                  \n"
            + "{                                            \n"
            + "  gl_FragColor = v_color*texture2D(tex, v_uv);\n"
            + "}";
      testShader = new ShaderProgram(vertexShader, fragmentShader);

```

# Answer
I simplified my renderer, and then looked at it.

The solution was the following. I tested with both options to ensure that I effectively fixed it.

The problem was

```
      renderer.testShader.setUniformMatrix("u_mvpMatrix",mEntityMatrix);

```

I set it before I set mEntityMatrix and made the incorrect assumption that it passed a reference and didn't make a copy. I assume this made it use the last "mEntityMatrix" from the last loop, hence transforming using "the last elements" position.

Once I moved the line to right before my drawElements everything started working.
> 2 votes

---
Tags: opengl, java, glsl, libgdx
---


# Question
Title: Are there specific benefits to using XNA for 2D development if you don't plan on releasing on xbox/windows phone?
I've been using XNA for a while to tinker with 2D game development, but I can't help but feel constrained by the content pipeline when targeting PC only. Things like no vector fonts or direct use of graphics files make it a pain while other frameworks do these things with no problem. I like XNA because it's robust and has a lot of support, but what are the specific benefits that I'd get developing exclusively for PC, if there are any at all?

# Answer
> 3 votes
Everything you are complaining about has been solved by the XNA community or is actually supported by the library.

Vector Fonts thanks to the Nuclex Framework

Also loading Texture2Ds from a stream is built into the library. If you want to use premultiplied alpha (the default XNA blend mode) with stream loaded textures use the below function.

```
static public void PreMultiplyAlpha(this Texture2D texture) {

    //Setup a render target to hold our final texture which will have premulitplied color values
    var result = new RenderTarget2D(texture.GraphicsDevice, texture.Width, texture.Height);

    texture.GraphicsDevice.SetRenderTarget(result);
    texture.GraphicsDevice.Clear(Color.Black);

    // Using default blending function
    // (source × Blend.SourceAlpha) + (destination × Blend.InvSourceAlpha)
    // Destination is zero so the reduces to
    // (source × Blend.SourceAlpha)
    // So this multiplies our color values by the alpha value and draws it to the RenderTarget
    var blendColor = new BlendState {
        ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
        AlphaDestinationBlend = Blend.Zero,
        ColorDestinationBlend = Blend.Zero,
        AlphaSourceBlend = Blend.SourceAlpha,
        ColorSourceBlend = Blend.SourceAlpha
    };

    var spriteBatch = new SpriteBatch(texture.GraphicsDevice);
    spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
    spriteBatch.Draw(texture, texture.Bounds, Color.White);
    spriteBatch.End();

    // Simply copy over the alpha channel
    var blendAlpha = new BlendState {
        ColorWriteChannels = ColorWriteChannels.Alpha,
        AlphaDestinationBlend = Blend.Zero,
        ColorDestinationBlend = Blend.Zero,
        AlphaSourceBlend = Blend.One,
        ColorSourceBlend = Blend.One
    };

    spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
    spriteBatch.Draw(texture, texture.Bounds, Color.White);
    spriteBatch.End();

    texture.GraphicsDevice.SetRenderTarget(null);

    var t = new Color[result.Width * result.Height];
    result.GetData(t);
    texture.SetData(t);
}

```

> Are there specific benefits to using XNA for 2D development if you don't plan on releasing on xbox/windows phone?

Anyways your main question makes no sense. Why are "specific benefits" for PC developers a desired trait? The library makes 2D graphics very easy on all supported platforms. So no, there are no benefits to being a PC exclusive developer.

---
Tags: xna
---


title: Why are trees shining in background?

text:
# Question
Title: Why are trees shining in background?
Currently I am creating a forest scene in the dark, and the trees are shining far away, but when I get close they are fine. I have the shaders set to "Nature/Tree Soft Occlusion \[bark/leaves\]", but they are still rendering strange far away, but close they are fine.

I tried placing the trees in a folder named "Ambient-Occlusion" like said here, but no luck. Also fog is turned off. Thanks in advance.

**UPDATE**

When I looked at the trees using the "Render Paths" camera, they appeared red while everything else was green.

**UPDATE 2**

I have tried re-installing the package I downloaded these from, but still no luck.

**UPDATE 3**

I have added some trees manually, and they work fine, but when adding them by painting on the terrain I get the problem.

**FINAL UPDATE**

I tried building the game to see if this had the effect on the .exe, and it didn't. So I just have to ignore when I am debugging it, as it works fine on the build. Thanks for all the help, it just seems like an error with unity. Picture of build:

# Answer
Turns out that it was rendered fine in the builds of the project, just not in the debugger in unity. I am planning on reporting this as an error on unity's site, as it was messed up in the debugger only, not the game.
> 6 votes

# Answer
I fixed the problem by adding fog with the properties:

* Color: R: 0 G: 0 B: 0 A: 255
* Mode: Exp2
* Density 0.03

I know this doesn't solve the problem, but I wanted to use fog in my game anyway and this was an easy solution. I am not going to accept this as the answer since it doesn't actually solve the question, I just wanted to say what ended up working. Picture:

It also adds that scary/mysterious feel to it, which I am happy about. I would still love to have an actual answer to how to fix this.
> 2 votes

---
Tags: unity, shaders, terrain, tree
---


title: Game Asset Management

text:
# Question
Title: Game Asset Management
I am making my first small mobile game in C# XNA. Lets say I have 3 screens, the main menu, options and game screen. A single game session usually lasts for 1 min, so the user will alternate frequently between the main menu and game screen. Therefore, once I load the textures for either screen, I want to keep them in memory to avoid frequent reloading. Both screens share some assets like their background textures, but differ in others. The first solution I came up with is making 2 texture factory classes, MainScreenAssetFactory and GameScreenAssetFactory, each with their own content manager, and ill store them in a globally accessible point so that they persist after either screen is destroyed. There is also a OptionsScreenAssetFactory, but that I dont want to cache it since the options screen is rarely visited.

A typical Factory would look something like this

```
public class MainScreenAssetFactory
{
    private readonly ContentManager contentManager;

    public MainScreenAssetFactory(IServiceProvider serviceProvider, string rootDirectory)
    {
        contentManager = new ContentManager(serviceProvider) { RootDirectory = rootDirectory };
    }

    public Texture2D ListElementBackground
    {
        get { return contentManager.Load<Texture2D>("UserTab"); }
    }

    public Texture2D ListElementBulletPoint
    {
        get { return contentManager.Load<Texture2D>("TabIcon"); }
    }

    public Texture2D LoggedOutUser
    {
        get { return contentManager.Load<Texture2D>("LoggedOutUser"); }
    }
}

```

Since both Main, Options and Game Screen share some common resources, instead of loading them more than once, I created another class CommonAssetTexFactory which holds the common stuff and stays in-memory during the app lifetime. For example, this class gets passed to the options screen when it is created.

However, given my small game with its few assets, I am already finding this solution cumbersome and inflexible. Changing anything would require looking to see if its already in the common factory, and if not, modifying existing factories and so on. And this is just considering textures currently, i didnt add sound files yet. I cant imagine bigger games with thousands of resources using this approach. A better idea must exist. Would someone please enlighten me?

# Answer
> 1 votes
It sounds like your problem could be rephrased as "How do I rename assets quickly? I really like VS's refactoring support." - But how often do you rename an asset? *Seriously?*

I think that most games that get into the thousands of assets are highly data driven. (It's worth pointing out that - if your game *isn't* going to have that many assets, then you shouldn't take the same approach!)

Once you're data-driven, it should be simple enough to validate your screens/levels/maps/whatever, check the assets used, and spit out errors for missing textures, etc.

And, if you needed it, you could then add proper global rename support to your tooling.

Any assets that you load directly in your engine, and are missing, would emit a runtime error. But proper testing should shake those errors out very quickly. And they're so trivial to fix that it's not worth the additional engineering effort.

---

For your purposes, just load the assets by name whenever you need them. As you hopefully already know, `ContentManager` works as an asset cache. If an asset changes name, it's easy enough to fix by hand. "Find in files" is probably all you need.

Additionally, it's worth pointing out that, in the XNA Content Pipeline, you can change the name of a resource independently of its filename. (Select the file, press F4, it's the `Asset Name` property).

You shouldn't run out of resources for a game this small. But, if you need to, you can always just publically expose multiple `ContentManager` and load from the "right" one, allowing you to `Unload()` unused sets of content individually.

---

If you're still keen on implementing something along the lines of the "Factory" class you've shown us (strong typing, auto-complete, etc), then you should look into how "Resources" work in Visual Studio. That is: the `.resx` type resource you can create (Project, Add New Item, Resource File).

Note how they produce a tool-generated C# source file, containing a class with a static property for each resource.

You could do something like that yourself, if you wanted.

# Answer
> 4 votes
I think you need to rethink what problem you're trying to solve and if that problem really exists.

As far as I can tell your game is small enough to keep all assets in memory on any modern computer, have you measured your peak memory usage? (A quick and dirty way to do this is by checking the value of 'peak working set' in the task manager (be sure to select that column from the view options)). Is it only a few hundred MB? That's great! Just use one content manager, it already caches everything it loads so you don't have to worry about things being loaded twice.

If you really have a problem with keeping everything in memory you could create a content manager with it's own caching strategy, say that it evicts items if they haven't been used for sometime, however such a strategy can cause some unexpected lag if resources get evicted right before they are needed again. A better way would give you total control over when an item is present or not. A way to do this is to use resource scopes. Just as in code a variable is only valid in it's own scope ("{..."}) or a lower scope try the same approach with your game. Say the highest scope you have the menu assets, on a lower scope you have the player assets, on an even lower scope you have the current level assets, etc... Make it easy to 'pop' a scope, meaning that everything in that scope and lower scopes is evicted from memory. It is a bit similar to your current approach but more dynamic and if done right it could be easier to handle.

Consider the following logic:

```
Initialize Resource Manager m
m.pushScope();
Let the menu system load everything it wants
m.pushScope();
Load all the character and weapon data, in game GUI glyphs etc...
m.pushScope();
Load all level specific data.

//... player goes to level 2
m.popScope();
m.pushScope();
Load all level 2 specific data.
//...player dies and returns to menu
m.popScope();
m.popScope();
//.. Memory now only contains menu data.

//etc...

```

If an entity wants to know if an item is present in the cache automatically check the lowest scope first and then search bubbling up, your resource manager should handle this, the entity should never have to concern itself with this.

---
Tags: xna, c#, mobile, resource-management
---


# Question
Title: How to adjust position relative to resolutions?
I have a lot of objects on the screen and would like at different resolutions, object's positions rendered correctly on the screen irrespective of the resolution. Is it correct to multiply the position by aspect ratio ?

# Answer
> 3 votes
Instead of noting your objects position with a 2d vector(absolute, in pixels) you should use a mix of two 2d vectors (relative, in percentage component and offset component)

The percentage component are two float variables with a value in the range 0.0 ~ 1.0. It specifies how much away from screen origin you are.

This explains it:

This way, you can do it: `{(0.5f,0.5f), (0,0)}` to put an object on the center of the screen, `{(0.0f,1f), (0,-5)}` to put an object on the 5 pixels above the bottom of the screen. Etc.

To achieve this, you should use something like this to calculate the absolute coordinates given the relative:

```
Vector2 getAbsolute(RelativeVector rel)
{
    float x = (rel.percentage.X * ScreenWidth) + rel.Offset.X;
    float y = (rel.percentage.Y * ScreenHeight) + rel.Offset.Y;
    return new Vector2(x, y).
}

```

Should work fine. Lots of GUI systems use this approach.

EDIT:

As @milkplus stated, anchoring is a good way to do it too, and if I'm not mistaken it's also how Windows do it on it's UI designers.

Just in case, you can simulate it with Relative positioning too. You just have to specify the edge you want to use (`0.0, 0.0`, `1.0, 0.0`, etc), and use the offset component. If you use a this relative position: `{(1.0, 0.5), (-50, 0)}` the object will always be 50 pixels away from right edge.

# Answer
> 1 votes
Instead of scaling like @Gustavo suggests, you could also just anchor your screen objects to the edges. That's how UI designers often work. A negative screen coodinate is taken to be anchored to the right or bottom.

```
if (x<0)
   x += ScreenWidth;
if (y<0)
   y += ScreenHeight;

```

For development, you could scale width and height for resolution. I would recommend uniform scaling instead of using the aspect ratio. Take the minimum of (designWidth/screenWidth) and (designHeight/screenHeight) to scale your UI elements. I normally pick ipad2 resolution (1024,768) as my design resolution.

For production, I would recommend having different sets of bitmaps rather than scaling.

# Answer
> 0 votes
If you originally setup your GUI while considering a system with resolution `Width X Height`, you can position items in other resolutions in `x * newWidth / Width, y * newHeight / Height` (make sure to cast these integers' values to floats). Items' widths and heights can be treated the same way. Essentially, like you said:

1. Calculating the ratio between the original resolution and the current one.
2. Multiply the position or size of the item by change in ratio % from the original display resolution.

---
Tags: opengl, mathematics
---


# Question
Title: What are the advantages and disadvantages to using a game engine?
How do I know whether or not to use a game engine? I want to make a relatively complex 2D game for Android. What factors should I weigh to decide whether to find, install and learn a game engine or just do everything manually?

# Answer
**Advantages:**

* Most if not all of the coding is done for you, so all you have to worry about is content, level layout, etc.
* Along those lines, memory management, asset loading, lighting (in complex engines), etc has all been designed and tested thoroughly (hopefully).
* As mentioned below, if the engine is cross platform you will have to do little to no work to port your game.

**Disadvantages:**

* If you are modifying anything, you now need to become familiar with a new codebase.
* If there is a bug in the engine, unless it is open source you can't fix it.
* The engine was not designed specifically for your game, so it may be less efficient than code you write specifically for your game.
* Game engines generally are not free.
* If a game is small, the overhead of using an engine may not be worth the time invested to write code yourself.
* If your game engine also has any editors or tools, you will have to build and test those as well before turning them over to artists or relying on them yourself.

Don't let the fact that the list of disadvantages is longer: when the time spent coding and testing all the systems you need is too long for your production cycle, or if you have more skill with art than code, using a game engine is definitely a good idea.

A comparison of game engines is in the works in this question: Pro's and Con's of Various 3D Game Engines
> 24 votes

# Answer
In my case, I spent a lot of time (months) floundering around getting nothing done because of game engines. I now typically avoid them like the plague, though I understand they should be used wisely and in moderation.

For me, I'd get obsessed over all the **possibilities**! Looking at a long list of features in engine X, it's like "Wow I could do all this! My game could be great!" So I'd download it, run the demos and be dazzled by those features in action, etc. Then I'd create a new project in my IDE and wouldn't know where to start. I'd write some code, I might learn from and base it off of the demo projects, but those were just demos.

I didn't know how to start from nothing and make something. I didn't know the first step. I loved the idea of an engine, it impressed me and got me motivated to make something, but my knowledge of actual development was so limited that even after knowing how to add the engine to the build path, and maybe writing a few lines to start the engine and then shut it down again, beyond that I never made anything worthwhile.

I'm much more of a baby step kind of person. I'd rather make my own game one step at a time, refactoring out useful functions and collecting those functions into a library which one day I might consider an "engine". So for now, I avoid the engine hype and just stick with the low-level stuff.

And engines do have their place. If you find an engine and think to yourself, "This is exactly what I would write! They've already done the work for me, I don't have to reinvent the wheel, and I know exactly how to hook it into the game that I've already started \[or at least fully planned and am ready to start\]" then it's probably a good fit. You'll know exactly how to use it, and how to write your own code to use the engine to create something useful. But if you get an engine just cause it has everything but the kitchen sink and you think you're standing on the shoulders of giants, you're very mistaken. **You have a giant standing in front of you, and you need to climb up to its shoulders.**

So the huge disadvantage for me: don't get caught up in all the things you could do. Whatever engine you might choose, it will have tons of potential. But if you don't know how to actually harness the potential, if it doesn't make your live easier or help you get your work done, **then why are you using it?**
> 16 votes

# Answer
The biggest disadvantage of a game engine is that you have to learn it. If you're new to programming in general, that may still be faster than learning to write code to do all the stuff that an engine handles for you out of the box, but if you're experienced then it costs you no time to sit down and start coding, but a fair amount of up-front time to learn your way around an unfamiliar engine.

Biggest thing to look for is support, because game engines are not perfect and they do not read your mind, and you WILL get stuck on SOMETHING at some point. So:

* Is there documentation?
* Is the documentation actually any good?
* Is there technical support (generally not, unless you're paying for it)? What's the turnaround time?
* Are there community forums where you can post questions and get real answers?
* Are there tutorials that show you how to start using the engine? Is sample source code included? How useful do you find these in getting up to speed?
> 4 votes

# Answer
As somebody who has a lot of software development experience and who only really tried to develop a game from scratch recently, here is my 2 cents.

The answers so far have provided long lists of pros and cons. I will provide what for me is the most important reason NOT to use a game engine. As I took on the task of learning to write a game purely for challenge and reward I decided to do it from scratch with no engine, just OpenGL and SDL, because I wanted to *learn* everything above that level of abstraction. At no stage have I regretted that decision. My game is a nice scrolling version of 2D Asteroids, basic but smooth. I am not trying to compete with vastly superior games, but I do distribute my game and people have enjoyed playing it. I will take the same approach in making the game multi player. This is a huge challenge and using libraries might make it easier, but I my goal is not to make it easy. My goal is to learn, and for me it is a part time activity, so I do not have a lot of time and progress is slow. But I have my reasons for this approach. Call it "higher learning".

So, answer your own question, do you want to learn how to do the things that the game engine instead does for you for the benefits that this learning might bring? If so, do not use a game engine.
> 3 votes

# Answer
You need to detail what you mean by "complex". A good game engine takes care of all the following:

* Rendering on a stable framerate
* Input handling
* User interface
* Sounds/music
* Resource management (images, sound, data files)
* Saving/loading your game
* Physics (2d or 3d)

Think to yourself, do I know how to code each of these? How long will I take to program each, and how long will I take to learn how to make an engine do each of these?
> 2 votes

# Answer
The biggest advantage: a lot of things are done for you. You don't have to keep re-inventing the wheel.

Another advantage: The game engine might also be cross-platform (Unity).

Disadvantages? Control? The engine is taking care of some things for you (such as rendering) so if it has bugs or performance issues, then you can't simply fix it yourself.
> 1 votes

---
Tags: game-design
---