title: When and Why to use Console Logging

text:
# Question
Title: When and Why to use Console Logging
Why and in which way should I incorporate console logging into my small sized games? I use Java and C++.

With console logging I mean things like this:

# Answer
Your question seems a little vague to me (mainly the how part, do you mean the concept or the coding?) but I'll try my best to answer it for you:

## **Why**

I know I use console logging in all my projects. For me, I mainly see it as a way for the end-user to report problems. An example could be, the game crashes for an unknown reason. So they come to help and support and say "My game crashes, here is the log:". The last line in the log is `[APP] Loading: Resources`. Well, now you have a great place to start helping the user.

I've found it also helpful to me when I'm developing. Sometimes I report important but non-crashing errors into the console. For example, if my game is loading extra entities that have no model data. Nothing will tell me this while running unless I get a `[WARN]: Attempted to create empty model for entity #ENTITY-NAME#`. This could be a performance problem if I'm trying to create and render a bunch of empty entities. With the console log, I can fix it easily.

Mainly console logging is just to do what the debugger can't. If your worried about performance, you can always just put the logging code into a macro (if in C++), and remove it in release builds. If you do keep it in for release builds, though, be careful as to what you put in it. In my projects, I don't put shader error dumps in release builds so users can't see what is in the shader code.

## **How**

What I'll do is give you the concept part. I'll explain how I usually do it, and you can adopt this method into your projects. Keep in mind I use C++, not Java. However, porting shouldn't be that hard. Because the adding of consoles into the project is language and class specific, I'll leave that up to you. I found it the first time by a quick Google.

What I do is create a class to handle the console. I always output the console logging to a file so the user (or me!) can review it after a game crash or unexpected closure. The handle to the file is managed within that class. It is a good idea to have this class available to all other classes. That way, you can always report a problem or status update. The way you do this depends on the structure of your application (you can make it global, or put it into another global class, or pass it to every object. It's up to you).

My console class always has these 5 functions:

* `Log(string)`: Writes a line to the output file (usually private and only used by the other 4 functions).
* `Print(string)` or `Info(string)`: Writes a regular status update or message.
* `Warn(string)`: Writes an important but not fatal or erroneous message to the console. This message is prefixed by `[WARN]` or `[WARNING]`.
* `Error(string)`: Writes an error to the console. This message is prefixed by `[ERROR]`.
* `Fatal(string)`: Writes a fatal error to the console. This message is prefixed by `[FATAL]`. Also shows a message box with the error and stops the program.

I mentioned performance in the Why portion. Indeed, performance can come into play in release builds. There are so many ways to handle this. You could add an extra argument to the logging functions along the lines of `bool release` with a default of `true`. If it is false, the message will be ignored in release builds.

I hope that what I've written can help you decide if you need console logging and how to do it. Good luck!
> 7 votes

# Answer
*Console logging* is used mainly to debug an application. It is always good to print out essential information, just in case something goes wrong you can have a first look to how things went. Information like library version, etc is always handy to have, especially if you are planning to run your application in different platforms.

What I usually do is set up different levels of debugging, each of them printing out different information. In your *release* level you can then set up a debugging level of 0, which would only print out essential information, as mentioned earlier. You can then prepare your code to print out a more detailed log when the debugging level is set to a higher number, which at the same time might affect your performance if you are also saving some debugging textures, etc....
> 4 votes

# Answer
In my games, I use the following macro's:

```
#define LOG_INFO(_msg, ...) { Log::Get().Message(Log::MessageType::eInfo, __FILE__, __LINE__, __FUNCTION__, _msg, __VA_ARGS__); }
#define LOG_WARNING(_msg, ...) { Log::Get().Message(Log::MessageType::eWarning, __FILE__, __LINE__, __FUNCTION__, _msg, __VA_ARGS__); }
#define LOG_ERROR(_msg, ...) { Log::Get().Message(Log::MessageType::eError, __FILE__, __LINE__, __FUNCTION__, _msg, __VA_ARGS__); }
#define LOG_FATAL(_msg, ...) { Log::Get().Message(Log::MessageType::eFatal, __FILE__, __LINE__, __FUNCTION__, _msg, __VA_ARGS__); }

```

This allows you to write this:

```
LOG_ERROR("Player is called '%s', which is a stupid name.", m_Name);

```

Which gives output like this:

```
[player.cpp:259] ERROR: Player is called 'SauerkrautUberAlles', which is a stupid name.

```

In any logging system, you will have to balance the following factors:

* Output - Do you want to output to screen? Console? File? Over network?
* Flexibility - Can you turn off logging for certain source files? Do you need that feature?
* Debugging - What info do you need to debug an error?
* Safety - Can a badly-formatted log message crash the game or worse, alter its state?

In my experience, a logging system needs to be *fast* above all else, including safety. In a game I worked, the log was only important when the game crashed. But when the game crashed, the log hadn't been written to the file yet! So to fix that, we opened the log file for every line, appended a line and closed it. This made sure that always got the very latest log message in the file *before* the crash.
> 3 votes

---
Tags: debugging, console
---


# Question
Title: What would make a good cursor movement sound effect?
I know specific questions like this are very borderline on acceptable - but I am having massive trouble finding a non-annoying sound effect for moving the cursor in my game.

The game is a Fire Emblem like SRPG and think it would be cool if I could have a little sound each time the cursor ticks in a menu/selection of character/etc. - it should be a non-intrusive sound (keeping in mind I can adjust volume).

What have you guys used for something like this? Going to various free soundclip sites putting in "cursor move" isn't doing much for me.

# Answer
I used a web based version of sfxr to create some generic sounds (menu cursor move ,select, abort etc.). SFXR is a tool that creates simple 8bit like sound effects. You have multiple templates (shoot, coin ,item pickup etc) that create sounds based on some randomized values. You can change all the values, mutate a sound or randomize all parameters to get special results.

AS3SFXR

Just try it out, its flash/adobe air based, so you can use it in the browser.
> 2 votes

# Answer
Moving the cursor should not create a sound. What you probably mean are sound effects that are being played whenever the cursor hovers over an important area (clickable elements within the game).

You're right, the sound effect should be really subtle. I think you'll get the best results if you search for *button rollover* or *blip* sound-effects. Here's an example of what I would consider a suitable sound (it could be toned down even more).
> 2 votes

---
Tags: sound, sound-effects
---


# Question
Title: Sprite not visible when using a Rectangle for collision in XNA
When I added a Rectangle to the Draw method for the sprite, it did not show up on screen.

```
 spriteBatch.Draw(texture, position, new Rectangle((int)position.X, (int)position.Y, (int)texture.Width, (int)texture.Height), Color.White, rotation, orgin, scale, SpriteEffects.None, 0f);

```

# Answer
The third parameter specifies which parts of the sprite you wish to draw.

From MSDN:

sourceRectangleType: Rectangle?

A rectangle that specifies (in texels) the source texels from a texture. Use null to draw the entire texture.

You should change your code to something like this:

```
  spriteBatch.Draw(texture, position, new Rectangle(0, 0, (int)texture.Width, (int)texture.Height), Color.White, rotation, orgin, scale, SpriteEffects.None, 0f);

```

This parameter is useful if you're using spritesheets (image files with multiple sprites in them).
> 2 votes

---
Tags: xna
---


# Question
Title: Need help to find error in collision dection in XNA
I really need some help to find the reason why not any of my Asteroids sprites are visible on the screen after I added som code to dedect collision. My suspect is that it has to do in the collision method and that the sprites are removed from the list from the beginning!? The Spaceship is visible.

In my manager class I have this method for checking the collision:

```
public void CollisionControl(Spaceship spaceShip)
    {
        for (int i = 0; i < asteroidList.Count(); i++)
        {
            if (asteroidList.ElementAt(i).Bounds().Intersects(spaceShip.Bounds()))
            {
                asteroidList.RemoveAt(i);
                i--;
            }
        }
    }

```

And then from the Game1 class I call this manager from the Update Method like this:

```
 asteroidManager.CollisionControl(spaceship);

```

And finally in the SpaceShip class and the Asteroids Class I have this code:

```
// Bounds
    public Rectangle Bounds()
    {
        //return new Rectangle((int)(position.X - orgin.X), (int)(position.Y - orgin.Y), texture.Width, texture.Height);
        return new Rectangle(0,0,60,60);
    }

// Draw method
    public void Draw(SpriteBatch spriteBatch)
    {
        //spriteBatch.Draw(texture, position, new Rectangle(0,0, (int)texture.Width, (int)texture.Height) , Color.White, rotation, orgin, 1, SpriteEffects.None, 0);
        spriteBatch.Draw(texture, position, null, Color.White, rotation, orgin, 1, SpriteEffects.None, 0);
    }

```

Help is really preciated! I'm doing a hand in task that I need to complete soon! Thanks!

# Answer
> 1 votes
Do you ever move the bounds? If not, then all the rectangles are always at 0, 0, 60, 60 and always intersecting. You need to move the bounds to the location of your ship/asteroid:

```
public Rectangle Bounds()
{
    int width = 60;
    int height = 60;

    int x = position.X - (width/2);
    int y = position.Y - (height/2);

    return new Rectangle(x, y, width, height);
}

```

# Answer
> 1 votes
You are not updating your rectangle, however you do not want to be creating it every test so you could when you set up the class create the rectangle.

```
public Spaceship() {
  rectangle = new Rectangle(position.X, position.Y, 60, 60);
}

```

then call bounds but update x and y before returning

```
public Rectangle Bounds()
{
    rectangle.X = position.X - (width/2);
    rectangle.Y = position.Y - (height/2);

    return rectangle;
}

```

this will avoid multiple objects being created and destroyed in your update part of game loop.

---
Tags: xna
---


title: UDK game Prisoners/Guards

text:
# Question
Title: UDK game Prisoners/Guards
For school I need to make a little game with UDK, the concept of the game is:

The player is the headguard, he will have some other guard (bots) who will follow him. Between the other guards and the player are some prisoners who need to evade the other guards.

It needs to look like this

My idea was to let the guard bots follow the player at a certain distance and let the prisoners bots in the middle try to evade the guard bots. Now is the problem i'm new to Unreal Script and the school doesn't support me that well.

Untill now I have only was able to make the guard bots follow me. I hope you guys can help me or make me something that will make this game work.

Here is the class i'm using to let te bots follow me:

```
class ChaseControllerAI extends AIController;

var Pawn player;
var float minimalDistance;
var float speed;
var float distanceToPlayer;
var vector selfToPlayer;

auto state Idle
{
    function BeginState(Name PreviousStateName)
    {

        Super.BeginState(PreviousStateName);
    }

    event SeePlayer(Pawn p)
    {

        player = p;
        GotoState('Chase');
    }
Begin:

       player = none;
       self.Pawn.Velocity.x = 0.0;
       self.Pawn.Velocity.Y = 0.0;
       self.Pawn.Velocity.Z = 0.0;
}
state Chase
{
    function BeginState(Name PreviousStateName)
    {

        Super.BeginState(PreviousStateName);
    }
    event PlayerOutOfReach()
    {
        `Log("ChaseControllerAI CHASE Player out of reach.");

        GotoState('Idle');
    }
