# Question
Title: More Efficient Data Structure for Large Layered Tile Map
It seems like the popular method is to break the map up into regions and load them as needed, my problem is that in my game there are many AI entities other than the player out performing actions in virtually all the regions of the map. Let's just say I have a 5000x5000 map, when I use a 2D array of byte's to render it my game uses around 17 MB of memory, as soon as I change that data structure to a my own defined MapCell class (which only contains a single field: byte terrain) my game's memory consumption rockets up to 400+ MB. I plan on adding layering, so an array of byte's won't cut it and I figure I'd need to add a List of some sort to the MapCell class to provide objects in the layers. I'm only rendering tiles that are on screen, but I need the rest of the map to be represented in memory since it is constantly used in Update.

So my question is, how can I reduce the memory consumption of my map while still maintaining the above requirements? Thank you for your time!

Here's a few snippets my C# code in XNA4:

```
public static void LoadMapData()
    {
        // Test map generations
        int xSize = 5000;
        int ySize = 5000;
        MapCell[,] map = new MapCell[xSize,ySize];
        //byte[,] map = new byte[xSize, ySize];

        Terrain[] terrains = new Terrain[4];
        terrains[0] = grass;
        terrains[1] = dirt;
        terrains[2] = rock;
        terrains[3] = water;

        Random random = new Random();

        for(int x = 0; x < xSize; x++)
        {
            for(int y = 0; y < ySize; y++)
            {
                //map[x,y] = new MapCell(terrains[random.Next(4)]);
                map[x,y] = new MapCell((byte)random.Next(4));
                //map[x, y] = (byte)random.Next(4);
            }
        }

        testMap = new TileMap(map, xSize, ySize);
        // End test map setup

        currentMap = testMap;
    }

public class MapCell
{
    //public TerrainType terrain;
    public byte terrain;

    public MapCell(byte itsTerrain)
    {
        terrain = itsTerrain;
    }

    // the type of terrain this cell is treated as
    /*public Terrain terrain { get; set; }

    public MapCell(Terrain itsTerrain)
    {
        terrain = itsTerrain;
    }*/
}

```

# Answer
> 8 votes
Don't use a class for MapCell.

Classes are allocate on the heap. Every MapCell hence has overhead associate with memory management (bookkeeping of the allocations, padding, etc.). There's also the overhead of all the internal data that every object instance has like the "vtable" handle (which isn't much but it adds up) and you don't need the featurs those provide.

Use a struct. It allows you to store any custom fields you want, has no additional object space overhead, and is allocated in-place in the List's memory buffer so it has no additional memory manager overhead.

Additionally, your code will be a fair bit faster, since iterating over the List will be much quicker as you're no longer suffering indirection overhead and poor cache utilization you get when you allocate 5000x5000 individual objects spread all over memory.

Note that the other suggestions you received to spatially subdivide your world and perform logic level-of-detail filtering are also good, and you should do that in addition to converting MapCell to a struct.

You can also look into using a sparse cell approach with a hierarchy of cells.

# Answer
> 6 votes
That's your problem, right here:

```
map[x,y] = new MapCell((byte)random.Next(4));

```

Each of those calls generates a new object, even if that object is identical to a million others already in the game.

What you can use to alleviate the problem is called the "Flyweight Pattern." In this case, your MapCell instances become immutable (similar to, for example, String instances), so you'll have to store the changeable state - like entities - in some other data structure. Similarly, if you want to define some behaviour in your MapCell instances, only the behaviour which is common to all of them can be defined as its class methods.

An example using a static Factory and a private constructor; this makes your MapCell class essentially `sealed`, aside from hard-coded exceptions.

```
using System.Collections.Generic;

public class MapCell
{
    private static readonly Dictionary<byte, MapCell> terrainCells
        = new Dictionary<byte, MapCell>();

    public static MapCell ForTerrain(byte cellTerrain)
    {
        MapCell result = null;
        if( terrainCells.ContainsKey(cellTerrain) )
        {
            result = terrainCells[cellTerrain];
        }
        else
        {
            // Possibly add a switch-case here
            // for hardcoding special terrain subclasses
            result = new MapCell(cellTerrain);
            terrainCells.Add(cellTerrain, result);
        }
        return result;
    }

    private readonly byte terrain;

    private MapCell(byte itsTerrain)
    {
        terrain = itsTerrain;
    }
}

```

Instead of the call above, you now use ...

```
map[x,y] = MapCell.ForTerrain((byte)random.Next(4));

```

An alternative, which allows for extending the MapCell class with your own and creating new terrain types at runtime (for example from configuration files) would have them register themselves in their constructor. You use them essentially the same way as above, though `MapCell.ForTerrain(...)` can now return `null`, which you have to deal with somehow (assuming that tile is empty, creating a new tile terrain type on the fly and so on).

```
using System.Collections.Generic;

public class MapCell
{
    private static readonly Dictionary<byte, MapCell> terrainCells
        = new Dictionary<byte, MapCell>();

    // Pre-defined MapCell types
    public static readonly MapCell TYPE0 = new MapCell((byte)0);
    public static readonly MapCell TYPE1 = new MapCell((byte)1);
    public static readonly MapCell TYPE2 = new MapCell((byte)2);
    public static readonly MapCell TYPE3 = new MapCell((byte)3);

    public static MapCell ForTerrain(byte cellTerrain)
    {
        MapCell result = null;
        if( terrainCells.ContainsKey(cellTerrain) )
        {
            result = terrainCells[cellTerrain];
        }
        else
        {
            result = null;
        }
        return result;
    }

    private readonly byte terrain;

    protected MapCell(byte itsTerrain)
    {
        terrain = itsTerrain;
        // Register ourselves
        // You should probably throw a RTE
        // if there's already a terrain registered here
        terrainCells.Add(terrain, this);
    }
}

```

(Note: Code untested, aside from looking if Unity throws any fits when compiling it.)

# Answer
> 5 votes
This is a difficult problem because you have a large world which you want to update and have AI running around, regardless of where the player is. Since you need to lower memory while keeping the above true you will have to either raise your memory requirement, or cut some corners. I will explain how to cut those corners.

For simplicity, I assume a 100x100 grid. Assume the player can reasonably see an area of 10x10. Since this area easily fits into memory we will fully simulate this region, which I will call the player region.

Now, for all area outside of the player region will be called non-visible space. Since the player can't see this area, updates don't need to be instant, but as per the requirements, we do need to keep updating this region. Since we can't fit all of it into memory, the usual trick is to break it up into chunks and load what you need. So we break the rest of the 90x90 region into equal sized chunks for convenient loading. These chunks are then rotated into a single (or multiple if you have mutliple threads) buffer. The trick here is to now fully/partially simulate this region up to the current game tick so as to keep the region relevant to changing AI/physics. Once the region is simulated, just write (compress as needed) the region back to disk.

This works great so long as the player doesn't move to those regions. What if he does? A hierarchical approach may be needed. Instead, we want to update non-visible regions close to the player more often than those which are further away. You may have to play with this a bit, but maybe we choose to update a close non-visible region two or three times for every further away non-visible region. This way if the player moves into a previously non-visible region, little extra work is needed to bring that region up to sync.

Keep in mind that AI/effects that happen on a boundary between regions. You may need to save those updates as a "resolve all boundary" update loop. Since you want each region to interact with another you will have to play around with the most appropriate way to propagate effects from one region to another.

You could also watch the player behavior. If they are moving close to an edge region, maybe you will alter now often those other regions get updated to avoid having the player wait while the game simulates up to the current tick.

However, this approach is only necessary because you have a very computationally difficult requirement of a large area that always needs to be updated with potentially complex AI/effects. I would look into how important that requirement is for core-gameplay and reevaluate what a more realistic requirement would be. As this approach opens a lots of cans of worms.

# Answer
> 4 votes
> as soon as I change that data structure to a my own defined MapCell class (which only contains a single field: byte terrain) my game's memory consumption rockets up to 400+ MB.

Objects in managed languages have lots of extra overhead, so when you have very large collections of them, you will notice that overhead.

> I plan on adding layering, so an array of byte's won't cut it and I figure I'd need to add a List of some sort to the MapCell class to provide objects in the layers.