//  class ChaseController extends AIController; CONTINUED
// State Chase (continued)
    event Tick(float deltaTime)
    {
       `Log("ChaseControllerAI in Event Tick.");

       selfToPlayer =  self.player.Location - self.Pawn.Location;
       distanceToPlayer = Abs(VSize(selfToPlayer));

       if (distanceToPlayer > minimalDistance)
       {
           PlayerOutOfReach();
       }
       else
       {
          self.Pawn.Velocity = Normal(selfToPlayer) * speed;
          //self.Pawn.Acceleration =    Normal(selfToPlayer) * speed;
          self.Pawn.SetRotation(rotator(selfToPlayer));
          self.Pawn.Move(self.Pawn.Velocity*0.001); // or *deltaTime
       }
    }
Begin:
     `Log("Current state Chase:Begin: " @GetStateName()@"");
}

defaultproperties
{
    bAdjustFromWalls=true;
    bIsPlayer= true;
    minimalDistance = 1024; //org 1024
    speed = 500;
}

```

# Answer
Assuming that the idea is that prisoners want to escape the circle of guards, trying to avoid them, what you could try is to apply something like the potential fields approach: http://aigamedev.com/open/tutorials/potential-fields/ With potential fields, guards will apply a repulsive force to the prisoners that come too close to them, and this will change the path prisoners will try to follow, apparently trying to stay away from them. I suppose prisoners will try to move to a position outside the circle of guards: in a simple way, if your prisoner is moving in the direction of a point outside the circle, at each update (or less frequently) you can check if it is close enough (sees) to any guard, and in the update do:

```
self.Velocity = Normal(self.Velocity) * speed;

// distance is the distance between this Prisoner and the closest Guards,
// minDistance is the distance at which if
if (distance < minDistance)
{
    vector rp = Normal(guard.RepulsiveForce) * (minDistance / distance);
    self.Velocity += rp;
}

```

Of course the Guard class needs a RepulsiveForce vector that will indicate the direction to which he will try to push close Prisoners: this vector will modify the current velocities of Prisoners that get close enough, and they will look like they will try to avoid them. But again, what you should also do is running a path planning algorithm (like A\* star) for the prisoners to find a path and, while running the A\*, treat the Guards (probably with a bigger influence circle) as obstacles.
> 1 votes

---
Tags: ai, udk
---


# Question
Title: Light levels - How to determine if a character should be spotted
Our team is trying to develop a stealth system with the UDK. Part of this will involve lighting.

The idea being that if you're hiding in a dark corner of the room, the armed goons will not start attacking you.

I've been looking for a few hours now. And while I can't say I have no leads it seems that now is a good time to start asking for help.

At the simplest level, I'm looking for a way to determine how brightly lit an actor is (primarily the player right now).

A bit beyond that, what they are wearing might also be a factor. Someone wearing solid dark clothing is going to be harder to spot than someone in a loud Hawaiin t-shirt covered in (given the stealth context probably stolen) diamonds.

The lighting will be dynamic, so the solution needs to be dynamic. As an example, a guard might get rather upset, grab a torch on the wall and throw it in your direction.

# Answer
> 5 votes
I'm not 100% sure if these are possible with the UDK, someone please correct me if they cannot.

Assuming that you're using point light sources you could trace one ray from all light sources to the character's location and see how many, if any, collide.

Then you can elaborate on the basic idea and check collision with multiple parts of the body, like torso+head+feet and decide on how many lights need to be hitting to trigger the reaction.

Or even more complex, using those same body parts first run a collision ray from the NPC's eyes and see what parts he could see if they were lit... and then run light collisions on only those body parts.

Idea number two, which will be more accurate and maybe slower, is to render to a small offscreen buffer the scene from the NPC's eyes location to the character's. Use shaders that make everything black except the character's lighting equations. Average that small buffer to see how much lit character the NPC can see and decide on a value to say that the player is detected.

Without all that, many stealth games use pre-calculated dark areas and only one mobile light source like a guard's flashlight to dodge with just one collision check which may make game and level design easier to tune too.

# Answer
> 0 votes
For the sake of gameplay itself, it would be valuable to modify how visible the character needs to be in order to be spotted based on the attentiveness of the goons. IF they're distracted, or bored, or working on something else, the character will have to be much more visible than if they're on patrol or even actively looking for him.

---
Tags: lighting, udk
---


title: Multi Screen Rendering in Unity

text:
# Question
Title: Multi Screen Rendering in Unity
My experience with Unity in not that in depth. But I am wondering if it possible in unity to split what is being rendered across multiple screens.

It's hard to explain, so here is an image:

So while the middle screen is fine to render, I want to spread the image all around the player. That is both to the side and, the bottom and top of the player.

Is such a thing possible? Has anyone ever done something similar?

# Answer
Unity doesn't support rendering to multiple targets, which leaves 2 options:

1. Render a single really-wide image, and use a screen-splitter (such as the Matrox TripleHead2Go) to drive 3 output devices
2. Link 3 computers together via local network. Use the 1st computer to respond to user controls and send transform information to the second two computers. The 2nd and 3rd computers just respond to the network transform information and render. If your scene is interactive or otherwise nondeterministic, this can get complicated.

See also this question which describes some middleware solutions for CAVEs.
> 3 votes

---
Tags: unity, rendering
---


# Question
Title: How to do simultaneous action without it being real time?
This is really a pacing question, but there's no tag for that:

The general concept is that the players are working in a team and need to be able to react to eachother's movement and observations as they happen(not being turn based) without the game having to be played at a real time pace.

This question and it's answers offer some insight: Turn-based strategy games where action happens in real-time? But I'd like to implement it so players can change their queued actions on the bases of realtime stimulus.

Right now my thought is to use an action queueing system in which the players can state a series of actions they intend to take and actions are played out simultaneously until one player runs out of queued actions or certain triggers offer a brief "change your queue" period. It seems like it would be clunky and leave players waiting a lot of the time.

Any bright ideas to make this possible while still enjoyable?

# Answer
The first mechanic this made me think of is from "The Last Night on Earth" which is a web-based zombie survivial game. Players have a set number of actions they can perform during a specific time period, which can be increased through items, in order to work together to survive the zombie attack. At midnight the servers update with the zombie attack and the next day you find out if you lived or died.

If the game is more competitive than cooperative, can have each action a player performs take time (ie: charging lazer beam) so that other players can react.

Alternately if you look at cooperative boardgames the turn order is not really the important part of the decision making process, most decisions for the turn are discussed prior to the first player going in order to have an organized effort. Turn order effects the decision but the decision is front loaded with that knowledge.

Hope this helps.
> 2 votes

# Answer
You can give every turn a fixed time length, for example say 5 seconds, then every player has 5 seconds to react.
> 1 votes

---
Tags: game-design, game-mechanics, multiplayer, turn-based
---


# Question
Title: Windows Phone Performance Analysis makes game run faster. Possible reasons?
A XNA game I was making was running slowly on my WP7 device. However when I started it in Windows Phone Performance Analysis to find the bottleneck, the game ran smoothly on the same device.

I figured the problem out a little later, and it was an adjacency-checking function. I have optimized the function and the game works fine now.

Why was the game magically speeding up in Perf Analysis mode? Any possible explanations?

This was the code that ran faster on the Perf Analysis mode, but slow otherwise. It is a damage-dealing function in a tower defense game.

```
 foreach (Target myTarget in _targets)
 {
        for (int x = -1; x <= 1; x++)
        {
                for (int y = -1; y <= 1; y++)
                {
                    if (x == 0 && y == 0) continue;
                    try
                    {
                        Tile adjacent = _tiles[(int)myTarget.CurrentTile.X + x, (int)myTarget.CurrentTile.Y + y];
                        if (adjacent.Tower != null)
                        {
                            DealDamage(myTarget, adjacent.Tower);
                        }
                    }
                    catch
                    {
                    }
                }
            }
 }

```

I optimized it later by checking damage for each tower instead of each target.

# Answer
My guess is the try/catch overhead for each iteration of a potentially large nested loop was killing your performance and that the analysis tool somehow affected the exception handler overhead. You could easily test that by removing the exception handling and running normally, without the profiler.

You definitely don't want a try/catch on the inside of a tight loop. You would be much better off ensuring that you account for anything that can generate an exception within your loop via conditional checks, or at the very least put the try/catch around the loop as a whole.
> 1 votes

# Answer
I am not familiar with the tool itself, nor I am an expert on compiler optimization, but the reason could lie in the line:

```
Tile adjacent = _tiles[(int)myTarget.CurrentTile.X + x, (int)myTarget.CurrentTile.Y + y];

```

What could happen here is that the a `Tile` adjacent is created on the stack, with values copied from the the right tile in `_tiles[]` (you are not using what would be a reference in C++, and I don't know if they exist in C#). Therefore, you are continuously creating and destroying a `Tile` object, and moreover, inside 2 big nested for loop. Although it's on the stack, this could definitely affect speed. What maybe happened is that the Perf Analysis mode recognized this scenario, pre-allocated a `Tile` object outside the nested loop and kept on using it through the function, avoiding the overhead of creation/destruction.
> 0 votes

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


# Question
Title: Implementing a sine using a bezier curve
I'm developing a 2D game using Cocos2d-x. Is possible to use `CCBezierTo` to parameterize a sine function?

# Answer
Just use Bezier, giving 3 points in concave section, and another 3 in convex section, its easier than give all points to do a perfect sine, and the trajectory is the same.
> 2 votes

# Answer
You could create a Bézier curve that matches a sine (read this article for an example). Creating a Bézier curve from a sine, just to feed into `CCBezierTo` seems like a very counter-intuitive way of doing things though.

I would skip `CCBezierTo` entirely and update the position of your sprite yourself. You could do so in your update method or implement a `CCAction` yourself. The easiest form of movement would be to increase `x` constantly (or with a decaying value to simulate some sort of drag) and use the sine function to calculate `y`.
> 3 votes

---
Tags: cocos2d-x, curves, beziers
---


# Question
Title: Managing text-maps in a 2D array on to be painted on HTML5 Canvas
So, I'm making a HTML5 RPG just for fun. The map is a `<canvas>` (512px width, 352px height | 16 tiles across, 11 tiles top to bottom). I want to know if there's a more efficient way to paint the `<canvas>`.

Here's how I have it right now.

## How tiles are loaded and painted on map

The map is being painted by tiles (32x32) using the `Image()` piece. The image files are loaded through a simple `for` loop and put into an array called `tiles[]` to be PAINTED on using `drawImage()`.

First, we load the tiles...

and here's how it's being done:

```
// SET UP THE & DRAW THE MAP TILES
tiles = [];
var loadedImagesCount = 0;
for (x = 0; x <= NUM_OF_TILES; x++) {
  var imageObj = new Image(); // new instance for each image
  imageObj.src = "js/tiles/t" + x + ".png";
  imageObj.onload = function () {
    console.log("Added tile ... " + loadedImagesCount);
    loadedImagesCount++;
    if (loadedImagesCount == NUM_OF_TILES) {
      // Onces all tiles are loaded ...
      // We paint the map
      for (y = 0; y <= 15; y++) {
        for (x = 0; x <= 10; x++) {
          theX = x * 32;
          theY = y * 32;
          context.drawImage(tiles[5], theY, theX, 32, 32);
        }
      }
    }
  };
  tiles.push(imageObj);
}

```

Naturally, when a player starts a game it loads the map they last left off. But for here, it an all-grass map.

Right now, the maps use 2D arrays. Here's an example map.

```
[[4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 4, 1, 1, 1, 1, 1],
[1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 1, 1, 1, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 1, 13, 13, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 1, 13, 13, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 1, 13, 13, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 1, 1, 1, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 13, 13, 13, 1, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 13, 13, 11, 11, 11, 13, 13, 13, 13, 13, 13, 13, 1],
[13, 13, 13, 1, 1, 1, 1, 1, 1, 1, 13, 13, 13, 13, 13, 1],
[1, 1, 1, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 1, 1, 1]];

```

I get different maps using a simple `if` structure. Once the 2d array above is `return`, the corresponding number in each array will be painted according to `Image()` stored inside `tile[]`. Then `drawImage()` will occur and paint according to the `x` and `y` and times it by `32` to paint on the correct `x-y` coordinate.

## How multiple map switching occurs

With my game, maps have five things to keep track of: `currentID`, `leftID`, `rightID`, `upID`, and `bottomID`.

* **currentID:** The current ID of the map you are on.
* **leftID:** What ID of `currentID` to load when you exit on the left of current map.
* **rightID:** What ID of `currentID` to load when you exit on the right of current map.
* **downID:** What ID of `currentID` to load when you exit on the bottom of current map.
* **upID:** What ID of `currentID` to load when you exit on the top of current map.

Something to note: If either `leftID`, `rightID`, `upID`, or `bottomID` are NOT specific, that means they are a `0`. That means they cannot leave that side of the map. It is merely an invisible blockade.

So, once a person exits a side of the map, depending on where they exited... for example if they exited on the bottom, `bottomID` will the number of the `map` to load and thus be painted on the map.

Here's a representational .GIF to help you better visualize:

As you can see, sooner or later, with many maps I will be dealing with *many* IDs. And that can possibly get a little confusing and hectic.

The obvious pros is that it load 176 tiles at a time, refresh a small 512x352 canvas, and handles one map at time. The con is that the MAP ids, when dealing with many maps, may get confusing at times.

## My question

* Is this an efficient way to store maps (given the usage of tiles), or is there a better way to handle maps?

I was thinking along the lines of a giant map. The map-size is big and it's all one 2D array. The viewport, however, is still 512x352 pixels.

Here's another .gif I made (for this question) to help visualize:

Sorry if you cannot understand my English. Please ask anything you have trouble understanding. Hopefully, I made it clear. Thanks.

# Answer
> 5 votes
Edit: Just saw that my answer was based on your code but didn't actually answer your question. I kept the old answer in case you can use that information.

Edit 2: I have fixed 2 issues with the original code: \- The +1 addition in the calculation of end x and y was by mistake inside the brackets, but it needs to be added after the division. \- I forgot to validate the x and y values.

You could simply have the current map in memory and load the surrounding maps. Imagine a world that consists of a 2d array of single levels of the size 5x5. The player starts in field 1. As the top and the left bounds of the level are on the edge of the world, they do not need to be loaded. So in that case level 1/1 is active and level 1/2 and 2/1 are loaded... If the player now moves to the right, all levels (besides the one your moving to) are unloaded and the new surroundings are loaded. Means level 2/1 is now active, 1/1, 2/2 and 3/1 are now loaded.

I hope this gives you an idea how it could be done. But this approach won't work very good, when every level has to be simulated during the game. But if you can freeze unused levels this should work fine.

Old Answer:

What I do when rendering the level (also tile based) is to calculate which items from the tile array intersect with the viewport and then I only render those tiles. Like that you can have big maps but only need to render the portion on screen.

```
//Mock values
//camera position x
//viewport.x = 233f;
//camera position y
//viewport.y = 100f;
//viewport.w = 640
//viewport.h = 480
//levelWidth = 10
//levelHeight = 15
//tilesize = 32;

//startX defines the starting index for the x axis.
// 7 = 233 / 32
int startX = viewport.x / tilesize;

//startY defines the starting index
// 3 = 100 / 32
int startY = viewport.y / tilesize;

//End index y
// 28 = (233 + 640) / 32 + 1
int endX = ((viewport.x + viewport.w) / tilesize) + 1;

//End index y
// 19 = (100 + 480) / 32 + 1
int endX = ((viewport.x + viewport.w) / tilesize) + 1;

//Validation
if(startX < 0) startX = 0;
if(startY < 0) startY = 0;
//endX is set to 9 here
if(endX >= levelWidth) endX = levelWidth - 1;
//endX is set to 14 here
if(endY >= levelHeight) endY = levelHeight - 1;

for(int y = startY; y < yEnd; y++)
    for(int x = startX; x < xEnd; x++)
          [...]

```

**Note:** The code above is not tested but it should give an idea what to do.

Following a basic example for a viewport representation:

```
public class Viewport{
    public float x;
    public float y;
    public float w;
    public float h;
}

```

A javascript representation would look like

```
<script type="text/javascript">
//Declaration
//Constructor
var Viewport = function(xVal, yVal, wVal, hVal){
    this.x = xVal;
    this.y = yVal;
    this.w = wVal;
    this.h = hVal;
}
//Prototypes
Viewport.prototype.x = null;
Viewport.prototype.y = null;
Viewport.prototype.w = null;
Viewport.prototype.h = null;
Viewport.prototype.toString = function(){
    return ["Position: (", this.x, "/" + this.y + "), Size: (", this.w, "/", this.h, ")"].join("");
}

//Usage
var viewport = new Viewport(23, 111, 640, 480);
//Alerts "Position: (23/111), Size: (640/480)
alert(viewport.toString());
</script>

```

If you take my code example, you simple have to replace the int and float declarations with var. Also make sure that you use Math.floor on those calculations, that are assigned to the int based values, to get the same behavior.

One thing I would consider (though I'm not sure if this matters in javascript) is to put all tiles (or as many as possible) in one big texture instead of using many single files.

Here is a link explaining how to do it: http://thiscouldbebetter.wordpress.com/2012/02/25/slicing-an-image-into-tiles-in-javascript/

# Answer
> 3 votes
Storing maps as tiles is useful for allowing you to re-use assets and re-designing the map. Realistically though it doesn't really offer much benefit to the player. Plus, you're then re-drawing every single tile each time. Here's what I would do:

**Store the whole map as one big array.** There's no point having maps and submaps, as well as potentially sub-sub-maps (if you're entering buildings, for instance). You're loading it all anyway and this keeps everything nice and simple.

**Render the map all at once.** Have an off-screen canvas that you render the map to and then use this in your game. This page shows you how to do it with a simple javascript function:

```
var renderToCanvas = function (width, height, renderFunction) {
  var buffer = document.createElement('canvas');
  buffer.width = width;
  buffer.height = height;
  renderFunction(buffer.getContext('2d'));
  return buffer;
};

```

This is assuming your map isn't going to change much. If you wanted to render sub-maps in-place (for example, the inside of a building) you just render that to a canvas too and then draw it on top. Here's an example of how you can use this to render your map:

```
var map = renderToCanvas( map_width*32, map_height*32, renderMap );

var MapSizeX = 512;
var MapSizeY = 352;

var draw = function(canvas, mapCentreX, mapCentreY) {
  var context = canvas.getContext('2d');

  var minX = playerX - MapSizeX/2;
  var minY = playerY - MapSizeY/2;

  context.drawImage(map,minX,minY,MapSizeX,MapSizeY,0,0,MapSizeX,MapSizeY);
}