I would argue that the most efficient data structure for your tile rendering would be an array of `byte`, provided that you do not have more than 256 different types of tiles (although these days, an array of `short` or `int` isn't going to kill you either).

You state that you cannot use an array of bytes because you want to implement layering, but I disagree. You could store each layer as a separate array, and simply render them in order.

I would also advise against trying to store your game entities within your tiles. If for some reason your game entities need to know which tile they are standing over, simply keep the tile's coordinates stored in your entity.

You may also want to consider using jagged arrays (`byte[][]`), instead of multidimensional arrays (`byte[,]`). For such a large collection of tiles that you will have to iterate over each frame, the additional performance benefits of using jagged arrays may prove to be worthwhile.

# Answer
> 3 votes
Store the tilemap with byte arrays. If byte is not enough for you, use more byte arrays or short/int arrays. Each object has such a big memory overhead in C# (and Java) that you should use primitive arrays for large sizes. Store the objects in other data structures, not per tile.

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


# Question
Title: Make a lives display in HUD, Flash AS3 (not text!)
I've been searching the internet all day and I can't find the answer I'm looking for.

In my HUD I want to use orange dots to represent lives. The user starts off with 5 lives and every time they die, I want a dot to be removed. Pretty straight forward.

So far my idea is to make a movie clip that has the five dots in a line. There would be 5 frames on the timeline (because after the last life it goes to a game over screen right away).

I would have a variable set up to store the number of lives and a function to keep track of lives. So every hit of an obstacle would result in `livesCounter--;`. Then I would set up something like this:

```
switch(livesCounter){

    case 5: livesDisplay.gotoAndPlay(1);
    break;

    case 4: livesDisplay.gotoAndPlay(2);
    break;

    case 3: livesDisplay.gotoAndPlay(3);
    break;

    case 2: livesDisplay.gotoAndPlay(4);
    break;

    case 1: livesDisplay.gotoAndPlay(5);
    break;
}

```

**I feel like there has to be an easier way to do this** where I could just have a movie clip of a single orange dot that I could replicate across an x value based on the number of lives. Maybe the dots would be stored in an array? When the user loses a life, a dot on the right end of the line is removed.

So in the end the counter would look like this:

```
* * * * *
* * * *
* * *
* *
*      (last life lost results in the end game screen)

```

EDIT: code based on suggestions by Zhafur and Arthur Wolf White

```
package  {
import flash.display.MovieClip;
import flash.events.*;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.Sprite;
import flash.text.*;
import flash.utils.getTimer;

public class CollisionMouse extends MovieClip{

    public var mySprite:Sprite = new Sprite();
    Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
    public var replacement:newSprite = new newSprite;
    public var score:int = 0;
    public var obstScore:int = -50;
    public var targetScore:int = 200;
    public var startTime:uint = 0;
    public var gameTime:uint;
    public var pauseScreen:PauseScreen = new PauseScreen();
    public var hitTarget:Boolean = false;
    public var hitObj:Boolean = false;
    public var currLevel:Number = 1;
    public var heroLives:int  = 5;
    public var life:Sprite;

    public function CollisionMouse() {
        mySprite.graphics.beginFill(0xff0000);
        mySprite.graphics.drawRect(0,0,40,40);
        addChild(mySprite);
        mySprite.x = 200;
        mySprite.y = 200;

        pauseScreen.x = stage.width/2;
        pauseScreen.y = stage.height/2;

        life = new Sprite();
        life.x = 210;

        stage.addEventListener(MouseEvent.MOUSE_MOVE,followMouse);
        /*mySprite.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);*/
        //checkLevel();
        timeCheck();
        trackLives();
    }
    public function timeCheck(){
            addEventListener(Event.ENTER_FRAME, showTime);
    }

    public function showTime(e:Event) {
        gameTime = getTimer()-startTime;
        rm1_mc.timeDisplay.text = clockTime(gameTime);
        rm1_mc.livesDisplay.text = String(heroLives);
    }

    public function clockTime(ms:int) {
        var seconds:int = Math.floor(ms/1000);
        var minutes:int = Math.floor(seconds/60);
        seconds -= minutes*60;
        var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
        return timeString;
    }

    public function trackLives(){

        for(var i:int=0; i<heroLives; i++){
            life.graphics.lineStyle(1, 0xff9900);
            life.graphics.beginFill(0xff9900, 1);
            life.graphics.drawCircle(i*15, 45, 6);
            life.graphics.endFill();
            addChild(life);
        }
    }

    function followMouse(e:MouseEvent){
        mySprite.x=mouseX;
        mySprite.y=mouseY;

        trackCollisions();
    }

    function trackCollisions(){
        if(mySprite.hitTestObject(rm1_mc.obst1) || mySprite.hitTestObject(rm1_mc.obst2)){
            hitObjects();
        }
        else if(mySprite.hitTestObject(rm1_mc.target_mc)){
            hitTarg();
        }
    }

    function hitObjects(){
        addChild(replacement);
        mySprite.x ^= replacement.x;
        replacement.x ^= mySprite.x;
        mySprite.x ^= replacement.x;
        mySprite.y ^= replacement.y;
        replacement.y ^= mySprite.y;
        mySprite.y ^= replacement.y;

    stage.removeEventListener(MouseEvent.MOUSE_MOVE, followMouse);
        removeChild(mySprite);
        hitObj = true;
        checkScore();
    }

    function hitTarg(){
        addChild(replacement);
        mySprite.x ^= replacement.x;
        replacement.x ^= mySprite.x;
        mySprite.x ^= replacement.x;

        mySprite.y ^= replacement.y;
        replacement.y ^= mySprite.y;
        mySprite.y ^= replacement.y;

        stage.removeEventListener(MouseEvent.MOUSE_MOVE, followMouse);
        removeEventListener(Event.ENTER_FRAME, showTime);
        removeChild(mySprite);
        hitTarget = true;
        currLevel++;
        checkScore();
    }

    function checkScore(){
        if(hitObj){
            score += obstScore;
            heroLives--;
            removeChild(life);
        }
        else if(hitTarget){
            score += targetScore;
        }
        rm1_mc.scoreDisplay.text = String(score);
        rm1_mc.livesDisplay.text = String(heroLives);
        trackLives();
    }
}
   }

```

# Answer
> 1 votes
If you want to keep your MovieClip, then you could set the frame with:

```
livesDisplay.gotoAndStop(6-livesCounter);

```

Or you could reverse the frames, thus the first frame would show 5 health, the second would 4 and so on.

Edit:
Then as **Arthur Wulf White** said, you can loop your hp and draw the graphics.Though the following example will use a custom shapes (the ones you have drawn) and not programmatically drawn shapes.
**Example:**

```
var hpContainer:Sprite = new Sprite(); //this will contain the graphics
var newHeart:MovieClip;
for(var i:int = 0;i<HERO.health;i++){
    newHeart = new HeartMovieClip();//The HeartMovieClip is the AS Linkage
                                    //of a movieclip in your library.
    newHeart.x = i*(50);//50 represents the width of your heart graphics, you can
                        //add spacing between them aswell by adding +number at the end
                        //of the equation.
    newHeart.y = 0;//The Y position of every heart will be 0. (So they will be in the
                   //top left corner.
    hpContainer.addChild(newHeart);//add the new heart to the container
}//endfor
...
function refreshHud():void{
    while(hpContainer.numChildren>0) hpContainer.removeChildAt(0); //removes every child
    //places the graphics again.
    for(var i:int = 0;i<HERO.health;i++){
        newHeart = new HeartMovieClip();//The HeartMovieClip is the AS Linkage
                                        //of a movieclip in your library.
        newHeart.x = i*(50);//50 represents the width of your heart graphics, you can
                        //add spacing between them aswell by adding +number at the end
                        //of the equation.
        newHeart.y = 0;//The Y position of every heart will be 0. (So they will be in the
                       //top left corner.
        hpContainer.addChild(newHeart);//add the new heart to the container
    }//endfor
}//endfunction

```

Or another way is to draw all the hearts once, then set the visibility of each one on hud refresh.

# Answer
> 0 votes
You seem to need to read the ActionScript 3 bible. This is not the way to do it. A slightly more reasonable way to do this is:

1. Create a `Shape` instance once.
2. Loop `livesCounter` times.
3. use `Graphics` to `drawCircle` in the correct place ie (i * 20, 10, 5)
4. Now `addChild` the shape.
5. Upon death `removeChild` the shape.
6. Use `Graphics clear` on it.
7. Deduct 1 from the `livesCounter` =\> go to step 2

---
Tags: flash, actionscript-3, hud
---


# Question
Title: What is the correct way to draw layered Sprites in modern OpenGL?
So what do I mean by layered sprites? `Layered Sprites` are Sprites that consist of multiple layers, e.g. you have `sprite sheets` for the basic Body, the Head, Clothes, Weapons, etc.

Well now I wanted to know how you would draw this in the most efficient way; right now the idea is to use `vertex buffer objects` (VBOs), but I heard that it is expensive to change the textures in a VBO...

So what would be the correct way to draw them? My idea right now would be to draw the Map tiles first (with a texture atlas), then I would draw all the basic bodys, then the heads, then clothes, and then the weapons. Would that be the best way or is there a more efficient way?

I also thought of using vertex arrays instead of VBOs, but as far as I know they are deprecated...

# Answer
Pack sprites into large texture atlases, and have a quad (VBO) per sprite (for each individual frame). When you want to draw a certain sprite, you draw the appropriate quad on screen, rather than changing the texture for a quad. Sort the draw calls by layer, and that should be all you need.

And to clarify:

Rather than having, say, `headQuad`, for which you change texture depending on what head and what frame you want, you instead have `monsterHeadQuad1`, `monsterHeadQuad2`, `monsterHeadQuad3`, `heroHeadQuad1`, `heroHeadQuad2`, and so on. The numbers represent the animation frame.

If you have lots of the same sprite on screen, look into **instanced rendering**.

There are plenty of hacks for speeding up the process, but I'd worry more about getting it working than getting it running at 1000+ frames per second.
> 0 votes

# Answer
Probably the most efficient method would be to draw all the sprites using the same texture at once. You can also save some time transferring memory to the GPU by using a geometry shader or instancing that only takes inputs like position, scale, and orientation, and builds the sprite triangles/quads from that.

You can preserve sprite layering by using depth buffering, which is arguably a better method all-around than temporal layering.
> 0 votes

---
Tags: opengl, sprites, vbo
---


# Question
Title: How do I convert DirectX's .X from binary encoding to text encoding and back
As far as I know, .X format can be text encoded and binary-encoded.

I basically want to look into the model I'm playing with, get a better understanding of .X, possibly make some changes in it and convert back.

# Answer
> 3 votes
Well, apart from other's suggestion to use a modeling package that can read/write both formats (polytrans can do it but ain't free), your original post links to both formats so if all else fails you got everything needed to be able to read and write both formats....

# Answer
> 3 votes
There is a mesh convert tool in my directory of DXSDK. I can convert **.x** format from binary to text and text to binary (among other things).

> C:\Program Files\DXSDK\Utilities\bin\x86\>MeshConvert.exe

# Answer
> 2 votes
When the model was exported from the 3d modeling app, whoever exported it chose binary instead of ascii.

One way to convert it would be to import the model into any 3d modeling app that supports .x (there are free ones out there) & re-export in ascii format.

# Answer
> 2 votes
If it's so straight forward, why can't you solve it? No need to be rude.

Anyway, the first hit on Google is the spec that tells you exactly how you can perform the conversion: http://msdn.microsoft.com/en-us/library/bb173014%28VS.85%29.aspx

Alternatively, a Google for tools that will do this brings up plenty of hits.

Straight-forward indeed.

# Answer
> 2 votes
If your goal is to get a better understanding of the X file format, it might be worthwhile to write a converter yourself. All of the information you would need to do this is on the MSDN link that Rushyo provided: http://msdn.microsoft.com/en-us/library/bb173014%28VS.85%29.aspx.

---
Tags: directx, directx9
---


title: Event/Trigger System Architecture

text:
# Question
Title: Event/Trigger System Architecture
**The Plan**
I am up to write write an own Trigger/Event System, an event engine or how you call it. I would like to achive something similar to Blizzard's most level editors, like Starcraft 1-2, Warcraft level editors.
They are all kind of event/trigger based, you can set actions, conditions which actually control the gameplay itself. What do you think, what would be the best architecture for this event/trigger system?
**The Architecture**
I thought it would look something like this:

* EventManager - would handle the events, checking if the conditions meet for any event, and calls the event if so.
* EventHolder - would hold the list of the events.
* EventEntity - would have an ID, the actions' ID and the params for them.