```

This will draw a small portion of the map centred around `mapCentreX, mapCentreY`. This will offer you smooth scrolling around the entire of the map, as well as sub-tile movement - you can store the player position as 1/32ths of a tile, so you can get smooth movement across the map (Clearly if you want to move tile-by-tile as a stylistic choice, you can just increment in chunks of 32).

You can still chunk up your map if you like, or if your world is huge and wouldn't fit in memory on your target systems (bear in mind that even for 1 byte per pixel, a 512x352 map is 176 KB) but by pre-rendering your map like this you'll see a large performance gain in most browsers.

What this gives you is the flexibility of reusing tiles across the world without the headache of editing one big image, but also allowing you to run this quickly and easily and only consider one 'map' (or as many 'maps' as you like).

# Answer
> 2 votes
In all the implementations I have seen tile maps are often generated as one big image and then "chunked" into smaller pieces.

https://gamedev.stackexchange.com/a/25035/10055

These chunks are usually in powers of 2, so they fit in memory optimally.

# Answer
> 1 votes
An easy way to keep track of the IDs would be to simply use another 2d array with them in: by only maintaining x,y on that "meta array", you can easily look up the other IDs.

That being said, here's Google's take on 2D tiled canvas gaming (well, actually HTML5 multiplayer, but tile engine is also covered) from their recent I/O 2012: http://www.youtube.com/watch?v=Prkyd5n0P7k It also has source code available.

# Answer
> 1 votes
Your idea to load the entire map into an array first, is an efficient way, but it will be easy to get JavaScript Injection'd, anyone will be able to know the map and there goes the adventure.

I'm working on a RPG game web-based too, the way I load my map is via Ajax from a PHP page, that loads the map from the database, where it says the X, the Y, the Z position and the vlaue of the tile, draw it, and finally the player move.

I'm still working on it to make it more efficient, but the map loads fast to enough to keep it this way by now.

# Answer
> 1 votes
**No**, *a array is the most efficient way of storing a tile map*.

There might be a few structures which require a little less memory but only at the expense of much higher costs for loading and accessing the data.

---

What needs some consideration however is when you are going to load the next map. Given that the maps are not especially big, the thing that actually will take the longest is waiting for the server to deliver the map. The actual loading will only take a few milliseconds. But this waiting can be done asynchronous, it doesn't have to block the flow of the game. So the best thing is not loading the data when needed but before. The player is in one map, now load all the adjacent maps. Player moves in the next map, load all adjacent maps again, etc., etc. The player won't even notice that your game is loading in the background.

This way you can also create a illusion of a border less world by also drawing the adjacent maps too, in that case you need to load not only the adjacent maps but also those adjacent of those, though.

# Answer
> 0 votes
I'm not sure why you think: As you can see, sooner or later, with many maps I will be dealing with many IDs. And that can possibly get a little confusing and hectic.

LeftID will always be -1 of the currentID, the rightID will always be +1 of the currentID.

UpID will always be -(total map Width) of the current ID and downID will always be +(total map width) of the current ID with the exception of zero meaning you've hit the edge.

A single map can be broken into many maps, and are saved sequentially with mapIDXXXX where XXXX is the id. That way, there isn't anything to be confused about. I've been to your site and it seems, I could be wrong, that the problem is down to your map editor imposing a size limitation which is hindering your automation to break down a large map into multiple small ones on save and this limitation is probably restricting a technical solution.

I've written a Javascript map editor which scrolls in all direction, 1000 x 1000 (I wouldn't recommend that size) tiles and it still moves as good as 50 x 50 map and that is with 3 layers including parallax scrolling. It saves and read in json format. I'll send you a copy if you say you don't mind an email approximately 2meg. It is meant to be on github but I haven't got any decent (legal) tileset which is why I haven't bothered to put it on there yet.

---
Tags: javascript, html5, html-canvas, image
---


title: Component Based Design DLL

text:
# Question
Title: Component Based Design DLL
I'm undecided on a design decision. Now for my game I was thinking on splitting components into separate dlls. This would allow for a more modular approach, especially when in need of updates. On launch it \[the game\] could swap out newer versions of the dll coming from a centralized server. This would allow us to provide updates to each component separately and also allow us to quickly swap dll's for different implementation.

Now is this design used, and how effective is it?

I started implementing it, and loading a dll through run-time ads a lot of complexity (unless i'm doing it wrong). Another problem that could arise is some components are optional. So it would ad additional complexity.

So what i'm trying to get to is: Is splitting separate components and subsystems in dll's?

This would allow the exe to be a lot smaller, and possibly make the whole system a little more organized.

# Answer
> 2 votes
It is not used by any game engine I've ever heard of, and I would strongly recommend against it.

All of the theoretical advantages of the model are red herrings. Smaller executables don't matter, the whole size of the loaded game matters, and an exe+dlls is larger than the same code all compiled into the same exe.

Libraries dont organize code. Your file structure (naming, folders, namespaces, etc) organizes your code. Use libraries for technical purposes, not to get around a lack of knowledge on how to use Visual Studio filters properly. One good reason to use separate static libs in Visual Studio is to use different sets of precomputed headers, for instance.

Updating via DLLs is also not a good use of time. The DLLs are going to be tightly tied to the specific version of the EXE being run an probably to the other DLLs as well (components have dependencies on othe components).

Reloading DLLs is not a good idea, either, for similar reasons to the previous point. Plus, reloading the DLL means you have tO unload all data it's using, serialize it somehow, reload the DLL, then unserialize the old data.

As others pointed out, there are many complexities and limitations of using separate DLLs. Given all those costs and a complete lack of any real benefit, there's just no reason to go that route.

As a final note, remember that the compiler can't optimize across DLL boundaries. Your game will be much slower than if you compile everything into a single EXE with link-time code generation turned on.

---
Tags: c++, component-based
---


title: 2D game development with C++

text:
# Question
Title: 2D game development with C++
I'm pretty newbie in this things and I've never really had particular experience in game developing. I started learning something about 3D (using 3Ds Max and then Blender) and then 3D game developing using OpenGL.

While with 3D i found it very easy to get started, I don't have a clue on where to start for 2D game developing.

For example, I know that for 3D you can use SDL for keyboard, mouse and OpenGL (I don't like Direct X) for animation and 3d models. Then you can create `.obj` files with Blender or any 3D modeling software and then parse that file to import vertexes and edges in OpenGL without drawing it yourself (which is almost impossible).

But for 2D games I don't know:

* What API could I use
* What are sprites and animated sprites made of
* What softwares may I have to use

I mainly like cross-platform things. I'm a bit confused about this but I'd like someday to export my game into all OS. I'd like to use c++ and I'd like to use Open sources softwares and API over owned ones (Like Direct X is for Windows). Also I'd like to use resources that can be used over Mac OS, Windows and Linux as well. I don't like easy things, such as pre made frameworks or game engines. I'd like to start from scratch.

Could you please explain to me how to get started?

# Answer
SDL and OpenGL are perfectly suitable for 2D. There's no reason to change APIs.

SDL has a built in 2D drawing API, and there is a newer SDL\_gfx module for more modern 2D rendering needs.

The triangles and textures and such you draw with OpenGL can just as easily be flat shapes in an orthographic projection view. Any portable 2D library you use is just going to be wrapping OpenGL with a handful of simple helper functions, so of you're already comfortable with OpenGL, just use it (and write your own helpers as needed).

Every 2D game I've ever written has been in OpenGL and C++, and I've used SDL for a few of them. They definitely work for the job.
> 2 votes

# Answer
I'd recommend using lazyfoo's tutorials which uses SDL, which is very cross-platform (officially: Win, OS X, linux, even Android and iOS! and some others non-officially), and it also supports OpenGL!

Not only do the above make SDL great, but the sheer fact that all you need to do is recompile on the target platform (for linking purposes)!

Of course, there are a ton of questions using SDL, so don't be afraid that it's an obscure library.

The library itself isn't open-source, and you should go for the external library option so you don't have to make all your code open-source, but SDL is still a great library!
> 2 votes

# Answer
This is probably going to get closed so i'll just throw something in.

SDL is "dimension agnostic", it's just an abstraction layer that makes working with given operating system easier. SDL (SFML is better if you're using C++) uses OpenGL to do 2D rendering. Which brings me to an important point, OpenGL is just a way to ease access to your graphics card functionality. It allows you to draw triangles on the screen, that's it, that's what graphics cards are so good at. If you make those triangles seem like they're 2D or 3D on a flat screen, that's up to you. OpenGL isn't some sort of a magical 3D fairy land API, you can easily create 2D games with it.
> 1 votes

# Answer
The extremely well put together tutorials videos over at http://fixbyproximity.com create a basic 2D shooter from scratch. The owner of the site, Mike Geig, has recorded hours of himself using the Allegro engine and Visual Studio 2010 to build it completely from scratch. There's an optional shorter set of videos at the end where he refactors the entire thing into C++ code (it's initially in a C-style coding).

The Allegro engine is a complete wrapper for 2D game development and makes everything pretty simple to work with.

Sprites are just basic 2D drawings - do a Google search for 'sprite sheets' and you'll see a bunch of them. Geig's videos also show them in action.

Any graphics software can create 2D sprites - so really, an IDE and Allegro and some sprite sheets are all you'd likely need to start putting together some demos.

Good luck!
> 0 votes

---
Tags: c++, cross-platform, open-source
---


# Question
Title: Collection of Simple Children's Game Mechanics
## Context:

I've tried Googling / searching on Amazon for books on this, but I end up get all types of resources on "How to Gamify XYZ" rather than the mechanics of simple games.

I'm trying to build a collection of "simple game mecahnics" that often shows up in Children's games. For example:

* color in the picture
* fill in pieces of a puzzle
* memory/matching game

## Question:

Is there some gigantic list of these "mechanics of simple games" ? Somewhere?

I don't need actual implementation (I can do that on my own).

I just need english descriptions of what the mechanics are.

Thanks!

# Answer
> 2 votes
This is an interesting question you bring up. Which touches on a fairly broad scope.

The problem is that children's games are still games. The subset of mechanics that are in children's games, is not substantially smaller than the set of all game mechanics.

What's more, people are making up new mechanics constantly. It's a trivial process that anyone can, and does do.

And in order to get any sense of those mechanics... while then you're asking for a complete study on game design itself.

May I ask what it is you're building this list for? There might be an easier way of doing this.

---
Tags: game-design
---


title: 2D Tower Targeting (Tower Defense)

text:
# Question
Title: 2D Tower Targeting (Tower Defense)
so just to be more specific this question isn't in regards to how to target enemies or anything like that rather its purposed towards a specific targeting issue i have with me enemies in its current state.

So the issue im having is that if i fire a bullet towards an enemy and then before that bullet hits the desired enemy it was initially set too, if my tower changes its target then suddenly my bullet does a u-turn and then targets this new enemy. Which isn't what i want.

I'm using C++. I know this is a pointer issue, that my pointer's memory address changes to point at the new enemy which the tower would be facing, the problem is i just don't know how to solve this, personally for me i don't use pointers that much and unfortunately im just not very good at using them it seems :/. Any help on this issue is greatly appreciated, its been annoying me now for the better part of a few hours, and if anyone could explain what I'm doing wrong here as-well that would be great! So here's my targeting code

```
for (int numOfEnemies = 0; numOfEnemies < lib.numberOfEnemies; numOfEnemies++)
{
    float y =  pow(enemies[numOfEnemies].position.y - position.y, 2);
    float x = pow(enemies[numOfEnemies].position.x - position.x, 2);

    if (sqrt(y + x) < range && enemies[numOfEnemies].alive)
    {
        cEnemy =  &enemies[numOfEnemies];
        acquiredTarget = true;
        break;
    }
}

```

Simple enough, then this is how i'm passing it in my Projectile class;

```
bullets.push_back(Projectile(bulletPosX, bulletPosY, 8, 8, damage, 1, speed, *cEnemy, currentUpgradeLevel));

```

Which specifically then uses this constructor;

```
Projectile::Projectile(float x, float y, int w, int h, int dmg, int type, float mxSpeed, Enemies& bulletTarget, int towerLevel)
{
     position.x = x;
     position.y = y;
     width = w;
     height = h;
     bulletAngle = 0;
     renderingAngle = 0;
     damage = dmg;
     active = true;
     ySpeed = 0;
     xSpeed = 0;
     maxSpeed = mxSpeed;
     typeOfProjectile = type;
     target = &bulletTarget;
}

```

There you see target is then a pointer to an enemy address, the cEnemy (currentEnemy). What my desired effect would be to have my Projectile store the enemy that I pass into it which then until it hits that enemy, the targeted enemy will forever stay focused on the enemy passed in when the projectile was first created.

Again any help greatly appreciated!

For reference

**Enemies** = Class Name. **enemies** = vector array of active *Enemies*.

cEnemy = (Pointer to Enemies Object)/Enemies\* cEnemy.

# Answer
Does it have to be a pointer to an enemy?

If it really does, make a copy of your enemy, and make a new pointer to that. Pass the pointer to the copy and that should resolve your issue.

If it doesn't? Then pass a copy of the target and store the copy of your tower's enemy in your projectile object.
> 0 votes

# Answer
I think it would be best if you use vector to represent projectile direction. So inside your *Projectile* constructor you can have:

```
Projectile::Projectile(...){
    ...
    directionVec = Util::getVector(Point(x, y), bulletTarget.getLocationPoint());
    ...
}

```

and *getVector* can be some static method inside some *Util* class which returns *Vector* when given start and end point.

Using vector to store your direction is convenient because you can *add* it to the current location and thus advance projectile. Scalar Multiplying of normalized vector then adding it to current location point gives you desired advance step.
> 1 votes

---
Tags: c++, 2d, tower-defense
---


# Question
Title: Collision detection between circle and rectangle in 2D
In a game im developing in 2D, im have one or more circles (balls) that can collide with several rectangles (bricks).

Im trying to figure out a collision detection strategy, and have come up with the following plan.

1. For each loop of the game ticker get the x,y point of the start and destination of the ball.
2. Form a rectangle (blue color in fig1.) at the start and dest point that has the balls rotation as well as setting the rectangle width as the balls radius times two.
3. check if the rectangle intersects with anyting in the play area using Separation of Axis
4. if the balls path, defined trough the rectangle intersects with anything in the play area, move the ball to the collision point, and after setting a new start and dest point, rerun from point 2 for as long as there are collisions or the ball has not travelled 100% of its planned distance.

With this strategy i can have collision detection with high ball speeds as well as high precision.

Im a quite new to game development so theres a high probability that im overdoing this, and that there probably exists alternatives to this. Any help/insight on this is greatly appreciated.

# Answer
> 2 votes
I have some ideas, although I'm not sure if any of these is better than your solution. Just something to think about.

1 . To filter out the cases where collision doesn't happen:

Notice, that the area your brick object covers while moving between two Updates, can be represented as a Polygon (let's call it P1). The area that you ball object covers, can be represented with a polygon (rotated rectangle) and two circles (let's call these P2, C1 and C2).

In every update, you create these polygons and circles (hopefully the acceleration of your objects isn't supposed to change between updates). Then check if P1 and (P2 || C1 || C2) intersect. If they don't, then you have no collision.

2 . To get the precision you want:

Interpolate to get the object positions between two Updates. If the ball moves 50 pixels in an Update, but the brick is only 20 pixels thick (or also moves too fast), then you must compare at least 3 states between T1 and T2 (T1 is the previous update, T2 is the current update). You can calculate the positions of the objects in these virtual updates (T1i, T1ii, T1iii etc.) the same way you do for T1 and T2. Then do collision detections with the corresponding object positions (Brick.GetPosition(T1i) vs Ball.GetPosition(T1i) etc.). The good thing about this method is that you can achieve exactly the precision you want, without doing too many or too difficult calculations.

# Answer
> 0 votes
I suggest you to really build the things from simple to complex, which means: start from a simple collision detection approach/routines, and improve it if you see that is not working properly, or not accurately enough. In your case, what you can just do is to simply check, at each timestep, if any ball is intersecting any of your rectangles, and if it is, just perform separation of the circle from the rectangle (move it away so that they don't collide anymore) and adjust the velocity/acceleration/properties (for example, you can mirror the velocity in the collision direction to have a bounce-like effect). From your side, you have the fact that circle and rectangles have very cheap intersection tests (if you have a circle, it intersects a rectangle only if it the center of the circle lies inside the rectangle, or if the center is closer than radius to any of the 4 points of the rectangle. In my opinion, if you assign circles and rectangle to different collision groups (so that collisions among rectangles for example are not checked) and don't use `sqrt` in comparing distances, you will probably make it. If you don't, consider using Bounding Volume Hierarchies to help the collision detection process, or modify the architecture of the game in order to run the collision detection many times between single updates. What you have in mind is a sort of Continuous Collision Detection that is often overkill.

---
Tags: collision-detection, game-mechanics, separating-axis-theorem
---


title: How do I create JavaScript buttons?

text:
# Question
Title: How do I create JavaScript buttons?
I have coded my main menu for the game in HTML and CSS, and need the image buttons to function with the engine, using JavaScript.

How do I create JavaScript buttons?

---

Here are some examples:

* Skip: One image button. Red, when disabled, and green. When enabled, skips the menu, when you come back to play to a continued game. When disabled, will return transitions to normal.
* Restart: When clicked, opens a box with two images and text for *"yes"* and *"no"*. If you click *"yes"*, it restarts game, and when you click *"no"*, it resumes the game.
* Sound: Will have one image button, which will be red for *"on"*, and green, when *"off"*. Turns sound on and off.

---

Here is some example code:

```
function ENGINE_get_option_state(opt:string):string {
    return…;
}

ENGINE_trigger_sound(…)

```

# Answer
> 1 votes
You bind the images/buttons to a variable, then you can access that from your javascript.

For example:

```
<img id="startGame" src="image.png" />

```

Here's how you access the image from javascript:

```
var startGame = document.getElementById('startGame');

```

Now that you have the element in a variable you can do what you want with it. Just setup a function that executes the code you want the button to do. The function can look something like this:

```
startGame.onclick = function() {
alert('Game started!'); // Execute code here.
}

```

Very basic, hope this helps.

**EDIT:** Paste the following to a html document, and you have something to experiment with.

```
<!DOCTYPE HTML>
<html>
<head>
<style>
#startGame {width:100px; height:50px; background:black;}
</style>
</head>
<body>
<div id="startGame"></div>
<script>
window.onload = function() {
    var startGame = document.getElementById('startGame');

    startGame.onclick = function() {
        alert('Game started!');
    }
}
</script>
</body>
</html>

```

---
Tags: javascript
---


# Question
Title: 2D game libraries that support positional stereo sound?
I would like my game to have semi-realistic sound, where the left/right channel volume depends on the position of the sound source within the world.

I've looked and it seems that it's not possible with Löve2d or pygame. They modify the volume of a sound based on distance, but the left and right channels are identical.

Am I wrong? Are there any other 2d game libraries that make this possible?

# Answer
> 1 votes
Check out SFML (C++ or .net), supports 2D/3D sound spatialization.

This is an old tutorial (2.0 changes API quite a bit), but it gives an example.

The 2.0 documentation has functions for GetPosition and such, so it should be easy to implement.

Edit: According to this and this, you are not wrong in thinking that the two mentioned libraries do not support what you want.

# Answer
> 1 votes
*There is no such thing as positional stereo sound.* Audio in stereo formats are pre rendered audio scenes where the listener is at one specific position. It's basically a lot mono channels at different positions mixed together to one. So to get a high quality sound experience you would need all those mono channels and position them where they actually come from. (For example the drum sounds would come from the position where the drum stands, as simple as that.)

You could also split the stereo audio file up into two mono sounds you put into different positions. That isn't realistic but maybe is a good approximation.

---
Tags: 2d, sound
---


title: Best practices with Vertices in Open GL

text:
# Question
Title: Best practices with Vertices in Open GL
What is the best practice in regards to storing vertex data in Open GL? I.e:

```
struct VertexColored {
    public:
        GLfloat position[];
        GLfloat normal[];

        byte colours[];
}

class Terrian  {
    private:
        GLuint vbo_vertices;
        GLuint vbo_normals;
        GLuint vbo_colors;
        GLuint ibo_elements;

        VertexColored vertices[];
}

```

or having them stored seperatly in the required class like:

```
class Terrian  {
    private:
        GLfloat vertices[];
        GLfloat normals[];
        GLfloat colors[];

        GLuint vbo_vertices;
        GLuint vbo_normals;
        GLuint vbo_colors;
        GLuint ibo_elements;
}