Every entity, enemies, player and other stuff would have an ID in the world, which would help to get the entity itself and fire a trigger on it.
Obviously, there would be finit and pre-set BASIC actions, but that would be stored by the current project itself. The project could pass the `EventSet` (list of `EventEntity`) to the `EventHolder`. Thus this whole event/trigger system would be very flexible, and could compile it as a DLL for use in future projects.
Do you have any better solution for this? Or some pro tips that I could use? Would really appreciate any help! Thanks!

**Edit:**
This picture shows it quite well:
**Edit2:**
I have wrote a raw architecture of a possible "engine", but it is missing some MAIN points:

```
{Initializing}

//in order
[Game]--set event list--[EventManager]--requests list of EventEntity--[Game]--sends list of EventEntity--[EventManager]

{EventManager loop}

[EventManager]--checks if any of the events meet in an EventEntity
[EventManager]--if any meets--[EventManager]--checks if all of the conditions are meeting in the EventEntity
[EventManager]--if all meets--[EventManager]--fires actions of the EventEntity

{Architecture of the Models}

[EventEntity] contains
- [List of Event Models]
- [List of Condition Models]
- [List of Action Models]

[EventModel] contains
//quite similar to the ConditionModel, an event only should fire, aka check the conditions and
//fire the actions, if these special conditions, happenings, events are fired
//like a unit dies, player reaches a specific position, etc.

[ConditionModel] contains
//model must simulate AND, OR logic statements
//model must simulate IF statements

[ActionModel] contains
- [List of Targets]
- [List of Action IDs] //One action per Target, a specific Target can be listed more than once in the [List of Targets]
//something is missing

```

Trying to write the "system" as standalone as possible, it must not depend on any project's source. Thus I think the best would be to seperate the data from the architecture, could store the event, condition and action datas in another DLL unit, and could read from that.

# Answer
> 3 votes
A trigger-event system is pretty fool-proof (as illustrated here). Trigger an event, and all objects listening to that event will react. It can get quite cumbersome though, managing event types, especially when you have similar events, but different targets. The alternative I'm proposing is *a messaging solution* similar to your example, with a few key differences:

```
Event {
    List ids;
    Action action;
    List args;
}

```

The ids represent all the entities that should *receive* the event (eg. player1, goblin3, world, HUD). The action would be an action from a preset list of possibilities (eg. damage\_player, heal\_goblin, reset\_level). The args would be any list of arguments relating to the action (so for a heal action, it might be a number representing the amount).

Next, you have your EventManager:

```
EventManager {
    Queue events;
    Dictionary listeners;

    addEvent(Event event);
    delegateEvents();

    addListener(String id, Listener listener);
}

```

The event manager holds two types of items: events, and listeners. Whenever an event occurs, it gets passed to the event manager (`addEvent()`). The event gets added to the queue of events. Then, at some point, (such as during the next update loop), you call `delegateEvents()`, which sends the list of events to the approproate **listeners**. Let's define a listener before moving on:

```
Listener {
    Queue events;
}

```

Every game object/entity, that is capable of receiving events, will have a listener attached to it. The EventManager will store a reference to this listener (added via the `addListener()` function), and will delegate events to these listeners, as illustrated above.

Once the events have been passed on to the listeners, the game objects/entities themselves will go through the events passed through to their listeners. The way in which they interpret the events will be specified for the game object itself. So if a **heal** (action) event is passed to the **player** (id), with an argument of **418** (arg), the player will update its own health with 418 additional hp. The player would then send an event to the renderer, and sound engine, that a *heal* of type *foo* was initialized at location *bar*, and they would then initialize the appropriate animation and sound.

Just to illustrate the difference between using triggers vs. messages, again using the healing example:

The first iteration of your game doesn't have a healing animation. You heal, it only updates a stat. Then, you want to polish it up, add some visual flare; with a trigger-event system, you need to register the renderer as a listener to the **player heal** event. In comparison, with the messaging solution, you need to tell the player to send a **heal** event to the renderer.

Two ways to achieve the same thing. I'd advocate the messaging solution, but that's mostly just personal preference.

# Answer
> 2 votes
To be honest, your system sounds like it will work just fine. There isn't going to be any *best* way to make something like this, but whatever works better for your tools and editor.

One suggestion I might make however is to use some sort of map, using either a string for the key or perhaps a hashmap. That way, a script or plugin could more easily extend the available events/triggers than having to compile a new DLL each time.

# Answer
> 2 votes
There might be a heavy lifting work on the hands of the EventManager if every frame god knows how many parameters must be accessed and checked, this is a passive solution.

I recommend using an active solution, a bit dirtier and harder to maintain but much more efficient potentially. Where each parts of the engine and game where parameters are subject to be watched, could trigger an event by calling a signal on the mutator method. This means, that you need boost::signals or libsignals, or C# with multicast events plugged to delegates.

This also allows dependency inversion and high decoupling, which is desirable. It is even better than classic DIP using interfaces. Philosophically there is not much difference between using a virtual call and a signal system though, the design is different, less contract therefore less clear big picture (harder for maintenance), but better decoupling, more flexibility.

Anyway, this is a low level cosnideration, but still, don't go too much by the rule "early optimize is root of all evil", I abhor this phrase, its just plain wrong and make people end up into UniformlySlowCode faster than lighting. Think well on the design phase so that impossible refactoring doesn't have to ensue later.

Then, using a true ECS (Entity Component System) will help the signal/slot design because of easier control of property mutation, so if you have an ECS you must have paved your way for smoothness.

In a classical hierarichal design, it still can be possible to get ECS-equivalent behavior if using a reflection system right from the start. Where mutators/accessors are generalized through a common interface, and access to members is made via global indices. This can be a serious overload, specially when sometimes the get/set is not trivial (big switch and each member has its way of being set/get...) but some engines DO work like that.

You may use JSON or something equivalent to describe your triggers and the list of parameters they convey. Then a visual scripting GUI can be presented to the designers so that events may show up as boxes on a graph, with sockets on the right side that can be plugged to entities (represented as boxes as well) using arrows, this will represent the signal to slot connection in terms of code. and one signal can be plugged to multiple slots. Then you can have computing nodes, like if you want the position of a hit event to get through a math function so that you can use a random seed for a spark emitter, or a timer to delay an event, then the nodes re-outputs the modified event to any plugged entity.

This description is obviously just saved as an event file for the data driven event engine, which can be isolated in a dll where features like event-file parsing can be done, and the whole event-file data model in memory can be stored, but necesarily, there will be procedures to code in upper libraries to connect their signals, which cannot be done by a DLL since bi-directional dependencies cannot exist. beware of your dependencies.

hope that helps getting a perspective

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


# Question
Title: Draw character silhouette when not visible
I have a mesh representing my character. I want to give it a partially transparent greyish silhouette when other objects are blocking it from view of the camera.

I'm using Ogre3D, and GLSL as a shading language, but this is a pretty technology/language agnostic question.

# Answer
Draw everything apart from your character. Switch to front face culling, turn depth testing off, and render your character in a transparent grey colour. Then return to back face culling, turn depth testing back on, and render your character normally.

The grey outline always gets drawn, but if the character is visible/not blocked, it'll get drawn on top of the grey outline, hiding it.
> 1 votes

---
Tags: 3d, shaders, camera, ogre
---


# Question
Title: Is Batching Geometry Every Frame Always Slower Than Individual Draw Calls
I'm currently have an application that has ~10k draw calls. I implemented a batching scheme where I group all objects that share material, vertex format, etc and pre-transform them by their world matrices and put all those objects in one vertex buffer / index buffer, and then draw them with `DrawIndexedPrimitive` (I do this every frame, since some objects might have moved / changed material etc). However, this method is always slower than if I just had multiple draw calls. Using VTune, it seems most of my time is spent computing the transformed vertices and copying the vertex/index data into the buffers.

My question is: Is this expected? Do systems that perform batching typically cache the batched data or are there some that get away with batching every frame like I am attempting to do (and if so, are there any tips for what I might be doing poorly)?

My application is in DirectX 9, but I'm curious about solutions in other platforms as well (OpenGL or DirectX 11).

# Answer
Batching will often lead to a performance gain, but this is only if you had a bottleneck being created by the multitude of draw calls being made to begin with.

In this particular case you may have simply introduced a new bottleneck.

I think it's likely that the CPU is now having to work overtime to transform and batch all that data. Keep in mind that all those vertices are being transformed individually on the CPU now, instead of on the GPU in the vertex shader (assuming your using shaders ofcourse). Also, you may find that your code is doing a lot of rearranging of memory at the same time.

You also have to keep in mind that when you are using a dynamic vertex buffer, the new buffer has to be copied to the GPU constantly for it to be used. In the case of a static buffer, because you have promised never to change anything, the graphics card will, where possible, keep a cached copy so that the data doesn't need to be transferred over the bus. So in this case, you may actually find that you have a databus bottleneck.

In general batch where you can, but you want to keep the updating of dynamic vertex buffers to a minimum. In this case you might find that the easiest way to get a slight performance boost is to batch all the static objects and forget about anything with a changing world matrix. That will remove those updates and you can batch all that data into a static vertex buffer.
> 2 votes

# Answer
Batching the way you're thinking about it is usually only used for static objects. In other words, everything that doesn't move and shares a material, transformation, etc. gets grouped up into a common buffer. That way, you don't have to update your vertex buffers every frame.

It seems like you had the right idea for grouping things based on material, vertex format, etc. This produces an optimization by reducing the number of *state changes*, so that you don't have to keep sending data to different parts of GPU memory.

In other words, it's good to change loops that look like:

```
for(GameObject obj : objects) {
  setMaterial(obj.material);
  draw(obj);
}

```

to

```
for(Material mat : materials) {
  setMaterial(mat);
  for(GameObject obj : mat.objects) {
    draw(obj);
  }
}

```

As far as I know, most game engines don't do dynamic batching the way you've described it because of the problems you're running into. The rule of thumb is to make sure that everything is grouped so that you have as little actual processing (generating vertex buffers, loading textures, etc) during your render loop as possible, and to do this you can usually get away with having one or two state changes to switch a material or have a few extra draw calls.
> 1 votes

---
Tags: opengl, directx, performance, directx9
---


# Question
Title: A few questions about integrating AudioKinetic Wwise and Unity
I'm new to Wwise and to using it with Unity, and though I have gotten the integration to work, I'm still dealing with some loose ends and have a few questions: (I'm on Unity 4.3 as of now but I think it shouldn't make any difference)