```

# Answer
There isn't any best practice. Everything varies on application which is being developed.

For game **renderer** there is **no need to store vertices in both RAM and VRAM**, that means you need to keep only vbo id. **Exception is terrain** where you need to have access to **positions** because of height player placement/collisions.

**Do you need to have all vertex data together?** If you want to have multiple colors for same vertices like different colors for same player models then putting everything together can cause little obstacle in development.

**Do you access data outside from class?** If no, you will only end up with more code like `vertices->position[i]` instead of `positions[i]`. In game/model designer you need to access them from outside, but you aren't accessing all data at same time when you are modeling then you access positions and when you are coloring then you access colors.

Only thing i would put together is `xyz` (`rgb`) values into one structure for nicer code:

```
Vector3 {
   GLfloat x,y,z;
};

Color3 {
   GLbyte r,g,b;
};

```

**Edit:** I'd like to add, that some people are using `unions` for easier glVertex\*3v, glVertex\*4v, glUniform\*v... calling where array is passed instead of separated variables:

```
union Vector3f {
   GLfloat v[3];
   struct {
      GLfloat x,y,z;
   };
};

union Color3b {
   GLbyte c[3];
   struct {
      GLbyte r,g,b;
   };
};

```
> 11 votes

---
Tags: c++, opengl, vertex
---


# Question
Title: Rotation matrices from Quaternion.Identity and -Quaternion.Identity are the same?
If I create a rotation matrix from an identity quaternion then it is the same as a creating it from a negative identity quaternion

```
        Matrix m0 = Matrix.CreateFromQuaternion(Quaternion.Identity);
        Matrix m1 = Matrix.CreateFromQuaternion(-Quaternion.Identity);

        Console.WriteLine(m0);
        Console.WriteLine(m1);

        Console.WriteLine(m0.Forward);   // {X:0 Y:0 Z:-1}
        Console.WriteLine(m1.Forward);   // {X:0 Y:0 Z:-1}

```

Why is this the case?

If I use a negative identity matrix

```
        Quaternion q0 = Quaternion.CreateFromRotationMatrix(Matrix.Identity);
        Quaternion q1 = Quaternion.CreateFromRotationMatrix(-Matrix.Identity);

```

the orientation will be rotated 180 degrees as expected.

# Answer
> 5 votes
Although rotation-matrices and unit-quaternions both can represent an orientation/rotation in 3D space, that does not mean that negating each of its individual terms will result in the same geometrical operation.

**1. Negating each number of a unit-quaternion**

There are always 2 unit-quaternions that represent a single unique orientation. One on each hemisphere of the hypersphere, pointing directly away from each other. In other words, each component of such quaternion is simply negated, however, both represent the same orientation.

Here are 2 examples:

```
Identity-Quaternion:
    axis     :    0.000    0.000    0.000
    w        :    1.000
    magnitude:    1.000 rad:    0.000 deg:    0.000

Negated Identity-Quaternion:
    axis     :   -0.000   -0.000   -0.000
    w        :   -1.000
    magnitude:    1.000 rad:    6.283 deg:  360.000

```

Above you see both, the identity quaternion and its negated quaternion. The first 3 numbers (axis, x, y, z -\> the imaginary part) can be interpreted as the rotation axis. The acos of the 4th number (w) multiplied by 2 is the angle of rotation. Since the rotation axis is basically zero, there is no rotation at all, no matter how big the actual angle is. So both are the same, no rotation change at all.

Another example of a unit-quaternion and its negated quaternion:

```
Q:
    axis     :    0.397    0.555    0.159
    w        :    0.714
    magnitude:    1.000 rad:    1.552 deg:   88.919

Q negated:
    axis     :   -0.397   -0.555   -0.159
    w        :   -0.714
    magnitude:    1.000 rad:    4.731 deg:  271.081

```

Here you see the rotation axis is basically the same, only negated. The angle changed from 89 to 271, which is the same orientation in a circle, just counter-clockwise (360-89 == 271) So again, if you check the numbers properly, "Q" and "Q negated" will result in the same orientation. So the bottom line is:

**Negating each term of a unit-quaternion will result in the same rotation, not in a rotation of 180 degrees**

---

**2. Negating each term of an identity-matrix**

`-Matrix.Identity` is not a rotation matrix anymore, it is a reflection matrix. Hence, this is no valid input for `CreateFromRotationMatrix`, it will return a result however, but that is not correct, as that function only works with valid input. So negating each term in a rotation matrix will not result in a rotation of 180 degrees.

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


# Question
Title: What are some good resources for learning OpenGL on Android?
Mainly I learned how to develop Android applications, but now I want to know how to make high resolution games, so does someone have a good book or a video that teaches OpenGL?

# Answer
> 1 votes
I would recommend you to start with this tutorial. It's directed especially for OpenGL on Android, but it's using old OpenGL ES, so when you understand it then you should learn OpenGL ES2.

Few tutorials for OpenGL ES2:

---
Tags: opengl, android
---


title: Console-type interface in game

text:
# Question
Title: Console-type interface in game
I am currently programming a very simple 2d game in C# with XNA.

I was wondering how to implement a console-type interface in a game or graphical software like there is in Skyrim or Counter-strike or some many more games?

These "consoles" can allow you through various command to change many parameters directly in-game.

I find this very interesting for debugging purposes and I was hoping to implement something similar in my program. Is there a particular way to achieve this?

# Answer
The graphical side should be easy, so i'll omit that.

You have to be able to parse your input properly. If you want to go all out you can read on compiler theory, though i don't think this is what you're looking for.

In general what you want to be able to do is lexical analysis of your input. This means being able to take a string and output tokens. Tokens are objects that say what a particular text is, so you'll have an "id" object for variables or an "operator" object, etc. It doesn't have to be so "official", but you want to be able to tell what each part of the string does/is. Then, you'd build a syntax tree, maybe do syntax analysis to check for errors and put that through your handling code. If you were hardcore, that is. I don't think this is what you're looking for, so i'll just suggest that for now you try coding an FSM and look for key words.

For example, you could just read a line one word at a time (you could tokenize the string and put each token in a list, it's the same thing, but safer) and for the first word check if it's a key word like "bind" or "modify" using if or switch statements. Then in each if/case statement you'd just have the code that handles this command.

So a string "modify fov 90" would create a list of 3 tokens "modify", "fov" and "90" and in if( stringlist\[0\] == "modify" ) you could have more if statements or you could have a global map that takes a string and returns a pointer to the fov variable (or the variable itself) and you'd stringtofloat the 3rd token and use that to set fov. Just don't forget to error check everything, like if stringtofloat returns an error or if you enter this "if" and the stringlist has only 2 elements, etc.

If you want a robust parser, there are a few availible, for example http://www.antlr.org/. The site looks like any terribly boring IT site, but the library is easy to use, just i don't think you actually need that.
> 5 votes

# Answer
Check out the performance monitoring sample, It contains a nice console that you can easily use. (Just take the console class and manager). It contains some nice code to register commands, have arguments, and a lot of stuff.

Also, this may be a bit overkill, but I personally use Neoforce Controls, which has a nice UI library, including a console.
> 3 votes

# Answer
*What is your actual problem? Did you encounter any errors? Your question is pretty much on par with the "how do I maek gaem?" ones. First, try to do it yourself. When you get to any errors, come here or to Stackoverflow.*

---

You can take a look at how I did the following in Python: https://github.com/Yannbane/Pysole.

Generally, I'd suggest you make a `Console` class. This class accepts user input (you'll have to be listening to it), and then translates what has been written to a function name, and then executes the function passing anything written after the name as an argument. You can have a dictionary look-up, that's what I did.

I suggest you also implement a `Command` class. That class would store the function to be executed, the function's name from the console's perspective (the thing you need to write for the function to be executed), number of arguments it gets, a description, and so on. These commands can be added to the console, and I strongly suggest that you don't hardcode them, but provide a way for the user (yourself, in this case) to `console.addCommand` them (or just push them to an array).

It's usually wise to have the console generate a `help` command by its own, which lists all the known commands and their descriptions. All other commands should be user supplied.

All that is written or outputted (as text) also needs to be stored inside the console in a, say, `.text` variable. Each frame, you just render all that text and add a background to it. Alternatively you can use some kind of markup to identify the color of a word and so on...

Other built-in commands you can have:

* clear
* description *\[command\]*
* nargs *\[command\]*
* hide (don't forget to provide another way of bringing it up once it's hidden, such as a keypress)

General suggestions:

* You will probably want to re-use this, so don't make it dependent on your game. The key of software design is code **separation**, so it become re-usable.
* It would be great if the console knew how to draw itself, but provided a way to set things up (font, background, color) to the user, this way you achieve the above point and don't have to recode it each time.
* Having a history array is very useful.

This answer is vague and from my experience, there are really tonnes of ways of doing this, I believe.
> 2 votes

# Answer
I did this awhile back by embedding IronPython, and redirecting standard in/out/error to a DrawableGameComponent class that maintained a list of strings for display, command history, etc with standard SpriteBatch textcommands, and a "hotkey" to toggle the control's Visible property. It's pretty easy to expose all of the classes and objects in your XNA project so that you can tweak things at run time, provides scripting, classes, etc.

Also, never underestimate the power of the Visual Studio command window. (though I think that's only available in VS Pro or better). For simple debugging, I added a case to my keyboard handler to call

```
Debugger.Break();

```

When I needed to stop at some point in execution, then used the command window to make changes to game state.
> 0 votes

---
Tags: xna, c#, gui, interface
---


title: RPG and human psychology

text:
# Question
Title: RPG and human psychology
Is there any book or article that describe interaction of RPG elements and human psychology?

For example: what will be more popular and attracting for people - linear function of experience per level or exponential function of experience per level?

# Answer
> 10 votes
Don't design like this.

It is definitely possible to figure out the "optimal" way to design each part in your game to attract some hypothetical average player. Sometimes you'll find books about the thing you're trying to design, sometimes papers.

But the average person is a fiction. No one actually *is* the average person; everyone deviates greatly in at least some preferences and attitudes. Some what paradoxically, by designing a game for the average person you are designing a game for no one.

Design a game you'd like to play. Design a game your friends, or parents, or partner(s), or kids want to play. Design one your neighbors or church or people from your hometown or people who also like your favorite book want to play. Root the design in a *real locus for real people*.

Don't design a game that the average person wants to play, because then no one will want to play it. And even if someone does, it will be a thoroughly average game.

# Answer
> 2 votes
You don't strictly need to read a psychology book for that, actually, but The Art of Game Design has what you need. With examples by real developers.

---
Tags: rpg, psychology
---


# Question
Title: Simple OpenGL program major slow down at high resolution
I have created a small OpenGL 3.3 (Core) program using freeglut. The whole geometry is two boxes and one plane with some textures. I can move around like in an FPS and that's it. The problem is I face a big slow down of fps when I make my window large (i.e. above 1920x1080). I have monitors GPU usage when in full-screen and it shows GPU load of nearly 100% and Memory Controller load of ~85%. When at 600x600, these numbers are at about 45%, my CPU is also at full load. I use deferred rendering at the moment but even when forward rendering, the slow down was nearly as severe. I can't imagine my GPU is not powerful enough for something this simple when I play many games at 1080p (I have a GeForce GT 120M btw). Below are my shaders,

**First Pass**

```