1. **The base path:** The Wwise documentation implies you set this in the `AkGlobalSoundEngineInitializer` `basePath` public ivar, which is exposed to the editor. However, I found that this variable is not really used. Instead, the path is hardcoded to `/Audio/GeneratedSoundBanks` in `AkBankPath`. I had to modify both scripts to actually look in the path that I set in the editor property. What's the deal with this? Just sloppyness or am I missing something?
2. **Also about paths:** since I'm on Mac, I'm using Unity natively under OS X and in tadem, the Wwise authoring tool via VMWare and I share the OS X Unity project folder so I can generate the soundbanks into the assets folder. However, the authoring tool (downloaded the latest one for Windows) doesn't automatically generate any "platform-specific" subfolders for my wwise files. That is, again, the Unity integration scripts assume the path to be `/Audio/GeneratedSoundBanks/<my-platform>/` which in my case would be Mac (I set the authoring tool to generate for Mac). The documentation says wwise will automatically generate the platform-specific folders but it just dumps all the stuff in `GeneratedSoundBanks`. Am I missing some setting? cause right now I just manually create the `/Mac` folder.
3. **The C# methods `AkSoundEngine.PostEvent` and `AkSoundEngine.LoadBank`** for instance, have a few overloads, including ones where I can refer to the soundbanks or events by their ID. However, if I try to use these, for instance:

AkSoundEngine.LoadBank(, AkSoundEngine.AK\_DEFAULT\_POOL\_ID)

where the int I got from the .h header, I get `Ak_Fail`. If I use the overloads that reference the objects by string name then it works. What gives?
4. **Converting the ID header to C#:** The integration comes with a C# script that seems to fork a process to call Python in turn to covert the C++ header into a C# script. This always fails unless I manually execute the Python script myself from outside Unity. Might be a permissions thing, but has anyone experienced this?
5. **The Profiler:** I set up the Unity player to run in the background and am using the "Profile" version of the plugin. However, when I start the Unity OS X standalone app, the profiler in VMWare does not see it. This I'm thinking might just be that I'm trying to see a running instance of the sound engine inside an OS X binary from a Windows virtual machine. But I'm just wondering if anyone has gotten the Windows profiler to see an OS X Unity binary.
6. **Different versions of the integration plugin:** It's not clear to me from the documentation whether I have to manually (or write a script to do it) remove the "Profile" version and install the "Release" version when I'm going to do a Release build or if I should install both version in Unity and it'll select the right one.

Thanks!

# Answer
So I just ran into this issue myself and it seems that all that's missing is setting up your Environment Variables to recognize the python path so that python can be run from anywhere.

In case you or anyone else reading this doesn't know how to modify environment variables here's a step by step.

1. Click your start button
2. Right Click "Computer"
3. Choose "Properties"
4. On the left, click "Advanced system settings"
5. Under the Advanced tab click "Environment Variables"
6. In the "System variables" box, find and select the "Path" variable and click "Edit..."

This variable should already contain several paths used by your system, don't touch those. 7. At the end of the list of paths add your python install path preceded by a ; (the delimiter between paths) 8. Hit Ok and try to run the Wwise menu option inside of Unity, should work fine now.

I hope this helped you and anyone else setting this up. Good luck!
> 1 votes

---
Tags: unity
---


# Question
Title: Problem with Texture Array and billboards
It's my first post here. My name is Bruno and I'm from Brazil. I'm trying to learn DirectX 11, and I'm using Frank Luna's book. The problem is that he uses the Effects Framework to do everything, and I have to port everything I learn. But now, I'm stuck at the Billboard Lesson (Geometry Shader).

Aparently, it seems to be a problem with the texture, but I tried changing everything, but still couldn't find what was wrong in code. I hope someone may help me on this. The billboards are drawn as full black quads, as if there was no texture, or if it was all black.

Here's the image:

Here's how it should be:

The HLSL codes are intact, I didn't do anything, except numbering the resources (register b0, t0, s0, etc). Here are 2 parts of my code, that I think may be broken.

```
void TreeBillboard::CreateTextureArray()
{
vector<ComPtr<ID3D11Texture2D>> textures(4);

HR(CreateDDSTextureFromFile(m_pDevice.Get(), L"../Direct3D11-Study/Textures/tree0.dds", reinterpret_cast<ID3D11Resource**>(textures[0].ReleaseAndGetAddressOf()), nullptr));
HR(CreateDDSTextureFromFile(m_pDevice.Get(), L"../Direct3D11-Study/Textures/tree1.dds", reinterpret_cast<ID3D11Resource**>(textures[1].ReleaseAndGetAddressOf()), nullptr));
HR(CreateDDSTextureFromFile(m_pDevice.Get(), L"../Direct3D11-Study/Textures/tree2.dds", reinterpret_cast<ID3D11Resource**>(textures[2].ReleaseAndGetAddressOf()), nullptr));
HR(CreateDDSTextureFromFile(m_pDevice.Get(), L"../Direct3D11-Study/Textures/tree3.dds", reinterpret_cast<ID3D11Resource**>(textures[3].ReleaseAndGetAddressOf()), nullptr));

//
// Create the texture array.  Each element in the texture
// array has the same format/dimensions.
//

D3D11_TEXTURE2D_DESC texElementDesc;
textures[0]->GetDesc(&texElementDesc);

D3D11_TEXTURE2D_DESC texArrayDesc;
texArrayDesc.Width              = texElementDesc.Width;
texArrayDesc.Height             = texElementDesc.Height;
texArrayDesc.MipLevels          = texElementDesc.MipLevels;
texArrayDesc.ArraySize          = textures.size();
texArrayDesc.Format             = texElementDesc.Format;
texArrayDesc.SampleDesc.Count   = 1;
texArrayDesc.SampleDesc.Quality = 0;
texArrayDesc.Usage              = D3D11_USAGE_DEFAULT;
texArrayDesc.BindFlags          = D3D11_BIND_SHADER_RESOURCE;
texArrayDesc.CPUAccessFlags     = 0;
texArrayDesc.MiscFlags          = 0;

ID3D11Texture2D* texArray = 0;
HR(m_pDevice->CreateTexture2D( &texArrayDesc, 0, &texArray));

//
// Copy individual texture elements into texture array.
//

// for each texture element...
for(UINT texElement = 0; texElement < textures.size(); ++texElement)
{
// for each mipmap level...
for(UINT mipLevel = 0; mipLevel < texElementDesc.MipLevels; ++mipLevel)
{
            const uint32_t subResourceIndex = D3D11CalcSubresource(mipLevel, 0, texElementDesc.MipLevels);
            const uint32_t destinationSubresource = D3D11CalcSubresource(mipLevel, texElement, texElementDesc.MipLevels);
            m_pContext->CopySubresourceRegion(texArray, static_cast<UINT> (destinationSubresource), 0, 0, 0, textures[texElement].Get(), subResourceIndex, nullptr);
}
}

//
// Create a resource view to the texture array.
//

D3D11_SHADER_RESOURCE_VIEW_DESC viewDesc;
viewDesc.Format = texArrayDesc.Format;
viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2DARRAY;
viewDesc.Texture2DArray.MostDetailedMip = 0;
viewDesc.Texture2DArray.MipLevels = texArrayDesc.MipLevels;
viewDesc.Texture2DArray.FirstArraySlice = 0;
viewDesc.Texture2DArray.ArraySize = textures.size();

HR(m_pDevice->CreateShaderResourceView(texArray, &viewDesc, m_pTexArraySRV.ReleaseAndGetAddressOf()));

//
// Cleanup--we only need the resource view.
//
for (UINT i = 0; i < textures.size(); i++)
{
textures[i].Reset();
}
};

```

And the Draw Tree Sprites function:

```
void TreeBillboard::DrawTreeSprites()
{
m_pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_POINTLIST);
m_pContext->IASetInputLayout(m_pInputLayoutTree.Get());

m_pContext->VSSetShader(m_pVSTree.Get(), nullptr, 0);
m_pContext->GSSetShader(m_pGSTree.Get(), nullptr, 0);
m_pContext->PSSetShader(m_pPSTree.Get(), nullptr, 0);

m_pContext->PSSetSamplers(0, 1, m_pSamLinear.GetAddressOf());

ID3D11Buffer* buffers[3] = { m_pCBPerObjectTree.Get(), m_pCBPerFrame.Get(), m_pCBPerOption.Get() };

//m_pContext->VSSetConstantBuffers(0, 3, buffers);
m_pContext->GSSetConstantBuffers(0, 2, buffers);
m_pContext->PSSetConstantBuffers(0, 3, buffers);

XMStoreFloat4x4(&m_cbPerObjectTree.m_mViewProj, XMMatrixTranspose(XMLoadFloat4x4(&m_view) * XMLoadFloat4x4(&m_proj)));
m_cbPerObjectTree.m_material = m_treeMat;

D3D11_MAPPED_SUBRESOURCE mappedResource;
HR(m_pContext->Map(m_pCBPerObjectTree.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));
CopyMemory(mappedResource.pData, reinterpret_cast<void*>(&m_cbPerObjectTree), sizeof(CBPerObjectTree));
m_pContext->Unmap(m_pCBPerObjectTree.Get(), 0);

UINT vertexSize = sizeof(TreeVertex);
    UINT offset = 0;
m_pContext->IASetVertexBuffers(0, 1, m_pTreeVB.GetAddressOf(), &vertexSize, &offset);

float blendFactor[4] = {0.0f, 0.0f, 0.0f, 0.0f};

//if(mAlphaToCoverageOn)
//{
m_pContext->OMSetBlendState(m_pAlphaToCoverageBS.Get(), blendFactor, 0xffffffff);
//}

//m_pContext->GSSetShaderResources(0, 1, m_pTexArraySRV.GetAddressOf());
m_pContext->PSSetShaderResources(0, 1, m_pTexArraySRV.GetAddressOf());
m_pContext->Draw(16, 0);

m_pContext->GSSetShader(nullptr, nullptr, 0);
m_pContext->OMSetBlendState(nullptr, blendFactor, 0xffffffff);
};

```

Hope someone can help. Thanks in advance.

PS: Let me know if you guys need any other part of the code. Also, I created this same topic in Gamedev forums -\> http://www.gamedev.net/topic/653037-problem-with-billboarding-geometry-shader-and-texture-array/

# Answer
A guy nicknamed "unbird" at Gamedev.net found the problem. Here's the link to the solution.

"There's also a constant buffer for the tex-coords (cbFixed), filled with default values. These only work with the effect framework, so you have to fill it manually and set it to the correct slot, just like the other constant buffers. For this particular case I for one wouldn't even use a constant buffer but declare this array as a static (which then gets hardwired in the shader)"

http://www.gamedev.net/topic/653037-problem-with-billboarding-geometry-shader-and-texture-array/

Thank you everyone for your time, János, unbird.
> 1 votes

---
Tags: textures, directx11, geometry-shader
---


# Question
Title: How can I clear the entire display in Corona?
How can I clear the entire display? I have tried doing `display.remove(obj)` and `obj:removeSelf()` on everything that was drawn, but it seems to miss a few things and I am unsure why.

A very basic version of this part would look like this:

```
Runtime:addEventListener("accelerometer", onShake)
Runtime:addEventListener( "touch", draw );

--Initialize arrScreen and other variables

function onShake (event)
  if event.isShake then
    --for loops
      display.remove(arrScreen[i][j])
      --arrScreen[i][j]:removeSelf()
    --end for loops
  end
end

function draw(event)
  if event.phase == "began" then
    arrScreen[event.x][event.y]=display.newRect(event.x,event.y,size,size)
    lastPoint.x=event.x
    lastPoint.y=event.y
  elseif event.phase ~= "ended" then
    arrScreen[event.x][event.y]=display.newLine(event.x,event.y,lastPoint.x,lastPoint.y)
    lastPoint.x=event.x
    lastPoint.y=event.y
  end
end

```

# Answer
> 4 votes
With Corona SDK, you normally group things such as sprites.

```
myGroup = display.newGroup() -- create a new group
myGroup:insert(sprite1) -- insert sprite1 in it
myGroup:insert(sprite2) -- insert sprite2 in it
myGroup:removeSelf() -- remove everything in this group
myGroup = nil -- nil the group's reference

```

# Answer
> 0 votes
To clear the entire screen, you have to remove all display objects you have created. I would recommend creating a table and inserting all objects into it.

```
objectsOnScreen = {}
-- Everytime you create a new display object, add it to the table
local newObject = display.newImage("foo.png")
table.insert(objectsOnScreen, newObject)

```

Then when you want to remove all objects from screen:

```
local function removeAllScreenObjects()
  for i=1, #objectsOnScreen do
    objectsOnScreen[i]:removeSelf()
    -- Can also use: objectsOnScreen[i].isVisible = false
    objectsOnScreen[i] = nil
  end
end

```

Another option is to create a rectangle the size of the screen and drawing it on top of everything.

Hope this helps.

---
Tags: corona-sdk
---


# Question
Title: Collision detection - make sure the player touches the object exactly
I know this is really something I should be able to figure out on my own, but a solution is evading me.

Okay, here are a few relevant parts of my code.

```
bool Game::Col(int x1,int y1,int w1,int h1, int x2, int y2,int w2,int h2)
{
    if(x1 > x2 + w2 || y1 > y2 + h2 || x2 > x1 + w1 || y2 > y1 + h1)
    {
        return false;
    }
    return true;
}

```

That's my collision detecting algorithm. Simple, for rectangles only.

```
        int bX = (player.getX() - 64) / 32;
        int bY = (player.getY() - 64) / 32;
        int tX = (player.getX() + 64) / 32;
        int tY = (player.getY() + 64) / 32;

        for(int a=bX;a<tX;a++)
        {
            for(int b=bY;b<tY;b++)
            {
                if(Col(player.getX(), player.getY(), 32, 32, a * 32, b * 32, 32, 32) && blocks[a][b] == 1)
                {
                    player.setX(oldX);
                    player.setY(oldY);
                    goto loopExit;
                }
            }
        }

        loopExit:

```

Here is my collision detection. This is performed right after the player x/y is manipulated(5 pixels in whatever direction every 1/60th of a second). Blocks is just a 2d array for my tile map. I know the way I have collision detection right now is not too optimized, but it took a few seconds to implement and is reasonably fast.

But the player can only get within 5 pixels of an object now. How do I solve that?

# Answer
> 2 votes
What you need to do is create a method that gets the amount that the player overlaps the tile by. You would make a copy of this method for each axis. When you are moving the player, you first move the player on the X axis. Then you check for collision. If you find a colliding tile, you get the player's offset into the tile and subtract that from the player's X axis (note that you will have to account for the direction the player is moving).

After you have moved the player on the X axis, you repeat the process on the Y axis, getting the colliding tile and offsetting the player. There is a reason why we have to move on each axis independently. If we didn't do this, you wouldn't be able to tell which movement caused the collision. In other words, did the fact that we are falling cause the collision, meaning that we have to get the Y offset? Or was it because we are moving to the right?

With this knowledge in mind, our collision code should look something like this:

```
void movePlayer()
{
    int left = // get the left-most tile to check for collision
    int right = // get the right-most tile to check for collision
    int top = // get the top-most tile to check for collision
    int bottom = // get the bottom-most tile to check for collision

    for(int xt = left; xt < right; xt++)
    {
        for(int yt = top; yt < bottom; yt++)
        {
            Tile t = world.getTile(xt, yt);
            if(aabb.collidesWith(t.getBox())
            {
                xPos -= t.getBox().getOffsetX(aabb, /* Here you may also pass in the movement direction to determine wether you should pass
                                                    a positive or negative number, to ensure you move the player in the right direction. */);
            }
        }
    }

    aabb.updateBox(); // Because we moved the character. You may also want to update the left and right variables

    for(int xt = left; xt < right; xt++)
    {
        for(int yt = top; yt < bottom; yt++)
        {
            Tile t = world.getTile(xt, yt);
            if(aabb.collidesWith(t.getBox())
            {
                yPos -= t.getBox().getOffsetY(aabb, /* Again, pass the movement direction. I usually represent
                                                    this with a positive or negative integer. */);
            }
        }
    }

    aabb.updateBox();
}

```

You will obviously have to adapt this code to fit your program, but this should help you.

# Answer
> 1 votes
If you are moving at 5 pixel increments, this will 'lock' the player to certain distances from the blocks. You have to build code to allow the player to move the remaining distance at smaller increments e.g. 1 pixel, to get into contact with the block.

---
Tags: c++, collision-detection, collision-resolution, allegro
---


# Question
Title: How to manage screen and input when using libSDL2 for both desktop and Android?
I have worked on libSDL1.2. Since, the release of 2.0, SDL also supports android. So, I am trying to develop game that can work both on desktop and android. But there are few things that are confusing me.

1. When we are creating a window, we pass the width and height of screen. But on android game covers whole screen and different devices have different resolutions. So how can we create a screen which appears uniform on both desktop and android.
2. How to handle inputs like back button.
3. Also, how to load graphics based on DPI.

# Answer
> 1 votes
It might be easier to deliberately develop two slightly differing versions of your game; one for PC and Android each. You could develop them in parallel git branches, for example.

---

However, if you want to take the full-on responsive resolution-independent user interface route:

It's been a while since I did SDL, but it has something to the tune of `SDL_GetDisplayMode` for finding the native screen resolution. Based on that, you could guess whether the game is running on Android or a desktop and hide / change UI elements or controls appropriately.

Such a comparison is only guess, of course, as you can't cover all possible screen resolutions. If you're really going to run the same code on both platforms, it might be best to add a user-configurable "phone / PC mode" option so nobody is accidentally stuck with the wrong UI.

---
Tags: android, sdl, pc
---


title: Can I jump from A to B?

text:
# Question
Title: Can I jump from A to B?
I'm making some rudimentary AI for my side-scroller and I need to know whether an AI unit can reach point B from point A simply by taking a jump.

Flight trajectory of my characters is a bit unusal as they can apply force in mid-air (like in Jazz Jackrabbit 2 for example), so unlike the classic trajectory of a projectile which is about...

> path that a thrown or launched projectile will take (...) without propulsion.

... I suppose that my problem is more about a projectile **with propulsion** (e.g. rocket).

To illustrate this, this is how the flight curve looks like for my character if I jump and continually press the "left button" (it looks different at the left end, this is where I was making some manuevers in mid-air):

The force applied during flight is always parallel to the X axis, so it is *F = (-f, 0)* if I hold "left" and it is *F = (f, 0)* if I hold "right".

He can move very much like a ski jumper:

So it differs a lot from the classic trajectory which is simply a parabola (source: wikipedia):

To make it more difficult, I am simulating simple air resistance so my characters can accelerate only up to some maximum speed value.

This is done by applying a small force in the opposite direction of travel:

```
b2Vec2 vel = body->GetLinearVelocity();
float speed = vel.Normalize(); //normalizes vector and returns length
body->ApplyForce( AIR_RESISTANCE_MULT * speed * speed * -vel, body->GetWorldCenter() );

```

The AIR\_RESISTANCE\_MULT is a constant that in my case equals 0.1.

Let's assume that my character is an infinitely small point.

And I'm **NOT** taking obstructions into consideration, so my question goes like this...

**How to determine (at least reliably guess), given initial velocity V, an impulse *J = (0, -j)* that I apply to the character upon jump, gravity *G = (0, g)*, force *F = (+-f, 0)* continually applied during flight and AIR\_RESISTANCE\_MULT if we really decide to take air resistance into account** *(this is optional)* **, whether a point lies below the curve drawn by the path my character will take?**

I have literally no idea where to start with the calculations and in fact, I am not necessarily interested in an exact answer; a well working hack/approximation would be great as the AI by no means needs to act perfectly.

**edit:** I've decided to solve this using simulation as Jason suggests, but how to handle such a case?

Should I draw a segment from **C** to **D** and check whether the desired point lies below this segment?

Or should I binary search the timesteps between **C** and **D** to look for the point that is close enough in horizontal distance to the desired point, and only then check the vertical difference? (seems a bit overkill to me)

# Answer
As you state, the best choice is to approximate, in this case using a numerical scheme. Divide time into large timesteps (say 100-300ms), and use the parabolic approximation for each timestep. The forces are the same throughout except air resistance. The parabolic path is basically for constant acceleration, but with air resistance the acceleration changes because the force depends on speed. A reasonable approximation is to treat air resistance as constant over each timestep. But using a quadratic (i.e. parabolic) approximation when integrating allows you to handle much larger timesteps. Then you just compute until a parabola crosses the desired point in the horizontal direction, and then compare the heights.

**EDIT:** A little more detail about the comparison. You know that over the timestep (which could be many in game frames), that the player crosses the target `<targetx,targety>`. Their path is described by the position `<ax*t^2 + bx*t + cx, ay*t^2 + by*t + cy>` where:

```
ax = 1/2 * accel.x
bx = velocity.x
cx = position.x

```