#VS
#version 330 core

uniform mat4 ModelViewMatrix;
uniform mat3 NormalMatrix;
uniform mat4 MVPMatrix;

uniform float scale;

layout(location = 0) in vec3 in_Position;
layout(location = 1) in vec3 in_Normal;
layout(location = 2) in vec2 in_TexCoord;

smooth out vec3 pass_Normal;
smooth out vec3 pass_Position;
smooth out vec2 TexCoord;

void main(void){

    pass_Position = (ModelViewMatrix * vec4(scale * in_Position, 1.0)).xyz;
    pass_Normal = NormalMatrix * in_Normal;
    TexCoord = in_TexCoord;

    gl_Position = MVPMatrix * vec4(scale * in_Position, 1.0);
}

#FS
#version 330 core

uniform sampler2D inSampler;

smooth in vec3 pass_Normal;
smooth in vec3 pass_Position;
smooth in vec2 TexCoord;

layout(location = 0) out vec3 outPosition;
layout(location = 1) out vec3 outDiffuse;
layout(location = 2) out vec3 outNormal;

void main(void){
    outPosition = pass_Position;
    outDiffuse = texture(inSampler, TexCoord).xyz;
    outNormal = pass_Normal;
}

```

**Second Pass**

```

#VS
#version 330 core

uniform float scale;

layout(location = 0) in vec3 in_Position;

void main(void){
    gl_Position = mat4(1.0) * vec4(scale * in_Position, 1.0);
}

#FS
#version 330 core

struct Light{
    vec3 direction;
};

uniform ivec2 ScreenSize;
uniform Light light;

uniform sampler2D PositionMap;
uniform sampler2D ColorMap;
uniform sampler2D NormalMap;

out vec4 out_Color;

vec2 CalcTexCoord(void){
    return gl_FragCoord.xy / ScreenSize;
}

vec4 CalcLight(vec3 position, vec3 normal){

    vec4 DiffuseColor = vec4(0.0);
    vec4 SpecularColor = vec4(0.0);

    vec3 light_Direction = -normalize(light.direction);
    float diffuse = max(0.0, dot(normal, light_Direction));

    if(diffuse > 0.0){
        DiffuseColor = diffuse * vec4(1.0);

        vec3 camera_Direction = normalize(-position);
        vec3 half_vector = normalize(camera_Direction + light_Direction);

        float specular = max(0.0, dot(normal, half_vector));
        float fspecular = pow(specular, 128.0);
        SpecularColor = fspecular * vec4(1.0);
    }
    return DiffuseColor + SpecularColor + vec4(0.1);
}

void main(void){

    vec2 TexCoord = CalcTexCoord();
    vec3 Position = texture(PositionMap, TexCoord).xyz;
    vec3 Color = texture(ColorMap, TexCoord).xyz;
    vec3 Normal = normalize(texture(NormalMap, TexCoord).xyz);

    out_Color = vec4(Color, 1.0) * CalcLight(Position, Normal);
}

```

Is it normal for the GPU to be used that much under the described circumstances? Is it due to poor performance of freeglut?

I understand that the problem could be specific to my code, but I can't paste the whole code here, if you need more info, please tell me.

# Answer
> The problem is that the framerate is too low given the simplicity of the rendering job.

Simplicity? You're doing *deferred rendering*.

That's not simple.

You're obviously fillrate-limited (as part of the point of deferred rendering is to be fillrate-limited). And your GeForce GT 120M only has 32 shaders. Which is good for a mobile chip, but pretty poor for serious work.

For every additional light, you're walking the entire screen and doing lighting on every point. Each light will require executing your shader over 2 million times.

If you have a lot of lights (you didn't say how many, which would be useful information to provide), I would suggest packing multiple lighting computations into a single shader invocation. That is, have variations of your shader for 1 light, 5, 10, and 25 if you have that many. This way, if you have 38 lights, you only need to run your full-screen lighting pass 5 times.
> 5 votes

# Answer
High GPU usage is not necessarily a bad thing and not necessarily performance-related. It means that you've got a hardware resource that is actually being *used* to do useful work for you, instead of just sitting there idle. It is perfectly normal to see high GPU usage with a game-loop and in cases where you're not CPU-bound. If that is not what you want then you can limit the framerate by e.g. enabling vsync.
> 0 votes

---
Tags: opengl, performance, glsl, resolution, glut
---


# Question
Title: What is a technique for 2D ray-box intersection that is suitable for old console hardware?
I'm working on a Sega Genesis homebrew game (it has a *7mhz* 68000 CPU). I'm looking for a way to find the intersection between a particle sprite and a background tile. Particles are represented as a point with a movement vector. Background tiles are 8 x 8 pixels, with an (X,Y) position that is always located at a multiple of 8.

So, really, I need to find the intersection point for a ray-box collision; I need to find out where along the edge of the tile the ray/particle hits.

I have these two hard constraints:

1. I'm working with pixel locations (integers). Floating point is too expensive. It doesn't have to be super exact, just close enough.
2. Multiplications, divisions, dot products, et cetera, are incredibly expensive and are to be avoided.

So I'm looking for an efficient algorithm that would fit those constraints. Any ideas? I'm writing it in C, so that would work, but assembly should be good as well.

# Answer
> 0 votes
I used a version of the bresenham line algorithm to project a line into the tilemap. Not the most efficient way, but it's fast enough so far and I only have to do it once per frame.

# Answer
> 0 votes
well if im understanding correctly, what you can do is mod (%) the x and y with the tile size and then check sizes by hand. So if its on the top edge, the X value would be smallest number or if the bottom edge, X would be the largest number, and the same for Y. I hope that answers your question

---
Tags: sprites, projectile-physics, intersection
---


# Question
Title: How do you assign a value of different roles in a game design project?
A friend and I are building a game together and having a great time with it, and we hope to sell the product at some point. The prospects for actual earnings maybe be practically nil (and we aren't getting our expectations up), but regardless, we wanted to get some of the hard "profit splitting" questions out of the way.

Originally, my feeling was that we are both putting a full time effort into the game and would split the profits evenly. I am a programming and his role would be art and music/sound. Game design and concept generation is something we are both doing together. This has become complicated, as we are now looking at "hiring" a few other interested parties and we want to split any profit up fairly. We were looking at perhaps hiring another artist, and perhaps a sound person. We are not sure at this point what level of commitment our hired hands will be willing or able to commit.

So:

Our idea was to make a very large list of all tasks that need to be done across all categories (programming, marketing, art, sound, research, design, etc) and assign weighted values to each task based on the time requirement, difficulty/value of skill set required, and importance to the project.

Then, we can assign tasks to our hired hands and as they complete them, they would earn that percent of any profits that came in. My hope is that my original partner and I would divy up the "remaining" profit (the money our hired hands don't earn) equally when all is said and done. There's still a lot of details to work out, but our feelings were to divy things first into broad categories as follows:
14.81% - Marketing (PR, promotional campaigns, website)
3.70% - Post-release support
18.52% - R&D (programming, tool development, engine development)
7.41% - HR (hiring, dealing with any legal stuff, registering for digital distribution, etc)
18.52% - Art (all graphics and animations in the game)
11.11% - Sound (music + SFX)
18.52% - Game Design
7.41% - Production (timesheet management, organizing meetings and project planning)

(The numbers are weird just because the calculated weights worked out that way)

I'm particularly interested in what others who has walked the same path as us feel. For the record, the game is a spin on the real-time strategic genre with a classic 16-bit look and feel.

1. Is this a sensible approach?
2. Are the numbers weighted reasonably in your mind? (I'm pushing for more value on game design and a little less on sound, myself)
3. How should be deal with changing requirements? We are estimating things as best we can currently, but we're all very new at this process, so there are sure to be areas we've over and underestimated.
4. Any generic advice appreciated!

Thanks everyone!

# Answer
I'm going to suggest the simplest method of all. Take a small cut off the top as founders, 10% between the two of you maybe. Split the remaining 90% equally between anyone who puts in a solid amount of work, including you two in the mix.

Once you start playing games with "your job is only worth 75% of what this other guy did" with a deferred payout on a hobby project you're only asking for bad feelings when what you really need is team spirit.

If you're uncomfortable with that then offer a deferred salary to be taken out of first sales and remove the percentages entirely to make it entirely a business transaction instead of a shared effort.

You're a small team, hobbyists, and all expending effort towards just one game to be sold and not even founding a studio and therefore you need to act like a Volunteer organization and everyone's help is important.
> 4 votes

# Answer
I've personally only experienced working on a project(s) with one other person, but I think I can still offer my two cents.

It seems to me like the only problem with what you're doing is that people will feel like they're being undercut and that you may be 'weighing' the money in your favor. Otherwise, it seems doable, albeit complex.

The classic formula tends to go something like a 40-40-20 split if there's a programmer, artist, and sound designer. Although even this is just the 'general' thing, and by no means a rule of any sort.

So I suppose in summary do whatever the most people on the team want!
> 1 votes

# Answer
I would suggest reduction. Generally break down game development into series of tasks, not abstracted under Marketing or R'n'D umbrella but actually tasks.

For example you already broken HR into: hiring, legal, distribution. You can move further and break following actions: Finding candidates, filtering candidates for interviews, interviewing candidates, handling contracts.

So this example, one person can find and filter candidate for example for programming role, but I guess he won't be interviewing the, existing programmers will interview candidates for programming roles, and existing artists will interview potential artists. This is more accurate way of dealing with tasks I think.

It's somewhat similar to what's some of Agile methodologies use, when features are broken down to functional and non-functional tasks and each assigned points depending on time this task will consume.
> 0 votes

---
Tags: project-management, business-model
---


# Question
Title: Help understanding the order of vector subtraction
I always struggle with intuitively figuring out the order of subtraction in multiple situations for example

The difference between the current mouse coordinates and the last frame's coordinates

The direction an object is to the camera position

etc.

I know that A - B = A + (-B) ..my problem is figuring out which one is A and which one is B ..and those were just simple examples

Is there any hard and fast rules for this? Or is it supposed to be intuitive and obvious (which is what I'm afraid of)?

I have similar problems with figuring out which order to take the cross-product of two vectors too, depending on the scenario

# Answer
Draw it all out on paper. Do it in 1D (ie. a number line), then do it in 2D (ie. a square grid).

Draw point B for the current mouse position, then point A for the previous position. B-A gets you the total change in 1D or 2D or 3D and why is very easy to see on the 1D number line.

Stop calling the points A and B until later, try calling them Now and Then. If you take Now minus Then you get what happened between Now and Then.

As for cross products keep in mind that positive rotation is counter-clockwise. So if you have 2D vectors drawn out on paper with points ABC if you look at it and BA is counter-clockwise to BC then the cross result will be up out of the paper towards your face.

If you hold your right hand out, index straight out, next finger turned left and thumbs up that shows the "right hand rule" for what side is what in 3D and it describes visually what you just drew in 2D.
> 1 votes

# Answer
The cross product is fairly simple. You just use the right hand rule, where your 4 fingers make the notion of going from the first vector to the second and the thumb points in the direction the product vector will be pointing.

As for vector subtracting, let's say you have two points. Then if you subtract point A from point B (it doesn't actually make sense from the stand point of mathematics, but you represent vectors like you do points, where the tail is at the origin and the head is at the given point) then you'll get a vector going from point A to point B. These things are easiest to visualize if you only account for the first quarter of the coordinate system (the x and y axii are positive). Same for vectors, if you have two vectors a and b, then subtracting a from b will result in a vector going from the tip of a to the tip of b.
> 1 votes

# Answer
For vector subtraction, I use the mental image of drawing a bow. If I'm subtracting A - B, I visualize holding up a bow with the arrow point at A, then drawing it back till the tail of the arrow is at B. The arrow is the result of subtraction, a vector pointing from B to A.

For cross products, dreta's and Patrick's answers already described the two most common methods.
> 1 votes

---
Tags: mathematics
---


# Question
Title: Application to record sound effects for games
I'm having kids record sounds using their PCs (a few have Macs as well) for use in the games they create. The built-in windows 7 sound recorder is surprisingly poor, didn't older versions of windows include a sound recorder that could at least play back the sound you recorded or tell you how long it was?

I tried Audacity, but that is pretty confusing for kids. They record a sound, don't like it, then want to record again and it merges those 2 sounds instead... It's also a little confusing trying to simply specify when the sound starts and ends.

Is there some tool game developers use to easily create sound effects from a mic?

# Answer
> 0 votes
Wavesurfer is less daunting and up for the task as described, cross-platform.

Re-recording overwrites the buffer and basic editing is supported.

You must right click on the sound document to create a waveform pane in order to be able to visually select sections of the recorded audio for editing. Otherwise new documents show just a tape transport and mini-waveform overview.

---
Tags: windows, sound, audio, effects, sound-effects
---


# Question
Title: Write alpha channel into SurfaceFormat.Single rendertarget in XNA/HLSL
I need to initialize a rendertarget ('SurfaceFormat.Single' format) drawing sprites into it. I would like the alpha channel of the sprite to be written into the rendertarget, so that regardless of the sprite texture, i end up with sprites silhouettes in the rendertarget. But XNA doesn't support alpha blending when using SurfaceFormat.Single, and from the pixel shader in which i handle the rendertarget for further calculations, i have all 0 readings. I find documentation of this features to be sparse and partial, so, could anyone suggest some source where i can check the sanity of my code?

# Answer
After some experimentation I wasn't able to directly use alpha when writing with spriteBatch to a SurfaceFormat.Single format RenderTarget.

So I had to render

* from **spriteBatch** into **SurfaceFormat.Color rendertarget "A"**
* from **"A"** into **SurfaceFormat.Color rendertarget "B"**, drawing a full.screen quad while using a pixel shader that stores alpha channel into red channel
* from **"B"** into **SurfaceFormat.Single rendertarget "C"**

***There are two problems addressed here:***

1. the application of a pixel shader to a sprite
2. usage of alpha channel in context where alpha is not supported

For first problem, it is not enough to specify an effect while calling spriteBatch.Begin(...), probably because using batch.Draw(...) isn't the same as drawing textured geometry; it is required to **draw sprites to a rendertarget and then use that as a texture** while drawing again to screen, applying the pixel shader, as suggested in Microsoft article http://msdn.microsoft.com/en-us/library/bb313868(v=xnagamestudio.31).aspx *(**outdated** since it's referring to XNA 3.0 way of doing so, but the underlying theory still holds)*

For second problem, **i still suspect there's a better way**, but the only way i managed to use alpha while in context not supporting it was to do **an additional pass before, writing alpha into some other channel** *(ok for me since for that technique i only cared about alpha)*
> 1 votes

---
Tags: xna, hlsl
---


title: How to save a lodu game state

text:
# Question
Title: How to save a lodu game state
I am coding lodu game in c++ and I want to know how to create a save file for my game, so that a user can play, and then come back later. Any idea how this is done

# Answer
I don't know what "lodu" means (although the Urban Dictionary suggest something rather offensive), but here's a relatively vague answer on how is saving done, due to a relatively vague question. Apparently, what you meant is not called "lodu", but "ludo".

First things first, you must figure out what do you want to save, ie, what part of the game state. Common suspects are:

* Object positions (player, enemies, etc)
* Character stats (strength, mana, speed, health)
* Fighting info (is the player in combat?)

What is not to be saved in the save file are things like level info, which should be loaded off separate files that don't need to be changed, or general static info that doesn't change.

To do this in C++, I suggest that you take a look at how filo I/O is done: http://www.cplusplus.com/doc/tutorial/files/.

I suggest that you also use Json: http://jsoncpp.sourceforge.net/.

Once you tell us the actual problems you have, we will be able to provide more concrete answers.
> 2 votes

---
Tags: savegame
---


title: Way to render objects

text:
# Question
Title: Way to render objects
Is it best to have a renderer class in which you have a seperate function for each object you wish to draw? Or is it best to give each object a render function?

```
class Renderer {
    ...
}

Renderer::renderPlayer(Player *player)  {
    ...
}

```

vs

```
class Player  {
    ...
}

Player::render()  {
    ...
}

```

# Answer
The question is a little bit vague and philosophical, im not sure it belongs to this website model, but here goes my opinion.

I would go with the first option, its my favourite way for the following reasons: The drawable object should not be able to know everything about how to draw itself, instead, a global(or not so global) renderer should be used as a dependency for all drawables, to influence how they are drawn.

If a drawable only has geometry data in its raw form, that allows global configurations in the renderer to influence all geometry, instead of changing all one by one. Also it may allow optimizations that would be otherwise impossible, if all geometry and draw code was hidden behind each drawable.

One example that comes to mind would be the ability to batch all geometry that uses a same texture, and have it draw as fast as it possible, with less state changes.

Sorry for the possible incorrectness, my sleepiness is winning , cheers
> 7 votes

# Answer
I would suggest option 2 as well, it keeps the code clean and is a little more maintainable.

However, if you have a lot of different objects implementing own draw commands, keep in mind that a `virtual` function call is more expensive than a simple function call. Consequently, when calling `virtual render()` on like 100K objects per frame, it may get less efficient.

In conclusion: It depends vastly on the number of different objects you want to render. Also, your compiler optimization may solve that problem by replacing the function calls where necessary so that the performance impact is neglectable (is that a valid word?).
> 0 votes

---
Tags: c++, opengl, rendering
---


title: Constructing a ladder

text:
# Question
Title: Constructing a ladder
Let's start with a basic OpenGL ES 2.0 setup (like the Xcode OpenGL game template), If I want to add parts (vertices I should say?) to my model over time, what should I do!

To clarify, let's say I want to add a "step" to a ladder every 5 seconds or every time user taps the view, I initialize with one "step" like an elongated cube and then as things are being rendered on the screen I want to "add" vertices to my data buffer (?),

can I just call:

```
glBufferData(GL_ARRAY_BUFFER, sizeof(gCubeVertexData), gCubeVertexData, GL_STATIC_DRAW);

```

with a brand new gCubeVertexData array of floats on the fly each time?
What is the best approach to this?

# Answer
> 1 votes
Note that that way you would need a buffer for every ladder in your game. And even if you have only one ladder you will have to reset the mesh whenever it you want to display it with less steps. Based on that I think in this case the best wouldn't be to modify the mesh but rather to draw the parts the ladder is consisting of each on their own.

Example:

```
ladderBase.drawScaled(1, ladderLength);
for(int i=0; i++; i<ladderLength)
   ladderStep.drawAtPosition(0, i);

```

However if for any reason you really want to modify the mesh on run time note that you can use glBufferSubData to update only a part of the buffer, as opposed to replace the whole old data with the whole new data.

---
Tags: opengl-es2
---


# Question
Title: Why would selecting a lot of rows crash my game?
I have a databse that contains: `id , playlistname , playlistnum` and I want to get alll the rows where `playlistname = "CoolPlaylist"` and I want to parse them 1 by 1, so I thought of doing this:

```
String name = "CoolPlaylist";
String[] columns = String[] {id , playlistname , playlistnum};
Cursor c = myDatabase.query(TABLE_NAME, columns, key_playlistname +"="+name,
                            null, null, null, null);

```

but when I do this, the code crashes. Does somebody know what the problem probably is?

# Answer
This portion of your code

```
key_playlistname +"="+name

```

probably needs the name part in quotes

i.e.

```
key_playlistname + "= '" + name + "'"

```

Otherwise CoolPlayList probably be treated as an SQL command and would come back with an error such as invalid SQL statement.
> 1 votes

---
Tags: java, android, sql
---