`t` is the time through the timestep (`0 <= t <= dt`) and similarly for `y`. So when `t=0` the character is at the previous position, and when `t=dt`, they are at the next position. Note that this is basically the Euler update with `dt` replaced by `t` so that we can calculate anywhere along the trajectory. Now we know the x-position is a quadratic function, so we can solve `ax*t^2 + bx*t + cx = targetx` and get (up to) two times during the step in which the character is directly above or below the target. Then we throw out any solutions that aren't in the range \[0, `dt`\], as these aren't in the current timestep. (For robustness, add a small constant to the ends of the range so you don't have round off problems). Now we could have no solutions (after filtering), in which case we don't hit the target this timestep. Otherwise, we evaluate `ay*t^2 + by*t + cy` at the solutions, and compare this y with `targety`. Note that you could be above the target at one point in your trajectory, and below it later (or vice-versa). You'll need to interpret such situations according to what you want to do.

Considering a bunch of timesteps is much easier than finding an analytic solution to the original problem, and far more flexible as you can change the motion model and this will still roughly work.

Bonus points for using variable steps, for example, 100ms for the first second (ten points), 200ms for the next two (ten more points), 400ms over 4 seconds, etc. In fact, as your character approaches terminal velocity the variation in the resistance goes down, and you don't need larger timesteps anyway. This way you can handle really long jumps without too much processing, as the complexity for T seconds is O(log T) rather than O(T).

You can also simulate what happens when the character stops boosting partway through their jump, or starts boosting the other way. With the above trick the complexity is O((log T)^2), which isn't too bad.
> 4 votes

# Answer
Yay! I did it!

I'm using simple simulation that takes the first position to land behind the vertical axis of the target point - from there, I take the previous simulated position and make a segment. Now I check whether the target point is below this segment. **If it is - we can jump there.**

It's a player-controlled character on the gif. Pink is the predicted path, yellow segments are predicted subsequent stepping positions, and the final segment turns white if the target point lies below it, red otherwise. Red curve is the actual flight path. There are some *slight* inaccuracies due to physics state interpolation turned on.

The calculations turned out to be surprisingly easy, however making my environment work the same way as these pure calculations do... was a massive pain in the butt. At least I solved some serious bugs out there, so it was a useful exercise after all.

Here is the complete code in Lua used to solve the original problem (the code assumes you have your own "debug\_draw" routine and your own vector class with basic methods like "length\_sq" (length squared), "normalize" or operators +,\*:

```
function simple_integration(p, dt)
    local new_p = {}

    new_p.acc = p.acc
    new_p.vel = p.vel + p.acc * dt
    new_p.pos = p.pos + new_p.vel * dt
    -- uncomment this if you want to use quadratic integration
    -- but with small timesteps even this is an overkill since Box2D itself uses traditional Euler
    -- and I found that for calculations to be accurate I either way must keep the timesteps very low at the beginning of the jump
     --+ p.acc * dt * dt * 0.5

    return new_p
end

function point_below_segment(a, b, p)
    -- make sure a is to the left
    if a.x > b.x then a,b = b,a end

    return ((b.x - a.x)*(p.y - a.y) - (b.y - a.y)*(p.x - a.x)) < 0
end

-- returns true or false
function can_point_be_reached_by_jump
(
gravity, -- vector (meters per seconds^2)
movement_force, -- vector (meters per seconds^2)
air_resistance_mult, -- scalar
queried_point, -- vector (meters)
starting_position, -- vector (meters)
starting_velocity, -- vector (meters per seconds)
jump_impulse, -- vector (meters per seconds)
mass -- scalar (kilogrammes)
)

    local my_point = {
        pos = starting_position,
        vel = starting_velocity + jump_impulse/mass
    }

    local direction_left = movement_force.x < 0
    local step = 1/60

    while true do
        -- calculate resultant force
        my_point.acc =
        -- air resistance (multiplier * squared length of the velocity * opposite normalized velocity)
        (vec2(my_point.vel):normalize() * -1 * air_resistance_mult * my_point.vel:length_sq()) / mass
        -- remaining forces
        + gravity + movement_force/mass

        -- I discard any timestep optimizations at the moment as they are very context specific
        local new_p = simple_integration(my_point, step)

        debug_draw(my_point.pos, new_p.pos, 255, 0, 255, 255)
        debug_draw(new_p.pos, new_p.pos+vec2(0, -1), 255, 255, 0, 255)

        if (direction_left and new_p.pos.x < queried_point.x) or (not direction_left and new_p.pos.x > queried_point.x) then
            if point_below_segment(new_p.pos, my_point.pos, queried_point) then
                debug_draw(new_p.pos, my_point.pos, 255, 0, 0, 255)
                return true
            else
                debug_draw(new_p.pos, my_point.pos, 255, 255, 255, 255)
                return false
            end
        else
            my_point = new_p
        end
    end

    return false
end

```

Accept goes to Jason for setting me into the right direction! Thanks!
> 4 votes

# Answer
You might want to "just calculate" the answer but I'm sure that you'll find it insufficient once you've got it because of the highly interactive nature of your "free fall" physics.

Consider using a different approach: Searching. Here is how it's done for Super Mario AI: http://aigamedev.com/open/interview/mario-ai/

Searching possible pathes to get from A to B allows for unlimited interactivity in mid-air while still being computationally efficient.
> 2 votes

---
Tags: 2d, mathematics, physics, ai, side-scroller
---


# Question
Title: gl_FrontFacing - is there perfomance cost?
If I use `gl_FrontFacing` in my PS, is there any performance cost during vertex transformation (like cross product from triangle vertices), or is this value computed any time ?

# Answer
> 1 votes
The standard answer is **profile**. It may vary between platforms, vendors, driver versions etc.

I would note that if you use this, you are clearly not backface culling, and so will lose some performance there. This information is always computed as part of the fixed function hardware rasterization stage (as usually backface culling is enabled), so barring any costs to transmit this value to the shader, it should have no performance impact.

# Answer
> 2 votes
I feel obligated to point out that there are too many things the rasterizer needs to know the facing of the polygon it is drawing for your use or non-use of `gl_FrontFacing` in the fragment shader to have any affect on the operation of the pipeline.

I highly suggest you take a look at the PDF diagram here, which shows all of the stages and inputs/outputs for the OpenGL graphics pipeline.

If you look carefully at the rasterizer part of the diagram, you will see that polygons must always first go through facing determination. This is used for polygon mode, culling, stencil testing, and in older versions of GL, lighting.

Keep in mind no cross-product is necessary to determine whether a polygon is front or back-facing (GL does not compute or use a triangle normal for this process). OpenGL actually uses the polygon's winding (after projection) and compares it with the front-face you established (Clockwise or Counter-Clockwise). This is a far simpler process than you expected, and it only has to be done once per-primitive, since all polygons in OpenGL are planar.

---
Tags: opengl, fragment-shader
---


title: Game Structure in depth

text:
# Question
Title: Game Structure in depth
I've been curious about game structure for some time now. Does everyone who is a game programmer come up with there own approach to structure there game, or is there like some sort of defined layout. to put this in prospective. Lets say a game programmer wanted to create a tiled map. Is there a specific way to do this, or does the every programmer do it there way.

# Answer
> 1 votes
There's no standard way of doing things when it comes to the implementation. It's like writing a book, there may be common overtones like the Monomyth (or Hero's Journey), but the story will be different and told in a different way for each book.

The patterns you'll find in game development are numerous. The idea behind each pattern may be similar, they'll likely be implemented in different ways.

You could look at a dozen different games that had tile maps and you'd find a dozen different ways to implement tile maps. Just like if you asked a dozen authors to write a story about X, you'd get a dozen different stories.

You'll pick up more as you go and get better. This is why game developers still exist, it's an art that is different in each case.

---
Tags: java, game-design, architecture
---


# Question
Title: What does changing GL_TEXTURE_WRAP)_(S/T) do?
I am working through some beginner OpenGL tutorials, and the current one teaches how to apply a texture to a simple rectangle. The tutorial states tells me to set the texture parameters GL\_TEXTURE\_WRAP\_S and GL\_TEXTURE\_WRAP\_T to GL\_CLAMP\_TO\_EDGE, however I am uncertain as to what this actually does. I am aware it is something to do with how textures larger/smaller than the space they are being mapped onto are handled, but I'm not sure what behavior this actually causes. What does GL\_CLAMP\_TO\_EDGE do, and how is this different from GL\_CLAMP, GL\_CLAMP\_TO\_BORDER, GL\_REPEAT? Thanks very much in advance, and bonus helpfulness if you can provide images for an idiot like me.

# Answer
Well S and T just mean U and V (or X and Y if you prefer), or in GLSL:

```
vec4.xyzw == vec4.rgba == vec4.strq

```

The GL\_REPEAT mode has textures repeat when you go past (0,0) to (1,1) range

The GL\_CLAMP\_TO\_EDGE mode has textures stop at the last pixel when you fall off the edge.

The GL\_CLAMP and GL\_CLAMP\_TO\_BORDER are depreciated because all texture borders must be 0 pixels, so the modes don't make sense anymore. (somewhere around GL3 I believe)

There are more modes so make sure to read the docs. (Examples: GL\_MIRRORED\_REPEAT, GL\_MIRROR\_CLAMP\_TO\_EDGE)

---

There are some good examples on http://www.flipcode.com/archives/Advanced\_OpenGL\_Texture\_Mapping.shtml, here is a preview:

> Wrap S : GL\_CLAMP / Wrap T : GL\_CLAMP
>
> Wrap S : GL\_CLAMP / Wrap T : GL\_REPEAT
>
> Wrap S : GL\_REPEAT / Wrap T : GL\_CLAMP
>
> Wrap S : GL\_REPEAT / Wrap T : GL\_REPEAT
> 35 votes

# Answer
Here is an extract of the OpenGL Reference page on glTexParameter as of 2014/02/07, formatted a bit for easier reading:

> **GL\_TEXTURE\_WRAP\_S**
>
> Sets the wrap parameter for texture coordinate **s** to either GL\_CLAMP\_TO\_EDGE, GL\_CLAMP\_TO\_BORDER, GL\_MIRRORED\_REPEAT, GL\_REPEAT, or GL\_MIRROR\_CLAMP\_TO\_EDGE.
>
> * **GL\_CLAMP\_TO\_EDGE** causes **s** coordinates to be clamped to the range , where **N** is the size of the texture in the direction of clamping.
> * **GL\_CLAMP\_TO\_BORDER** evaluates **s** coordinates in a similar manner to GL\_CLAMP\_TO\_EDGE.
> However, in cases where clamping would have occurred in GL\_CLAMP\_TO\_EDGE mode, the fetched texel data is substituted with the values specified by GL\_TEXTURE\_BORDER\_COLOR.
> * **GL\_REPEAT** causes the integer part of the **s** coordinate to be ignored;
> the GL uses only the fractional part, thereby creating a repeating pattern.
> * **GL\_MIRRORED\_REPEAT** causes the **s** coordinate to be set to the fractional part of the texture coordinate if the integer part of **s** is even; if the integer part of s is odd, then the s texture coordinate is set to , where represents the fractional part of **s**.
> * **GL\_MIRROR\_CLAMP\_TO\_EDGE** causes the the **s** coordinate to be repeated as for GL\_MIRRORED\_REPEAT for one reptition of the texture, at which point the coordinate to be clamped as in GL\_CLAMP\_TO\_EDGE.
>
> Initially, **GL\_TEXTURE\_WRAP\_S** is set to **GL\_REPEAT**.
> 5 votes

---
Tags: opengl, textures
---


title: Lerping back and forth in Coroutine

text:
# Question
Title: Lerping back and forth in Coroutine
Im trying to lerp the scale of a game objecto to 30% its size and then back again, but all i get as output is "

> Blippping Cursor
>
> up scale 0
>
> down scale 0

```
        IEnumerator Blip_cr (Vector2 position)
    {
            coordinateSelected = true;
            SetPosition (position);

            print ("Blippping Cursor");
            var duration = 10f;
            var startScale = transform.localScale;
            var targetScale = startScale * 1.3f;
            var startTime = Time.time;
            var progress = 0f;

            while (progress < 1) {
                    print ("up scale " + progress);
                    var newScale = Vector3.Lerp (startScale, targetScale, progress);
                    progress = duration / (Time.time - startTime);
                    transform.localScale = newScale;
                    yield return  null;
            }
            progress = 0;
            startTime = Time.time;
            while (progress < 1) {
                    print ("down scale " + progress);
                    var newScale = Vector3.Lerp (targetScale, startScale, progress);
                    progress = duration / (Time.time - startTime);
                    transform.localScale = newScale;
                    yield return  null;
            }

            coordinateSelected = false;
    }

```

# Answer
> 1 votes
The formula for `progress` looks wrong. I think it should be:

```
progress = (Time.time - startTime) / duration;

```

---
Tags: c#, unity, lerp
---


# Question
Title: Recommended way to handle sprite assets for different screen densities (Android)
I am currently working on a 2D game for Android. All of the images that I render were created as SVG's and then exported to PNG's which I have placed in my assets directory. These images are also all sprites that I render using a sprite batcher.

My question is around using different versions of the sprites for devices with different densities. I know that when developing a traditional android app you could place separate directories for separate density levels inside of res and then place the correctly sized versions of the images in question in these sub-directories of res.

What is a good approach when dealing with sprite images in the asset directory? Should I just have one copy of the sprites at a really high density / resolution that I use for everything and I just render them on a coordinate system that is independent of screen size or should I resize the image based on screen density before I process it to create all my texture regions? Or is there another solution entirely?

Currently I have one high resolution set of sprites that I use for everything, it just seems wasteful and inefficient for the lower density devices.

# Answer
> 2 votes
After having used multiple asset resolutions on a couple of projects it has proven to be fairly painful in the long run to work with, even though it's usually just running a batch script. More complex support and build processes when updating slow down iteration.

The growing range of aspect ratios and resolutions makes the process questionable. Code that relies on detecting certain resolutions becomes more and more prone to needing rework. Most recently the 'retina' resolutions of iOS caused nearly a week's worth of restructuring to update an old game, since the old code had not considered such an eventuality.

I would recommend keeping your current line of using the highest resolution set only. If performance is a problem, perhaps generating scaled down versions of the assets could be handled on initialization.

# Answer
> 1 votes
Even though it does require more work and a little bit of thought, I think it does add value to your game.

I personally use two resolution sets - one for all resolutions above some threshold and one for all below it. Then I use an initialization class which takes care of setting up the correct file names based on the current device's resolution. My rendering is then performed to a non-screen size dependent coordinate system which is also setup in the initialization class based on the aspect ratio of the device.

Doing it this way means that even if future devices require increased resolution, or I want to make changes to my current assets, I **only have to change one class** to affect all my graphics.

Going through the trouble of doing this depends largely on your game and intended audience. But since android has a very large group of low end devices I think it is worth the trouble, especially if you find in testing that your game performs poorly on low end devices using high resolution assets.

This will also future proof your game and allow you to fairly easily "upgrade" it for higher resolution devices as they become available. Most current devices target **HD/1080p**, but with **UHD/2160p/4K** becoming all the rage it is just a matter of time before devices support these resolutions. Graphics designed for 1080p will need to be scaled up to twice their original size to render to these devices, so adding native support for UHD could dramatically increase your visual quality.

---
Tags: android, sprites, assets
---


# Question
Title: ParticleEffectPool.obtain() not resetting particles
I want to use ParticleEffectPools in libGDX but I'm running into an odd issue where the effects don't seem to be reset when obtained by the pool. The code below looks for an existing ParticleEffectPool for the named effect, creates one if necessary, and then obtains a particle effect for the newly created Actor. The particle effect should be reset in the obtain function (if you look at the source it does so). What happens is the first effect works as expected but every subsequent one flashes very briefly on the screen as if its run out of duration.

```
public class ParticleEffectActor extends Actor {

    private static final Map<String, ParticleEffectPool> ParticlePools = new HashMap<>();
    private final PooledEffect effect;

    public ParticleEffectActor(String effectName, float rotation) {
        if(!ParticlePools.containsKey(effectName)) {
            ParticleEffect particleEffect = new ParticleEffect();
            particleEffect.load(Gdx.files.internal("resources/particles/" + effectName + ".p"), Images.Atlas);
            ParticlePools.put(effectName, new ParticleEffectPool(particleEffect, 10, 50));
        }

        this.effect = ParticlePools.get(effectName).obtain();

        rotation -= 90f;
        for(ParticleEmitter emitter : effect.getEmitters()) {
            emitter.reset();
            ParticleEmitter.ScaledNumericValue angle = emitter.getAngle();
            angle.setLow(rotation - 35, rotation + 35);
            angle.setHigh(rotation - 35, rotation + 35);
        }
    }

    @Override
    public void draw (SpriteBatch batch, float parentAlpha) {
        effect.draw(batch);
    }

    @Override
    public void act (float delta) {
        super.act(delta);
        effect.setPosition(getX(), getY());
        effect.update(delta);
    }

    @Override
    public boolean remove() {
        effect.free();
        return super.remove();
    }
}

```

# Answer
For what it's worth, I was having this issue (or at least very similar) where when I reset my emitters, I no longer had any particle effects.

My situation is I needed to shrink my particle effects to a dynamic size upon each reset, since I am re-using projectile objects, that happen to contain a projectile trail, and each time a projectile object is fired, it is given the projectile properties the turret desires.

***Anyways**, turns out I had done:*

```
m_TrailEffect.getScale().setLow(size * m_TrailEffect.getScale().getLowMin(), size * m_TrailEffect.getScale().getLowMax());
m_TrailEffect.getScale().setHigh(size * m_TrailEffect.getScale().getHighMin(), size * m_TrailEffect.getScale().getHighMax());

```

So each time I reset my emitter, my scale was getting larger/smaller by a ***factor*** of 'size'!

**To fix it**, I stored the initial scale low min/max and high min/max right after load()'ing the emitter, and used those instead of getMin/getMax:

```
m_TrailEffect.getScale().setLow(m_ScaleLowMin * size, m_ScaleLowMax * size);
m_TrailEffect.getScale().setHigh(m_ScaleHighMin * size, m_ScaleHighMax * size);

```
> 1 votes

---
Tags: libgdx, particles, object-pools
---


title: XNA - Spritebatch Drawing Order

text:
# Question
Title: XNA - Spritebatch Drawing Order
I'm new in this and I'm making XNA game. I have problem with the `spritebatch` drawing order. To be explained : I click button to open inventory and I need all drawing to be behind my inventory layout. But problem is that I don't know how to do this because in my draw method I cannot change my drawing hierarchy, as all the stuff need to be drawn before the inventory is drawn.

Is there a way to set up a drawing order? Or is there a way to dynamically move one particular `spritebatch` up in drawing hierarchy?

# Answer
> 2 votes
You could have a `DisplayManager` which contains some "layers", let's say you want 3 layers, `bottom`, `middle` and `top`. These layers aka `lists` contains the instances of the `IDisplay` objects. `IDisplay` is an *interface* with a `Draw` function.
The `DisplayManager` itself has an `Update` or `Draw` function, however you name it, and you call it between the `SpriteBatch's` `Begin` and `End` function.

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
DisplayManager.Update(spriteBatch);
spriteBatch.End();
...
//In the DisplayManager class:
private static List<IDisplay> top = new List<IDisplay>();
private static List<IDisplay> middle = new List<IDisplay>();
private static List<IDisplay> bottom = new List<IDisplay>();
...
//In the DisplayManager class:
public static void Update(SpriteBatch batch){
    for (i = 0; i < bottom.Count; i++)
    {
        bottom[i].Draw(batch);
    }
    for (i = 0; i < middle.Count; i++)
    {
        middle[i].Draw(batch);
    }
    for (i = 0; i < top.Count; i++)
    {
        top[i].Draw(batch);
    }
}

```

Note the draw order in the Update function, first draw the "bottom" layer, then the middle and the top.

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


# Question
Title: How are Volumetric Effects made within games? (e.g. Smoke/Fire)
For computer generated volumetric elements such as clouds, fire, and whitewater.

How are they made? *Is it just a simple collection of particles \[put to pixels\] taken from Physics equations or are the like textures?*

How are they applied? I would assume not from UV mapping

---

Derbis, smoke and fire come from the vehicle.

# Answer
> 2 votes
Particle emitters with additive/multiplicative blending?

http://www.pxleyes.com/blog/wp-content/uploads/2010/04/fumefx.jpg

Maybe you mean something different? But I think the effects in that screenshot is made out of particles with additive blending, and then overlayed with particles with multiplicative blending (the darker parts).

---
Tags: textures, graphics
---


title: Still confused about timesteps in XNA

text:
# Question
Title: Still confused about timesteps in XNA
I have been reading many different posts and articles about timesteps and while I now understand that fixed timesteps are generally considered superior, I'm having a bit of difficulty implementing one in XNA.

Apparently XNA uses a fixed timestep where the update method is called 60 times per second by default. However, I'm not really sure how to reconcile this fact with what I have been reading here, here, and here.

Do I need to supply my physics stepping with some sort of delta variable? Should I even be using `GameTime.ElapsedGameTime` anywhere in my code?

I guess I'm just a bit confused in regard to how much XNA is actually doing for me. Is it advisable to turn off the fixed timestep in XNA and instead make my own loop like the one from this post?

# Answer
By default, although XNA *tries* to work with fixed timesteps, it only uses a best effort policy. Also, later during development, you might want to reduce FPS to 30 or lower (for example, when releasing on X360 or WP7, or after you realize your game is too demanding).

If you implement your game assuming a fixed frame rate, you'd better be damn sure that'll work until the end. Otherwise, adapting to a new frame rate might be troublesome. If, from the onset, you use `gameTime.ElapsedTime` in your calculations, you can pretty much expect your game to behave as if it worked with fixed time step, but still have future changes covered. The only cases where I can see a real advantadge in using hard-wired fixed time step is when using very precise physics calculations (as stated in your last link) or when relying on discrete time intervals between updates, like a game with a perfect rewind/play mechanism, as Braid.

Regarding the implementation of your own game loop, I think that's more complicated than necessary in XNA. Pretty much everything in the framework is tailored to work within XNA's time step implementation and update/draw loop. You'll have to tinker around, finding out what to remove or keep to get what you want. And if you're not taking advantadge of the work XNA does for you, you shoud really look for a better fit to your specific needs and desires.
> 6 votes

# Answer
> Do I need to supply my physics stepping with some sort of delta variable? Should I even be using GameTime.ElapsedGameTime anywhere in my code?

Yes, you should. I'm not sure if XNA have a fixed timestep in 60fps, but even if it does, the fps may drop and you wont be able to do nothing about it, so that's why it is better to still use `GameTime.ElapsedGameTime`.

> Is it advisable to turn off the fixed timestep in XNA and instead make my own loop like the one from this post?

May be a good practice, and also a complicated if you don't know what you're doing. If XNA have fixed timestep, good, stay with it.
> 4 votes

# Answer
FixedTimeStep is about as advanced as you can make such a routine, it gives you (by default) 60 updates a second regardless of if you have 10fps or 100fps, it will also gracefully handle debugging without locking your machine up (the loop you refer to would naively try to catch up to all the lost frames, causing an interesting cascade effect and loss of fps as it jumps the game - possibly all the way to game over screen).

As to if its better or not, that depends on who you ask. For consoles fixed time step makes sense since it simplifies the code and the console has a very fixed potential frame rate. Computer games can be run on wildly varying hardware so those would normally prefer one update per actual frame rendered.

If your not going to code anything "smart" using the ElapsedGameTime (such as running physics in a simpler mode to prevent lag) then technically there's no reason to not use FixedTimeStep. That said, it's easier to convert a game **to** fixed timestep rather than from it. If you make use of ElapsedGameTime your game will run fine in either mode, where as if you ignore it you can't easily change your decision.

I suggest you read more about how XNA handles this in the words of Shawn Hargreaves himself which should answer most of your questions.
> 4 votes

# Answer
Be aware of FPS drops below 60. Even with fixed time step it will cause issues with your physics/update method. I'd recommend to use GameTime.ElapsedGameTime anywhere in your update/physics code to avoid issues.
> 0 votes

---
Tags: xna, c#, fixed-timestep
---


title: How to make a game without OOP?

text:
# Question
Title: How to make a game without OOP?
I am currenty studying game development and practicing making games.

I use a lot of OOP in my games. For example, each missile that is shot is an instance of a `Missile` object, and added to a list of `Missile` objects. Each tank in the game is a `Tank` object. Etc.

The entire design of the program is based on this. For instance, having a list of `Missile` objects allows me every frame to move the missiles, draw them, etc. And having an instance of a `Tank` object for every tank allows me to check for each tank if it collides with something, etc.

It's hard for me to imagine how a game (which is more complex than Pac-Man) could be programmed in a non-OO language. (With no disrespect to non-OO programmers of course). Not only in terms of how long it will take, but mostly in terms of how a game could be designed this way.

I can't imagine designing a game without using object oriented programming, because my entire understanding of how to design a game-program is based on OOP.

I would like ask: Today, are there any games that aren't programmed using OOP, in a similiar fashion to what I described above? Are there any 'professionl' games that don't use OOP as a major factor in the development process?

If so, could you give me an idea of how, for example, collision detection between a tank and N number of missiles could be implemented, without OOP?

# Answer
> I can't imagine designing a game without using object oriented programming, because my entire understanding of how to design a game-program is based on OOP.

Then it will probably be good for you to try writing some programs in non-OO style. Even if you discover that this is not pragmatic for you, you'll probably learn a lot along the way that will help you in the future.

OO style is pretty well-suited for games because games are almost always about manipulation of stateful objects. A laser beam hits the robot and the state of the robot changes while its identity remains the same.

However it is possible to program games in a *functional* style. In a functional style, state doesn't change per se. Objects are immutable. Rather than changing objects, you ask the question *how would the universe be different if I changed this?* and then produce an entire new universe that has the changed property. Of course, you can re-use a lot of the previously existing universe *because it is immutable*.

In functional programming every function must compute its return value solely from the information passed in; there's no reading from "global state".

If you do this, the fundamental problem you will have to get through your head is that *every update is non-destructive*. When the laser hits the robot you don't change the robot's state. Ultimately you compute an entirely new universe identical to the old universe except that the robot has a different state; if you need that old universe, it's still there, unchanged.

This series of blog articles has more thoughts on writing games in a functional style:

http://prog21.dadgum.com/23.html

This article specifically addresses your "shell hits a tank" question:

http://prog21.dadgum.com/189.html

In fact, just read the whole blog. There's good stuff there and the articles are short.
> 16 votes

# Answer
Any object-oriented program can be refactored to a procedural program by replacing all classes with structures and converting all member-functions into stand-alone function which take the object which would be `this` as an argument.

So

```
 missile.setVelocity(100);

```

becomes

```
 setMissileVelocity(missile, 100);

```

or when that function is trivial, you just do

```
 missile.velocity = 100;

```

The main difference between object-oriented programming and procedural programming is how you treat your data. In OOP, data is *smart*. It manages and manipulates itself. But in procedural programming, data is *dumb*. It doesn't do anything on its own and needs to be manipulated from the outside.

When you even consider structures too object-oriented, you can replace one array of structures with multiple arrays, one for everything which would be a variable of a missile. So

```
struct Missile {
     int x;
     int y;
     int velocity;
}

Missile missiles[256];

```

becomes

```
int missileX[256];
int missileY[256];
int missileVelocities[256];

```

In this design, a function which does an operation involving multiple attributes on the same missile would now take an array index instead of a reference to a structure. Its implementation would look like this:

```
function updateMissilePosition(int index) {
     missileX[index] += missileVelocity[index];
}

```
> 13 votes

# Answer
I do it as follows:

* All OOP classes/methods have access to `this`. In order to utilise `this` in a non-OO approach, simply pass in whichever instance (see next point) `this` should be, as the first parameter.
* Now, as for instances, you can pass `struct`s into your functions as `this`, but I find the best way to achieve good cache performance for objects which are prolific, such as entities or particles, is to simply pass a single index into several arrays of primitives or small `struct`s. So this index is used for each individual data member of the original class. So for instance if you had

...

```
class Entity //let's say you had 100 instances of this
{
   int a;
   char b;
   function foo()
   {
      .../*can access 'this' herein*/
   }
}

```

You would replace that with

```
int a[100];
char b[100];
function foo(int index);

```

So that you are now passing an index into the function to get what would usually be `this`.

Bear in mind that you may wish to use either arrays of primitives as above, *or* arrays of `struct`s, depending on how best to interleave your data for good cache locality (locality of reference). Of course, decent cache performance relies on a lot more than this -- particularly, what language / platform you are writing your code on -- but even in VM-based, dynamically-allocated languages like Java, large linear arrays of primitives tend to display better performance characteristics than object instances. The main reason for this is that objects are accessed by reference and this means you are jumping all over memory to access data -- inefficient compared to accessing primitives contiguously from a large array.

For more information on building entities etc. as array of structs or primitives, see Mick West's Evolve your Hierarchy.
> 7 votes

# Answer
In addition to the existing answers you may want to know how to do polymorphism in a procedural language.

There are two approaches:

**Storing the type**

In this case the struct has a field for the type identifier, probably an enum, that's checked using a `switch` statement when type specific action needs to be done.

The other way is:

**Storing function pointers**

You didn't mentioned which programming language you have experience in, but in various languages they are also called callbacks, delegates, events or high order functions or simply function objects.

In this case you won't store a type, but store a pointer/reference to a function that does the particular action. When type specific action needs to be done, you simply call this function. This one looks much like the ordinary virtual methods.

By allowing setting each function independently you get the strategy pattern free.

---

Regarding your last paragraph with the collision detection. I think you probably have multiple kinds of tanks and you have multiple kinds of missiles, and each combination can potentially have a different outcome when they collide. If this is what you look for, you have a problem that's not yet solved by even OOP languages: multiple dispatch and multi-methods that can have multiple `this` parameters of different types. For this problem there again two alternatives:

* Nested switches for each combination of tank and missile.
* Two dimensional dispatch arrays, which contain pointers to functions for each combination of tank and missile.
> 0 votes

---
Tags: architecture, software-engineering, oop
---


# Question
Title: How can I compute the orbit of one body around another?
I'm attempting to have a planet (with a known mass and radius) orbit it's sun (also with a known mass and radius). It doesn't have to be 100% realistic, but it should be possible that the sun have more than one planet orbit it at a time.

What equations should I use to accomplish this?

# Answer
> 1 votes
If the players will never know the difference, then don't worry about mass or radius. For the oribiting planet store \- the distance to the center planet (radius of rotation) \- current position in degrees \- orbit-speed (degrees per game tick)

For each game tick \- change the position by adding the speed \- calculate the new position (using Cos and Sin)

Would this simplified method work?

# Answer
> 1 votes
If players have no effect over the orbit (such as moving planets) then the best option would simply be to define paths for the planet to travel along (using bezier curves etc). It's stable and simple. You would never be able to affect the movement in game (unless you went to the trouble of altering the defined path) and may open up unrealistic possibilities (like crazy orbits).

Just remember to keep in mind Kepler's law of planetary motion, especially the second one as this will affect how you move the planet along the path.

---
Tags: opengl, c++, planet, orbit
---