title: Entity Component System based engine

text:
# Question
Title: Entity Component System based engine
*Note: I'm programming this in Javascript, but it should be language agnostic in the most part.*

I am thinking about converting my engine to an ECS based one.

I get the basic idea (*note: this is wrong, see my answer*):

**Entities** are game objects.
**Components** are bits of functionality (`reactToInput()`) or state (`position`) which can get "glued" to entities.
**Systems** have a list of entities they manage and update.

But, I'm not quite sure that I get the implementation and some details...

Question: **can a system operate on different kinds of entities?** I usually give the example of a class called `Scene` in my engine, and it will serve this purpose now, as well. A scene is a container of all objects that can be rendered, updated, affect the rendering (lights), and maybe, in future, even `2DSoundEmitter` objects. It has a high-level interface so the user doesn't need to worry about the type of the object he's `scene.add()`ing, and all that kind of stuff.

I realize that the `Scene` could be a system. It takes in entities, stores them, and then it can call their update methods, and maybe even do some state changes. But, there is a problem: as I described above, the `Scene` can be fed *different types* of objects! What should I do in, say, a situation where a scene has both renderable objects ("drawables") *and* lights in it? Should I make it type-check entities before interacting? Or, should I solve it at an even lower level: make a `LightSource` component which can be added to *any* object, and the light would just be an entity with `LightSource` and `Position` components. Is that acceptable?

Also, is it a good practice to still use conventional inheritance and traditional classes? For example, I just can't figure out what would my `Renderer` be! It's not a system, as its only function is to take in a camera and a scene, render everything and apply effects (such as shadows). It also manages the context, the width and the height of the game, makes translations... But it's still not a system!

**Edit:** could you maybe link any resources you found on the ECS? I'm having trouble finding good ones.

# Answer
> 6 votes
Let me see if by trying to understand as a web/UI JS dev, I can be of help. Also, don't go too far in language agnosticism. A lot of patterns established in other languages are worth studying but can be applied very differently in JS due to its flexibility or really aren't necessary due to the malleable nature of the language. You could blow some opportunities if you write your code thinking of JS as having the same set of boundaries that a more classical OOP-oriented language does.

First of all, on the "don't use OOP" factor, remember that JavaScript objects are like playdough compared to other languages and you actually have to go out of your way to build a cascading-inheritance scheme nightmare since JS isn't class-based and compositing comes much more naturally to it. If you are implementing some silly class or prototype hand-me-down system in your JS, consider ditching it. In JS we use closures, prototypes, and we pass functions around like candy. It's disgusting and filthy and wrong but also powerful, concise and that's the way we like it.

Inheritance heavy approaches are actually spelled out as an anti-pattern in Design Patterns and for good reason as anyone who has walked down 15+ levels worth of class or class-like structures to try and figure out where the heck the busted version of a method was coming in from can tell you.

I don't know why so many programmers love doing this (especially java guys writing JavaScript for some reason), but it's awful, illegible, and completely unmaintainable when used to excess. Inheritance is okay here and there, but not really necessary in JS. In languages where it's a more enticing shortcut, it should really be reserved for more abstract architecture concerns rather than more literal modeling schemes like frankensteining a zombie implementation through an inheritance chain that included a BunnyRabbit because it happened to work. That's not good code reuse. It's a maintenance nightmare.

As a JS dev Entity/Component/System based engines strike me as a system/pattern for decoupling design concerns and then compositing objects for implementation on a highly granular level. In other words, child's play in a language like JavaScript. But let me see if I'm grokking this correctly first.

* Entity - The specific thing you are designing. We're talking more in the direction of proper nouns (but not actually, of course). Not 'Scene', but 'IntroAreaLevelOne'. IntroAreaLevelOne might sit inside a sceneEntity box of some kind but we're focusing on something specific that varies from other related things. In the code, an entity is really just a name (or ID) tied to a bunch of stuff that it needs to have implemented or established (the components) in order to be useful.
* Components - types of things an entity needs. These are general nouns. Like WalkingAnimation. Within WalkingAnimation we can get more specific, like "Shambling" (good choice for zombies and plant monsters), or "ChickenWalker" (great for reverse-joint ed-209ish robot-types). Note: Not sure how that could decouple from the rendering of a 3D model like that - so maybe a crap example but I'm more of a JS pro than an experienced game dev. In JS I would put the mapping mechanism in the same box with the components. Components in their own right are likely to be light on logic and more of a roadmap telling your systems what to implement if systems are even needed (in my attempt at ECS some components are just collections of property sets). Once a component is established, it's easy enough to tweak one component and assign the altered version to a new name if necessary but having sets of properties that can referred to for branching of behavior established by Systems strikes me as a better way to go.
* Systems - The real programmey meat is here. AI systems are built and linked, Rendering is achieved, animations sequences established, etc... I'm copping out and leaving these mostly to the imagination but in the example System.AI takes a bunch of properties in and spits out a function which is used to add event handlers to the object that ultimately gets used in implementation. The key thing about System.AI is that it covers multiple component types. You could sort out all the AI stuff with one component but to do so is to misunderstand the point of making things granular.

Mind the Goals: We want to make it easy to plug in some kind of GUI interface for non-designers to easily tweak different kinds of stuff by maxing and matching components within a paradigm that makes sense to them, and we want to get away from popular arbitrary code schemes that are a lot easier to write than they are to modify or maintain.

So in JS, maybe something like this. Game devs please tell me if I've got it horribly wrong:

```
//I'm going with simple objects of flags over arrays of component names
//easier to read and can provide an opt-out default
//Assume a genre-bending stealth assassin game

//new (function etc... is a lazy way to define a constructor and auto-instantiate
var npcEntities = new (function NpcEntities(){

    //note: {} in JS is an object literal, a simple obj namespace (a dictionary)
    //plain ol' internal var in JS is akin to a private member
    var default={ //most NPCs are humanoids and critters - why repeat things?
        speedAttributes:true,
        maneuverAttributes:true,
        combatAttributes:true,
        walkingAnimation:true,
        runningAnimation:true,
        combatAnimation:true,
        aiOblivious:true,
        aiAggro:true,
        aiWary:true, //"I heard something!"
        aiFearful:true
    };

    //this. exposes as public

    this.zombie={ //zombies are slow, but keep on coming so don't need these
        runningAnimation:false,
        aiFearful:false
    };

    this.laserTurret={ //most defaults are pointless so ignore 'em
        ignoreDefault:true,
        combatAttributes:true,
        maneuverAttrubtes:true, //turning speed only
    };
    //also this.nerd, this.lawyer and on and on...

    //loop runs on instantiation which we're forcing on the spot

    //note: it would be silly to repeat this loop in other entity collections
    //but I'm spelling it out to keep things straight-forward.
    //Probably a good example of a place where one-level inheritance from
    //a more general entity class might make sense with hurting the pattern.
    //In JS, of course, that would be completely unnecessary. I'd just build a
    //constructor factory with a looping function new objects could access via
    //closure.

    for(var x in npcEntities){

        var thisEntity = npcEntities[x];

        if(!thisEntity.ignoreDefaults){

            thisEntity = someObjectXCopyFunction(defaults,thisEntity);
            //copies entity properties over defaults

        }
        else {
            //remove nonComponent property since we loop again later
            delete thisEntity.ignoreDefaults;
        }
    }
})() //end of entity instantiation

var npcComponents = {
    //all components should have public entityMap properties

    //No systems in use here. Just bundles of related attributes
    speedAttributes: new (function SpeedAttributes(){
        var shamblingBiped = {
            walkingAcceleration:1,
            topWalking:3
        },
        averageMan = {
            walkingAcceleration:3,
            runningAcceleration:4,
            topWalking: 4,
            topRunning: 6
        },
        programmer = {
            walkingAcceleration:1,
            runningAcceleration:100,
            topWalking:2
            topRunning:2000
        }; //end local/private vars

        //left is entity names | right is the component subcategory
        this.entityMap={
            zombie:shamblingBiped,
            lawyer:averageMan,
            nerd:programmer,
            gCostanza:programmer //makes a cameo during the fire-in-nursery stage
        }
    })(), //end speedAttributes

    //Now an example of an AI component - maps to function used to set eventHandlers
    //functions which, because JS is awesome we can pass around like candy
    //I'll just use some imaginary systems on this one

    aiFearful: new (function AiFearful(){
        var averageMan = Systems.AI({ //builds and returns eventSetting function
            fearThreshold:70, //%hitpoints remaining
            fleeFrom:'lastAttacker',
            tactic:'avoidIntercept',
            hazardAwareness:'distracted'
        }),
        programmer = Systems.AI({
            fearThreshold:95,
            fleeFrom:'anythingMoving',
            tactic:'beeline',
            hazardAwareness:'pantsCrappingPanic'
        });//end local vars/private members

         this.entityMap={
            lawyer:averageMan,
            nerd:averageMan, //nerds can run like programmers but are less cowardly
            gCostanza:programmer //makes a cameo during the fire-in-nursery stage
        }
    })(),//and more components...

    //Systems.AI is general and would get called for all the AI components.
    //It basically spits out functions used to set events on NPC objects that
    //determine their behavior. You could do it all in one shot but
    //the idea is to keep it granular enough for designers to actually tweak stuff
    //easily without tugging on developer pantlegs constantly.
    //e.g. SuperZombies, zombies, but slightly tougher, faster, smarter
}//end npcComponents

function createNPCConstructor(npcType){

    var components = npcEntities[npcType],

    //objConstructor is returned but components is still accessible via closure.

    objConstructor = function(){
        for(var x in components){
            //object iteration <property> in <object>

            var thisComponent = components[x];

            if(typeof thisComponent === 'function'){
                thisComponent.apply(this);
                //fires function as if it were a property of instance
                //would allow the function to add additional properties and set
                //event handlers via the 'this' keyword
            }
            else {
                objConstructor.prototype[x] = thisComponent;
                //public property accessed via reference to constructor prototype
                //good for low memory footprint among other things
            }
        }
    }
    return objConstructor;
}

var npcBuilders= {}; //empty object literal
for (var x in npcEntities){
    npcConstructors[x] = createNPCConstructor(x);
}

```

Now any time you need an NPC, you could build with `npcBuilders.<npcName>();`

A GUI could plug into the npcEntities and components objects and allow designers to tweak old entities or create new entities by simply mixing and matching components (although there's no mechanism in there for non-default components but special components could be added on the fly in the code as long as there was a defined component for it.

# Answer
> 1 votes
I have read up on Entity Systems in the articles that kind people provided in the comments, but I still had some doubts, so I asked another question.

First off, my definitions were wrong. **Entities** and **Components** are just dumb data holders, while systems provide *all* functionality.

I learned enough to cover most of my question here, so I'll answer it.

The `Scene` class I was talking about shouldn't be a system. It should, though, be a central manager that can hold all entities, facilitate messages, and maybe even manage systems. It can also function as a sort-of factory for entities, and I've decided to use it like that. It *can* take any type of an entity, but then it must feed that entity to an appropriate system (which, for performance reasons, shouldn't perform any type-checks, unless they're bitwise).

I shouldn't use any OOP while implementing an ES, suggests Adam, but I find no reason not to have objects with methods for both entities and components, not just dumb data holders.

The `Renderer` can simply be implemented as a system. It would maintain a list of drawable objects and call their render component's `draw()` method each 16ms.

# Answer
> -2 votes
Introduction to dependency management 101.

This course assumes you have basic knowledge of dependency injection and repository design.

Dependency injection is just a fancy way for objects to talk each other (via messages/signals/delegates/whatever) without being directly coupled.

It goes by the phrase: "`new` is glue."

I will be demonstrating this in C#.

```
public interface IEntity
{
    int[] Position { get; }
    int[] Size { get; }
    bool Update();
    void Render();
}

public interface IRenderSystem
{
    void Draw(IEntity entity);
}

public interface IMovementSystem
{
    bool CanMoveLeft();
    void MoveLeft();
    bool CanMoveRight();
    void MoveRight();
    bool CanMoveUp();
    void MoveUp();
    bool CanMoveDown();
    void MoveDown();
    bool Moved();
    int[] Position { get; set; }
}

public interface IInputSystem
{
    string Direction { get; set; }
}

public class Player : IEntity
{
    private readonly IInputSystem _inputSystem;
    private readonly IMovementSystem _movementSystem;
    private readonly IRenderSystem _renderSystem;
    private readonly int[] _size = new[] { 10, 10 };

    public Player(IRenderSystem renderSystem, IMovementSystem movementSystem, IInputSystem inputSystem)
    {
        _renderSystem = renderSystem;
        _movementSystem = movementSystem;
        _inputSystem = inputSystem;
    }

    public bool Update()
    {
        if (_inputSystem.Direction == "Left" && _movementSystem.CanMoveLeft())
            _movementSystem.MoveLeft();
        if (_inputSystem.Direction == "Right" && _movementSystem.CanMoveRight())
            _movementSystem.MoveRight();
        if (_inputSystem.Direction == "Up" && _movementSystem.CanMoveUp())
            _movementSystem.MoveUp();
        if (_inputSystem.Direction == "Down" && _movementSystem.CanMoveDown())
            _movementSystem.MoveDown();

        return _movementSystem.Moved();
    }

    public void Render()
    {
        if (_movementSystem.Moved())
            _renderSystem.Draw(this);
    }

    public int[] Position
    {
        get { return _movementSystem.Position; }
    }

    public int[] Size
    {
        get { return _size; }
    }
}

```

This is a basic system for Input, Movement, and Rendering. The `Player` class is the entity in this case and the components are the Interfaces. The `Player` class knows nothing about the internals of how a concrete `IRenderSystem`, `IMovementSystem`, or `IInputSystem` work. However, the interfaces provide a way for the `Player` to send signals (e.g. invoke Draw on the IRenderSystem) without depending on how the end result is accomplished.

For example take my implementation of IMovementSystem:

```
public interface IGameMap
{
    string LeftOf(int[] currentPosition);
    string RightOf(int[] currentPosition);
    string UpOf(int[] currentPosition);
    string DownOf(int[] currentPosition);
}

public class MovementSystem : IMovementSystem
{
    private readonly IGameMap _gameMap;
    private int[] _previousPosition;
    private readonly int[] _currentPosition;
    public MovementSystem(IGameMap gameMap, int[] initialPosition)
    {
        _gameMap = gameMap;
        _currentPosition = initialPosition;
        _previousPosition = initialPosition;
    }

    public bool CanMoveLeft()
    {
        return _gameMap.LeftOf(_currentPosition) == "Unoccupied";
    }

    public void MoveLeft()
    {
        _previousPosition = _currentPosition;
        _currentPosition[0]--;
    }

    public bool CanMoveRight()
    {
        return _gameMap.RightOf(_currentPosition) == "Unoccupied";
    }

    public void MoveRight()
    {
        _previousPosition = _currentPosition;
        _currentPosition[0]++;
    }

    public bool CanMoveUp()
    {
        return _gameMap.UpOf(_currentPosition) == "Unoccupied";
    }

    public void MoveUp()
    {
        _previousPosition = _currentPosition;
        _currentPosition[1]--;
    }

    public bool CanMoveDown()
    {
        return _gameMap.DownOf(_currentPosition) == "Unoccupied";
    }

    public void MoveDown()
    {
        _previousPosition = _currentPosition;
        _currentPosition[1]++;
    }

    public bool Moved()
    {
        return _previousPosition == _currentPosition;
    }

    public int[] Position
    {
        get { return _currentPosition; }
    }
}

```

`MovementSystem` can have its own dependencies and the `Player` wouldn't even care. By using interfaces, a game state machine can be created:

```
public class GameEngine
{
    private readonly List<IEntity> _entities;
    private List<IEntity> _renderQueue;

    public GameEngine()
    {
        _entities = new List<IEntity>();
    }

    public void RegisterEntity(IEntity entity)
    {
        _entities.Add(entity);
    }

    public void Update()
    {
        _renderQueue = new List<IEntity>();
        foreach (var entity in _entities)
        {
            if(entity.Update())
                _renderQueue.Add(entity);
        }
        // Linq version for those interested
        //_renderQueue.AddRange(_entities.Where(e => e.Update()));
    }

    public void Render()
    {
        foreach (var entity in _renderQueue)
        {
            entity.Render();
        }
    }
}

```

And that is the start of a lovely game (that is also unit testable).

And with a few additions and some polymorphism:

```
public interface IEntity
{
}

public interface IRenderableEntity : IEntity
{
    void Render();
}

public interface IUpdateableEntity : IEntity
{
    void Update();
    bool Updated { get; }
}

public interface IRenderSystem
{
    void Draw(IRenderableEntity entity);
}

// new player class
public class Player : IRenderableEntity, IUpdateableEntity
{
    private readonly IInputSystem _inputSystem;
    private readonly IMovementSystem _movementSystem;
    private readonly IRenderSystem _renderSystem;
    private readonly int[] _size = new[] { 10, 10 };

    public Player(IRenderSystem renderSystem, IMovementSystem movementSystem, IInputSystem inputSystem)
    {
        _renderSystem = renderSystem;
        _movementSystem = movementSystem;
        _inputSystem = inputSystem;
    }

    public void Update()
    {
        if (_inputSystem.Direction == "Left" && _movementSystem.CanMoveLeft())
            _movementSystem.MoveLeft();
        if (_inputSystem.Direction == "Right" && _movementSystem.CanMoveRight())
            _movementSystem.MoveRight();
        if (_inputSystem.Direction == "Up" && _movementSystem.CanMoveUp())
            _movementSystem.MoveUp();
        if (_inputSystem.Direction == "Down" && _movementSystem.CanMoveDown())
            _movementSystem.MoveDown();
    }

    public bool Updated
    {
        get { return _movementSystem.Moved(); }
    }

    public void Render()
    {
        if (_movementSystem.Moved())
            _renderSystem.Draw(this);
    }

    public int[] Position
    {
        get { return _movementSystem.Position; }
    }

    public int[] Size
    {
        get { return _size; }
    }
}

public class GameEngine
{
    private readonly List<IEntity> _entities;
    private List<IRenderableEntity> _renderQueue;

    public GameEngine()
    {
        _entities = new List<IEntity>();
    }

    public void RegisterEntity(IEntity entity)
    {
        _entities.Add(entity);
    }

    public void Update()
    {
        _renderQueue = new List<IRenderableEntity>();
        foreach (var entity in _entities)
        {
            if (entity is IUpdateableEntity)
            {
                var updateEntity = entity as IUpdateableEntity;
                updateEntity.Update();
            }

            if (entity is IRenderableEntity)
            {
                var renderEntity = entity as IRenderableEntity;
                _renderQueue.Add(renderEntity);
            }
        }
    }

    public void Render()
    {
        foreach (var entity in _renderQueue)
        {
            entity.Render();
        }
    }
}

```

We now have a primitive entity/component system based on aggregating interfaces and loose inheritance.

---
Tags: software-engineering, javascript, component-based, entity-system
---


# Question
Title: How to combine image with a gradient? Or make it more featured in a different way
I generate an abstract 128x128 image, that is in general two-color (it uses values scaled between "blue" and "white", or other similar color pair). I need to make the image more "featured".

Currently, I am blending a four color gradient (prepared in a separate 128x128 buffer) via techniques based on equations from gimp docs. The effects are not good – the gradient dominates over the source image.

How to add some "features" to an abstract image, in procedural way? Maybe you have some tested techniques?

**EDIT:** here is the image – based on Perlin Noise:

# Answer
I have no real idea what you want, but you can probably rule out a number of blend modes, because they bias towards darker or lighter images. There aren't too many that take two images with full dynamic range and produce another image will full dynamic range.

Additionally, some of the blend modes are going to mostly alter the dark areas (blue regions in your image: *Lighten only* seems to be in this category), while others are only going to alter the light areas (white regions in your image: *Hard light* seems to do this).

*Difference* seems to do decently at producing dynamic images and altering both the colors of your source image:

If you ever need to scale down the contribution of the color texture, you can always just uniformly lighten/darken it (which you do depends on the blend mode you select).
> 2 votes

---
Tags: procedural-generation, image
---


# Question
Title: Is it possible to make a text based game and filter bad stuff?
I was thinking of a text based game where the users type in various "things." But I know it will quickly degenerate into filth. Is there any way to stop something like this?

# Answer
> 4 votes
Users determined to use inappropriate words can be *very* creative in getting around even quite sophisticated automatic systems. Imagine you want to block the word, "pear". Can your filter deal with deliberate misspellings like "pair"? And what about false positives, like "appear"? What if the user's real name is actually "Pearson"? But offenders start using the player's name in place of "bad words"?

There are, however, several techniques that can help. The idea is not to prevent offensive behaviour, but rather to take the fun out of it.

* Make expectations clear to users (terms of use, on-screen instructions)
* Filter words that are obviously bad. So, you would filter "pear" but not "pair". You're dealing with casual offenders, you're setting the tone, but you'll still allow "pearson" to play.
* As suggested in another answer, show the original words to the person who typed them, but the clean version to others. The genius of this technique is that users may not realise that their words are being filtered, so may not think to invent workarounds.
* Automatically (and politely) remind offenders to stop. Explain why some people find their behaviour inappropriate
* If it isn't an essential aspect of the game, allow users to turn off the chat facility so they don't have to read conversations that they consider offensive
* Allow users to ignore certain players
* Allow peer review. An additional advantage is this can also discourage other "bad" behaviour such as racism or trolling which is not based on word matching. Stack exchange is a great example of how this can work in practice.
* Some games have force users to pick from stock phrases. This is generally perceived as boring, but can be appropriate in some situations.

None of these suggestions will outright prevent bad words, but they can go a long way to helping you keep your game clean.

# Answer
> 3 votes
It's effective in these kinds of systems to show the original words to the user who made the input, but the scrubbed version to everyone else.

# Answer
> 2 votes
One simple option is to have a text file that contains a list of all words and phrases that you want to block. Scrub the input prior accepting it by checking it against the list of words in that file.

File contains:

```
Apple
Pear
Banana

```

Then scrub the input like so (pseudocode):

```
if(!blockedWords.Contains(input))
    // accept input and do whatever you need to
else
    print 'Hey, be nice!'

```

If `input` is "Apple", the `blockedWords` array read in from the text file will contain it and throw up the message.

---
Tags: browser-based-games
---


# Question
Title: If you make a game for facebook do you have to have a "real website" on the domain name?
Can you just use the domain to house your database and code? Do you have to have a "real" front end webpage?

# Answer
I think what you're asking for is "do you need a complete website with index page and links, or can you just host game.html". If I'm right the answer is: no you don't need a real website. Aslong as facebook can access the game, and it is playable you're fine.

I would not recommend it though, what if a player goes straight to that link in his browser (www.website.com/game.html) but isn't online on facebook, does that affect how the game plays?

Useable for minigames that don't need usernames though.
> 4 votes

---
Tags: browser-based-games, facebook
---


title: Settlers-like terrain representation

text:
# Question
Title: Settlers-like terrain representation
Remember this beauty? I'm playing it now on my old Amiga 1200.

My question is: How do you think they represented the terrain, data structure wise? Obviously it's some kind of points, with a height. Or hexagons. And how did they decide which dots were buildable?

**EDIT:** I could rephrase the question to say "how do I achieve this kind of terrain", but I would still only be interested in how to do it on a machine with 1 MB of RAM and a 7 Mhz processor, because this is the machine i currently developing games for. If that seems like a vague or meaningless question to you, that's alright, but I'm still curious if someone has any knowledge about this.

# Answer
> 3 votes
You could check Widelands, it's an open source remake of Settlers and they have a wiki page where they explain how they made the terrain.

---
Tags: data-structure
---


# Question
Title: Use current Vector2 variable and add value?
If I have a Vector2 variable, like this:

```
Vector2 fuellevelPosition = new Vector2(50, 750);

```

and I want to use that position for another object and also add 30 pixel to the X value for the position of the new object, how do I do that?

This didn't work:

```
Vector2 fuellevelTextPosition = new Vector2(fuellevelPosition.X + 30, fuellevelPosition.Y);

```

EDIT:

The code I use in the beginning of Game1.cs

```
 Vector2 fuellevelPosition = new Vector2(50, 750);
 Vector2 fuellevelTextPosition = new Vector2(fuellevelPosition.X + 30, fuellevelPosition.Y);

```

# Answer
> 3 votes
Try something like this.

```
Vector2 fuellevelPosition = new Vector2(50, 750);
Vector2 fuellevelTextPosition = fuellevelPosition + new Vector2(30, 0);

```

Why didn't your current code work? It should.

**Edit Based On Your Edit**

You can't use fuellevelPosition before it's initialized. Assuming that those two lines of code are inside the Game1 class, just assign them for now, like so.

```
Vector2 fuellevelPosition;
Vector2 fuellevelTextPosition;

```

Then, in the constructor function for Game1 set the variables, like so.

```
public Game1()
{
    fuellevelPosition = new Vector2(50, 750);
    fuellevelTextPosition = fuellevelPosition + new Vector2(30, 0);
}

```

---
Tags: xna
---


title: 2D Mask antialiasing in xna hlsl

text:
# Question
Title: 2D Mask antialiasing in xna hlsl
I have two texture2d , one of these is a mask texture and have 2kind color and i use that for mask (filter) second texture2D something like

```
     float4 tex = tex2D(sprite, texCoord);
float4 bitMask = tex2D(mask, texCoord);
if (bitMask.a >0)
{
 return float4(0,0,0,0);
}
else
{
      return float4(tex.b,tex.g,tex.r,1);
}

```

but because mask texture is just two color the result is too jagged i want know how i can do some antialiasing for edges that smooth these ty for reading and sry for my bad english

# Answer
> 1 votes
Based on your code example, it looks like you use the alpha channel in your bitmask to determine whether or not to draw a pixel. It also looks like you treat an alpha of `0` as "draw the pixel" and anything `> 0` to "not draw the pixel." I'm also going to assume that in your bitmask, you can make anti-aliased edges in the alpha channel where the alpha value is between `0` and `1` (exclusive). If any of these assumptions are incorrect let me know.

Now, assuming the above is true, you should be able to do this simply by using this code:

```
float4 tex = tex2D(sprite, texCoord);
float4 bitMask = tex2D(mask, texCoord);
return float4(tex.b,tex.g,tex.r,1 - bitMask.a);

```

Remember, `float4(0,0,0,0);`is actually drawing a black pixel to the screen but since the alpha channel is set to `0`, it's transparent. So, rather than drawing a black pixel, we'll continue to draw the regular pixel colour and just change the alpha channel on it. By using `1 - bitMask.a`, we're saying "when the bitmask alpha == 1, don't draw the pixel". This is what you were already doing with `if (bitMask.a >0)`. However, if the value is less than `1`, but not `0` we still draw the pixel, it will just be semi-transparent. Likewise, if the value is equal to `0`, it will fully draw the pixel.

Hope this helps!

**Edit**
How is the bitmask generated? I think it would be easier and more efficient to pre-calculate the different alpha values in the bitmask texture rather than dealing with edge detection in the shader. If you really want to do it in the shader, you could try sampling pixels within a certain distance from the current one (if the current one is not "blocked" (i.e. `bitmask.alpha == 1`) to see if they are blocked. And then, based on whichever blocked pixel is closest, you could set the alpha value based on the distance away.

For example, let's say you start by going up pixel by pixel for a maximum of 5 pixels or until you hit a blocked one. Then you would do the same thing for the right, down and left directions and possibly on the diagonals as well. After you do that, we'll say the closest blocked pixel is 2 pixels away. So the alpha is `2/5 == 0.4` (`2` being the pixel distances and `5` being the max distance checked).

In this way, if a pixel is 1 pixel away from a blocked pixel, it will have `0.2` alpha (`1/5 == 0.2`) and will be mostly invisible.

---
Tags: xna, hlsl, fragment-shader, antialiasing
---


# Question
Title: What Javascript game engines are out there, other than Impact?
Does anybody know of a decent (*meaning* preferably free `;)`) alternative to Impact? Any suggestions are very much appreciated!

# Answer
> 2 votes
There are a few here's a list of some:

Crafty (open source)

MelonJS (open source)

LimeJS (open source)

These are all free, and seem fairly finished. I don't know much about the Lime and Melon, but Crafty has a decent community where you can get help in their forums. Which you choose depends on what you need.

# Answer
> 3 votes
Here's a lengthy list: https://gist.github.com/768272/.
Here's something I'm making: https://github.com/Yannbane/Irenic.

# Answer
> 1 votes
Playin looks pretty good. It's free and open-source game library from Google. It was used for conversion of Angry Birds to Chrome browser. Games written in *playin* should run both in Chrome and Android phones.

---
Tags: javascript, html5, editors
---


title: iOS - pass UIImage to shader as texture

text:
# Question
Title: iOS - pass UIImage to shader as texture
I am trying to pass **UIImage** to GLSL shader. The fragment shader is:

```
varying highp vec2 textureCoordinate;

uniform sampler2D inputImageTexture;
uniform sampler2D inputImageTexture2;

void main()
{
  highp vec4 color = texture2D(inputImageTexture, textureCoordinate);
  highp vec4 color2 = texture2D(inputImageTexture2, textureCoordinate);

  gl_FragColor = color * color2;

}

```

What I want to do is send images from camera and do **multiply blend** with texture. When I just send data from camera, everything is fine. So problem should be with sending another texture to shader. I am doing it this way:

```
- (void)setTexture:(UIImage*)image forUniform:(NSString*)uniform {

  CGSize sizeOfImage = [image size];
  CGFloat scaleOfImage = [image scale];
  CGSize pixelSizeOfImage = CGSizeMake(scaleOfImage * sizeOfImage.width, scaleOfImage * sizeOfImage.height);

  //create context
  GLubyte * spriteData = (GLubyte *)malloc(pixelSizeOfImage.width * pixelSizeOfImage.height * 4 * sizeof(GLubyte));
  CGContextRef spriteContext = CGBitmapContextCreate(spriteData, pixelSizeOfImage.width, pixelSizeOfImage.height, 8, pixelSizeOfImage.width * 4, CGImageGetColorSpace(image.CGImage), kCGImageAlphaPremultipliedLast);

  //draw image into context
  CGContextDrawImage(spriteContext, CGRectMake(0.0, 0.0, pixelSizeOfImage.width, pixelSizeOfImage.height), image.CGImage);

  //get uniform of texture
  GLuint uniformIndex = glGetUniformLocation(__programPointer, [uniform UTF8String]);

  //generate texture
  GLuint textureIndex;
  glGenTextures(1, &textureIndex);
  glBindTexture(GL_TEXTURE_2D, textureIndex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

  //create texture
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pixelSizeOfImage.width, pixelSizeOfImage.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData);

  glActiveTexture(GL_TEXTURE1);
  glBindTexture(GL_TEXTURE_2D, textureIndex);
  //"send" to shader
  glUniform1i(uniformIndex, 1);

  free(spriteData);
  CGContextRelease(spriteContext);
}

```

Uniform for texture is fine, **glGetUniformLocation** function do not returns -1. The texture is PNG file of resolution 2000x2000 pixels.

**PROBLEM:** When the texture is passed to shader, I have got "black screen". Maybe problem are parameters of the **CGContext** or parameters of the function **glTexImage2D**

Thank you

# Answer
glGetUniformLocation returns a glint, so it probably is returning a -1, but it get converted to a uint.
> 1 votes

# Answer
You may want to use the GLKit framework. In particular GLKTextureLoader.
> 1 votes

# Answer
You should try this code with texture where resolution is power of 2 for each side (512x512, 256x1024 for example..). And max texture resolution in OpenGL ES for iPhone 3GS is 1024x1024, dont forget it.
> -2 votes

---
Tags: textures, ios, glsl, opengl-es2, fragment-shader
---


title: Quaternions - how to limit axis?

text:
# Question
Title: Quaternions - how to limit axis?
Is there any possibility to limit quaternions to move only in x & y axis (like in Eulers- yaw and pitch, without rolling)? I's there any equation or something similar to do this?
Some example:
Movement should behave like this: http://360.art.pl/experimental/1/
But when I build my player on quaternions it have no limits and I don't know how to fix it http://360.art.pl/experimental/2/

# Answer
Don't use quaternions. Store yaw and pitch Euler angles, and convert to a quaternion if you need to (for supplying to another piece of code, for example). There are no real advantages to using a quaternion like this (this set up cannot get into a gimbal lock, for example).

If you feel the *need* to use a quaternion, use two: one to represent the pitch and one to represent the yaw. If you ever permanently compose them, you'll have to decompose them at some point to apply the constraints. (Note that two quaternions, one for pitch and one for yaw, is really just obfuscated Euler angles.)
> 4 votes

# Answer
UPDATE: As pointed out in one of the other answers, you could use Euler angles. Actually, when analyzing the solution given in the first web application, we can see that this is how they do it. They're computing latitude and longitude (spherical coordinates) and from then on, they move by rotating a gimbal rig.

You can picture this imagining that the z axis of a frame is pointing towards the ceiling and NEVER moves (can only rotate in place, spinning). Now, you weld an y axis to this z one and let that axis support a ring. Z and Y must be perpendicular. Denote a point X on the cross product end of YxZ. That's where your camera can point. Now try to derive the mathematical equations that allow you to cover the whole sphere by first rotating against the Z, then against the Y axis. REMEMBER: the Y axis has rotated as well, so it's not correct to name it (0,1,0) or whatever convention you have for a world axis. It's actually something in the likes of (cos(t), sin(t), 0), where t is the longitude coordinate of a spherical coordinate system. On the other hand, Z does remain fixed and you can call it (0,0,1) (or, again, whatever convention you choose).

Mathematically, to rotate the camera you can first apply a rotation R\_z(deltaLongitude) followed by an R\_Y(currentLongitude) (endLongitude - currentLongitude).

longitude is an angle in radians, in the \[0, pi) interval, whereas latitude is in the (0, pi) interval.

The only advantage of this rotation system is that it's easier for the human brain to accommodate to: it's pretty much how our head pan/tilts. Our entire body, perpendicular on the ground is the Z axis I was talking about, while the Y axis is free to rotate perpendicular to this axis (picture it as the your shoulder line when it is in its rest position :D).

Quats are very similar to an angle-axis representation, nothing more.

So if you apply a quat, you imply that the result is the input rotated against the quat's axis by the specified angle.

What does that tell us?

It tells me this: that the quat's axis must be perpendicular to the camera's lookat axis in order to not rotate the camera against this look at ray.

If the axes are not perpendicular, there will be a roll component taking its toll, and hence the OPs problem.

If required, I could provide further details (a 3D rep maybe?). This link does explain a trackball rotation concept and how to implement it..
> 0 votes

---
Tags: javascript, quaternion, three.js
---


# Question
Title: Player's feeling towards stage selection in a platform game
In a 2D platform game with RPG elements (not that it matters much), there's three ways, among others, for the player to choose the next stage he will play:

1. He can only play the next stage and the ones he already beat
2. On game start, half of the stages are open, and the other half is released when he beats the first half
3. All stages are available to the player

What's the difference in perspective to the players general experience and his feelings towards a game rating of these three alternatives?

(I know it sounds like a copy of an exercise, but it isn't. I did this way so people may take this question in a more academic way)

# Answer
The main objective here is to find a suitable progression system which allows a sense of progression, a proper difficulty curve, and a controlled release of game mechanics, without the roadblock problem of a player reaching a point they can't progress past and getting frustrated.

The latter problem can be ameliorated by RPG-elements, if grinding past a difficulty is possible (true for getting through enemy mobs, not necessarily true for platforming challenges). However, there are other ways of addressing this, and option 2 is a subset of those. Some examples of games which do it well:

* Super Mario World: starts off linear, but the map very quickly starts diverging, which means that most of the time there are multiple points of progression. Furthermore, the existence of secret exits encourages replay of old levels.
* Super Meat Boy: you can play any level from the latest world you've reached, and can face the boss after beating only a subset of the levels in that world, meaning any given level won't ever stop you from progressing. Beating levels within a time limit then unlocks a harder version of that level
* Super Mario 3D games: beating a level earns you a star, and access to each group of levels is gated by your total number of stars.

One thing that's common to these games is that whilst they offer divergent options, they also have convergence points - a single point that must be passed to progress to the next section, usually a boss. This is actually really important, in order to give the game a sense of structure, milestones of progression.
> 4 votes

# Answer
This is kind of a cop-out answer, but I would say that all of them have their pros and cons (like much in life).

Option 1: I feel that this is the weakest option. Players will be forced to play the newest level or the levels that they've probably already learned and crushed. There is no way for the player to take a break from banging their head against a new level while simultaneously making progression. It's either suffer the next level or farm (for lack of a better term) the previous levels (boring).

Option 2: This option reminds me of Mega Man stage selects where you can pick multiple stages in case you need to get an item from one stage to use in another or just want a change of pace after getting your ass kicked on Stage X. At least in this case the user can try to progress without feeling stuck.

Option 3: Truly laissez faire. It kind of ruins progression a bit when there's nothing to give you that "finally I can go to that stage I've seen locked!" feeling. Maybe not everyone likes unlockables, but I think in order to trigger some sort of feeling of accomplishment, you need to allow the user to have the satisfaction of going to the next area as a direct result of their work.
> 2 votes

# Answer
I find the Mega Man series of games has usually been a mix of all 3. Select any stage, and after finishing them, you are given a set of more difficult stages that are linear in progression. Seasoned players have figured out there's sort of a puzzle to the best order of beating the bosses/stages, as the order of weapons you obtain present better options to tackle future stages. If you can work out a challenge based around the order in which the stages are beaten, this could be a fun way to play the game.

In other cases, the game has no apparent barriers to let you explore the whole world at first, but the extent to which you can explore it is limited by your character's abilities. This is common in RPGs, but also in Metroid/Metroidvania type of games. The world should be set up in a way in which the player would have to figure out where to go next, but without getting lost. If the process of elimination is made easy for the player, he would know where to go next and incidentally obtain an item that will let him pass through to places he previously couldn't go before.

The replayablity of the stages depends on whether or not it is worth the player's time to visit old stages with their newer abilities. You'll have to give him an incentive to go back, either by teasing the player with visible but out of reach areas during the first run, or some storyline component that calls for some backtracking.
> 1 votes

---
Tags: game-design
---


# Question
Title: Algorithm for creating adjacent triangles
I have a system where you can click once to place a node in a scene. When you place 3 nodes, it forms a triangle. When you place any future nodes, it creates a new triangle by joining that node to the 2 nearest existing nodes.

This works fine most of the time but is flawed when used near triangles with very acute angles, because one of the 2 nearest nodes is often not one that should be used.

For example, see the image below. The magenta triangle is the first one placed. If I then click at the position marked X, what I get is a new triangle where the blue overlay is. What I want is a new triangle where the green overlay is. (ie. symmetrical to the magenta one, in this example. Clarification: The green and magenta triangles don't overlap - the green one extends under the blue one to the left-most node)

How can I determine which 2 existing vertices to use when creating new triangles so that triangles are not superimposed like this?

**EDIT**: Searching for the nearest edge gives *better* results, but not perfect ones. Consider this situation:

The 'nearest edge' test is ambiguous, and can return AB or AC (as the nearest point to X for both is at A). The desired result would be AC, to form the ACX triangle with no edges overlapping. How could I ensure this result? (I'd rather not have to perform individual edge overlap tests as a tie-breaker if possible as I'm concerned that the nearest edge test won't necessarily spot the 2 are exactly equidistant, given floating point precision issues.)

# Answer
> 11 votes
Rather than finding the minimum distance to the nodes, find the minimum distance to the edge (ie the line segment defined by the nodes).

Then, if the nearest point is a vertex (which you'll have to use some floating point epsilon\** test), compare the angle between the line from new point to the vertex and each of the edges connected to that vertex. Choose the one with the minimum absolute angle:

```
MinAngle(newPoint, vertex, edge1, edge2)
{
   newEdgeUnit = norm(newPoint - vertex); // don't actually need to normalize this
   edge1Unit = norm(edge1 - vertex);      // you probably have these from your dist to line tests
   edge2Unit = norm(edge2 - vertex);

   edge1Dot = dot(edge1Unit, newEdgeUnit);
   edge2Dot = dot(edge2Unit, newEdgeUnit);

   // you can simply compare dot products to find the minimum absolute angle
   if (edge1Dot > edge2Dot) return edge1;     // set up this way so you can generalize to an array
   return edge2;
}

```

\** To avoid adding degenerate triangles, which might disrupt the epsilon test, you might want to put a region around each vertex where adding points is disallowed, (something like disallowing points within some multiple of the epsilon used above).

# Answer
> 6 votes
After the first triangle is placed, when placing a new vertex, you will always generate two new edges. The third edge for the new triangle will always be a shared edge with a previous triangle. If you could find a way to determine the shared edge, you'd know which vertices to connect to, but that's the hard part. I believe one way you can do this by drawing a line from your new vertex to the center of each of the last three edges generated (or probably the 3 nearest edges).

If the line from your vertex to the center of the edge does **not** cross either of the other two edges, you have your shared edge. The shared edge will tell you which two vertices to connect your new vertex to.

Jimmy brought up the case for a point that is ambiguous as to where the new triangle would go like this:

That would give you the opportunity to choose between two valid triangles. Perhaps the tie breaking being which center point is closest.

Considering your update, while more complex, my solution will only result in a tie when you have two valid triangles. Using this method your second example image would produce the result you want.

# Answer
> 1 votes
Having your magenta triangle ABC, you then incorporate a new vertex X. I think it is obvious that there will be two lines starting at D that will not intersect between any of the edges of the triangle ABC.

These two lines could be AX & BX, BX & CX or AX & CX. You can then treat your problem as the classical problem of "do two lines intersect"? You can then check which of this pairs of lines does not intersect with any of the ABC triangle edges following, for example, any of the methods from this question. Hence, you will have the two new edges of the new triangle.

# Answer
> 1 votes
Figuring out if you're in one of the unambiguous regions (1, 2, 3 below), is fairly easy: treat each edge of your triangle as a 2D plane and test which side of the plane your new point is on. If you're inside two of them but outside one, then that one corresponds to the edge of the triangle that contributes two vertices to your new triangle.

If you're inside one and outside two, you're in the ambiguous case where the nearest part of the triangle to your new point is a corner. In that case, you can form a 2D plane from the midpoint of the opposite edge (the one that you're inside of) and the nearest vertex (the one shared by the two planes you're outside of). You can pick an edge depending on which side of this plane your new point is on.

Note that a plane test in 2D works the same way as in 3D: dot a vector from anywhere on the plane to your point with the plane's normal (in 2D, this is the line's perpendicular).

(Incidentally, the magenta-delimited regions in this image are called Voronoi regions; they're the areas of space containing points that are closest to a particular feature—edge or vertex—of the triangle. **Edit:** My terminology here isn't actually quite correct, these aren't exactly Voronoi regions.)

---
Tags: algorithm, geometry
---


# Question
Title: Implementing audio for a game made using JMonkey?
Is it possible to implement music/SFX in game made using JMonkey? If yes, how did you do it? What did you use?

# Answer
> 3 votes
http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello\_audio

Admittedly I don't have a ton of experience with JMonkey, however this page seems to have enough information to explain the system.

From what I can read, JMonkey's audio system uses a listener/source system. Regardless, it seems simple enough to implement and should be a fairly trivial task.

Edit: After reading the article, I'll try to explain it more here:

Each sound uses an instance of AudioNode, created like this:

```
AudioNode nodey;

```

To load the sounds themselves, simply create a new instance like so:

```
nodey = new AudioNode(assetManager, "a-file.wav", false);

```

The true/false sets if the sound will be streamed or not. For long sounds (think things like in-game Music,) this should be set to true, however shorter sounds, this should not be streamed.

Once you load the sound, you can then attach to the root node, and then either play it using play() or playInstance():

```
rootNode.attachChild(nodey);
/** Repeat playing if sound is ambient (Waterfall, wind etc.) [Note: nodey.setLooping(true) should be called before adding to the root node if the sound will loop] */
nodey.play();
/** Play as instance (Footstep, Gunshot, etc.) */
nodey.playInstance();

```

For playback, a "listener" object must be created, and said "listeners" proprieties should be updated as the camera moves.

---
Tags: audio
---


# Question
Title: Collision on the first rectangle only - Why?
I've made a very simple collision detection, it works fine. However, when I decided to load in all my rectangles into a list and then give each of them collision, it only adds it to the first one. Any ideas? I've tried it with a for loop as well.

Here's the code:

```
    Rectangle interaction, interaction2, interaction3;

    List<Rectangle> collisionList = new List<Rectangle>();

        public GamePlayScreen()
            {

                interaction = new Rectangle(200, 200, 32, 32);
                interaction2 = new Rectangle(400, 200, 32, 32);
                interaction3 = new Rectangle(200, 400, 32, 32);

                collisionList.Add(interaction);
                collisionList.Add(interaction2);
                collisionList.Add(interaction3);

            }
    // This right here is just to show you guys that it is getting updated.
    // This is not the real update, I refrained from posting that since it might confuse
    // people.
    public override Update(GameTime gameTime)
    {
    CheckCollision();
        }

     float xx;
     float yy;

        private void

CheckCollision()
            {
                foreach (Rectangle rect in collisionList)
                {
                if (player.Sprite.Bounds.Y > rect.Top - 33 && player.Sprite.Bounds.Y < rect.Bottom && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.X > rect.Left - 30)
                {
                    player.Sprite.position.Y = yy;
                }
                if (player.Sprite.Bounds.Y < rect.Bottom && player.Sprite.Bounds.Y > rect.Top && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.X > rect.Left - 30)
                {
                    player.Sprite.position.Y = yy;
                }
                if (player.Sprite.Bounds.X > rect.Left - 30 && player.Sprite.Bounds.X < rect.Right && player.Sprite.Bounds.Y > rect.Top - 30 && player.Sprite.Bounds.Y < rect.Bottom)
                {
                    player.Sprite.position.X = xx;
                }
                else
                {
                    xx = player.Sprite.position.X;
                    yy = player.Sprite.position.Y;
                }
                }

            }

    //The Draw method

    spriteBatch.Draw(scrollDownButtonNormal, interaction, Color.White);
                spriteBatch.Draw(scrollDownButtonNormal, interaction2, Color.White);
                spriteBatch.Draw(scrollDownButtonNormal, interaction3, Color.White);

```

I will of course continue to work on this, and post a solution if I find one.

~Etarnalazure

*UPDATE* Just checked with a boolean if the other boxes react, it changes to true. So it means it works just fine (I put the boolean in between each if loop to check if it registered any collision).

# Answer
> 0 votes
I've found the answer to the question, it was rather simple honestly.

By putting this:

```
 xx = player.Sprite.position.X; yy = player.Sprite.position.Y;

```

instead of this:

```
else { xx = player.Sprite.position.X; yy = player.Sprite.position.Y; }

```

It worked just fine (I put it outside the Foreach loop as well).

# Answer
> 0 votes
Have you tried to use the `Intersect` method of `Rectangle` structure? I don't' know if it resolves your problem but maybe it may be useful to see if your collision algorithm is working well. So, for example, if `Bounds` is a `Rectangle` you could do:

```
if (player.Sprite.Bounds.Intersect(rect))
 ...

```

---
Tags: 2d, collision-detection
---


title: How to save game progress (savefile)

text:
# Question
Title: How to save game progress (savefile)
I am currently working on a terminal text game just to practice my skills (C). It will be story driven escape the mansion kind of game. Even though the game will be short I want it to support save files.

Since I am new to game programming I am not sure how should I handle save files. The game will be short yet players will be able to find a lot of objects. I was thinking about saving a structure into a .txt file OR saving lots of 1 and 0 into txt file. Where each line represents each item or progress.

Is there a better way or common way how to do it?

# Answer
Saves do not usually need readability, so it's good to save them binary format. If object interactive, you should save all non-calculated fields to file, as I suppose you have multiple locations. So there will be saves for each location and hero saves (inventory, active tasks). There are many related questions. related topic
> 5 votes

# Answer
From my small experience, one of the best ways of saving a game is using XML. You can see what is happening, you can change the save files, you can even prepare then to be used for map editors. Finally, in the end, you could always put then in the binary form.
> 0 votes

# Answer
```
fprintf( fd, "format",  ...); /*save*/
fscanf( fd, "format", ...); /*load*/

```

Where ... represents variables and "format" describes how they are formatted.
> 0 votes

---
Tags: c, savegame
---


# Question
Title: What data should a generic collision detection system gather?
I'm working on a relatively generic 2D AABB collision detection system for a game engine, and I've re-written it more times than I'd like to admit, due to not calculating or recording specific details of each collision. Right now, this is what I'm collecting:

* Collision time as a fraction of an update cycle in the game loop.
* Location of the collision.
* ID of the colliding object.

Each object has a `Set` that holds this data for each collision (I'm working with a component/entity system) so other systems can use the recorded data. The problem I just ran into was that I needed to know which side of the object the collision takes place on.

What other values or points of interest should I calculate or record, per collision? What do you look for in a standard collision detection system?

# Answer
It depends.

What factors into the collision resolution? Depending on how sophisticated you want the engine to be, you may want to know the velocity at time-of-impact, which objects were involved in the collision, as well as many other factors. This is where I would give you the advice to **write games, not game engines**.

If you write a game, you can know what you need to support. If you write a game-engine, you have to make decisions like these, on what you're going to support and what you're not going to support.

If you're creating a game like Braid, where you can manipulate time, you might need to know everything you did, in order to undo the collision.
> 3 votes

---
Tags: collision-detection, entity-system
---


# Question
Title: Why does my frames per second function return inconsistent results?
I have a FPS function that:

```
private static void runGameFPS2() {
    long beginTime; //The time when the cycle begun
    long timeDiff; //The time it took for the cycle to execute
    int sleepTime; //ms to sleep (< 0 if we're behind)
    int fps = 1000 / 40;

    beginTime = System.currentTimeMillis();

    //Update game state
    updateGame();
    //Render state to the screen
    renderScreen();

    //Calculate how long did the cycle take
    timeDiff = System.currentTimeMillis() - beginTime;

    //Calculate sleep time
    sleepTime = fps - (int)(timeDiff);

    if (sleepTime > 0) {//If sleepTime > 0 we're OK
        try { Thread.sleep(sleepTime); }catch(InterruptedException e){}
    }else{
        //suppose will not be
    }
}

public static void main(String[] args){
    while(true){ runGameFPS2(); }
}

```

When I run my code, Java works at different speeds on same computer or on different computers.

How can I write a consistent code, that Java will always work "same time" (for example 40 FPS) on mycomputer or any computer?

Note: suppose `sleepTime` will never be `sleepTime < 0`

# Answer
System.currentTimeMillis() isn't a very good method to use for this sort of timing as it only has a resolution of 16ms on Windows based systems.

Try using System.nanoTime() / 1000000 instead, and see if that makes it better.

You could also switch to using nanoseconds entirely, there is a Thread.sleep(long, int) that takes nanoseconds.
> 6 votes

# Answer
Your problem might be that you're calling `sleep()` on each loop. I don't think `sleep()` is high precision, meaning it may deal in 16ms increments on Windows also, like `System.currentTimeMillis()`.

Your best bet is not to sleep in the main loop. Try just running it without sleeping and see if the timing is still inconsistent.

**EDIT:**

You control the speed by calculating how far the box has moved during the frame. The basic formula is `distance = speed * time`, so the speed of the object multiplied by the time between frames gives you the object's change in position between frames.

For example, if you want the box to move 100 pixels per second, then do a calculation like:

```
// get time since last frame
currentFrameTime = System.currentTimeMillis();
timeBetweenFrames = currentFrameTime - lastFrameTime;
lastFrameTime = currentFrameTime;

// calculate distance change and new position
distanceX = 100 * (timeBetweenFrames / 1000);
box.x += distanceX;

```

Just be sure to get your units the same (that's why we divided `timeBetweenFrames` by 1000, since it's in milliseconds).
> 5 votes

# Answer
Sleep itself is not a good method to use for anything in a game loop, and is even worse for use as an FPS limiter - the only realistic use case for it is if you have an absolute power-saving requirement that is considered more important than timer accuracy.

Reason why is that Sleep fails on two counts. First it is a low-precision timer itself, using (again) an approx. 16ms resolution. Second it only guarantees a *minimum* time to sleep for - the actual time it does sleep for can be any arbitrary time-span above this.

If you want to limit frame rate, do so based on accumulated time or on vsync, but never use any Sleep call for this purpose.
> 4 votes

# Answer
Sleeping can't promise a precise come back. That is handled by the scheduler of the JVM as well as the Operative System. It's impossible to accomplish it that way. You must accept the fact you can't control it and compensate for over sleeping as well.

The most complete way to make it work is by this piece of code extracted from the book "Killer Game Programming in Java". It does all this:

* Makes sure that you work at the desired frame rate consistently across any computer.
* Divides updating the game state from actually rendering it
* Releases the current thread if it finished updating and rendering the frame in less than the required time. It also releases the current thread in case it is hogging the CPU because it didn't have extra time.
* Handles the case where it overslept and tries to catch up
* In case it takes longer to make update and render for a given frame it takes note. Then it will skip the rendering but will do an update. If too many renderings are being skipped it will perform a rendering even if it still didn't catch up so the image doesn't freeze.

It's the most solid update/render loop I have come across in several years.

```
// Desired frames per second
private static int FPS = 60;
// nanoseconds per frame
private long period = 1000000000L / FPS;
private boolean running = true;
// no. of frames that can be skipped in any one animation loop
// i.e the games state is updated but not rendered
private static int MAX_FRAME_SKIPS = 5;
/**
 * Number of frames with a delay of 0 ms before the animation thread yields to other running threads.
 */
private static final int NO_DELAYS_PER_YIELD = 16;

/*
 * Repeatedly update, render, sleep so loop takes close to period nsecs. Sleep inaccuracies are handled.
 *
 * Overruns in update/renders will cause extra updates to be carried out so UPS tild== requested FPS
 */
public void run() {
    long beforeTime, afterTime, timeDiff, sleepTime;
    long overSleepTime = 0L;
    int noDelays = 0;
    long excess = 0L;

    beforeTime = System.nanoTime();

    running = true;
    while (running) {
        gameUpdate();
        gameRender();
        paintScreen();

        afterTime = System.nanoTime();
        timeDiff = afterTime - beforeTime;
        sleepTime = (period - timeDiff) - overSleepTime;

        if (sleepTime > 0) {   // some time left in this cycle
            try {
                Thread.sleep(sleepTime / 1000000L);  // nano -> ms
            } catch (InterruptedException ex) {
            }
            overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
        } else {    // sleepTime <= 0; frame took longer than the period
            excess -= sleepTime;  // store excess time value
            overSleepTime = 0L;

            if (++noDelays >= NO_DELAYS_PER_YIELD) {
                Thread.yield();   // give another thread a chance to run
                noDelays = 0;
            }
        }

        beforeTime = System.nanoTime();

        /*
         * If frame animation is taking too long, update the game state without rendering it, to get the updates/sec
         * nearer to the required FPS.
         */
        int skips = 0;
        while ((excess > period) && (skips < MAX_FRAME_SKIPS)) {
            excess -= period;
            gameUpdate();      // update state but don't render
            skips++;
        }
    }

    System.exit(0);
}

```
> 2 votes

---
Tags: java
---


# Question
Title: Benefits of implementing systems like classes instead of just functions
In an Entity System I am making, there is a central class called `World`, which stores all component instances. It's a dictionary-of-arrays, and entity ids are indexes for the arrays.

To access a component of an entity with `id = 3` you would do this: `world.storage["ComponentType"][3]`.

So, each loop of the game, these arrays would be fed to their respected systems ( `movement(world.storage["Position"], world.storage["Velocity"])` ).

Now, I don't see why systems couldn't be implemented just as functions, as I showed. **What optimizations can be made by using classes with data and methods (caching)?**

Also, these systems would need to iterate over all the entities that exist, doesn't this make entity frameworks much slower than regular inheritance based engines? Why do some people "register" systems to the `World` class?

# Answer
> 1 votes
> What optimizations can be made by using classes with data and methods (caching)?

On a logical level, `x.y()` is completely equivalent to `y(x)`, and in most languages is pretty much implemented exactly that way. The only benefit you get is that your language might treat member variables as locals within methods, so that you save some typing. eg. Java and C++ do this, Python does not.

On a practical level, where the data is located makes a difference to the speed of access. Unfortunately how much difference and how to influence this is 100% dependent on the language you are using. But in general, if you can ensure that data that is used together or used sequentially is stored closely together, and if your language is low level enough, you can see some significant performance increases.

> Also, these systems would need to iterate over all the entities that exist, doesn't this make entity frameworks much slower than regular inheritance based engines?

No, because again the systems are logically equivalent. The traditional system would iterate over all entities, and for each entity, would iterate over each element of functionality that needs processing. (The iteration may be implicit in that there would be a sequence of function calls.) The component system starts with the element of functionality and iterates over each entity that uses it. Exactly the same code gets called, just in a different order.

There's no free lunch - to get the same results you do the same work in all systems. The only difference is how you want to organise it all.

# Answer
> 1 votes
I am using a component/subsystem architecture in my current system for multiple reasons.

1. I want to operate on batches of like data in order to optimize cache hits. If I store my components in the subsystems I can do this but I have to have logic somewhere to create the correct components and attach them to the entity messaging system. In some systems this is done in the world model, so the subsystems need to be registered. In my system I have a separate engine class handling it. There is a BehaviorTypes enum to determine what kind of behavior is being requested or provided.
2. I want to avoid data sharing problems without violating encapsulation by passing needed data in message parameters. I do this by making my entities an ID, a messaging system and a collection of behavior data components. These components are processed by the subsystems and the entity is notified of changes to it's member components through OnChanged type events. The components are physically located within the subsystems. Additional subsystems can register their interest and have these components passed through appropriate event arguments in order to provide additional behavior (ex. Animation advances in response to a position or velocity change). These relationships are established when a subsystem registers with the engine (in my system the WorldModel object is a singleton in the engine.
3. I want to be able to vary the entity data and subsystem data processing independently. This way if I decide to change my pathfinding system or change the tiles to hexagons, I can do so without disturbing the rest of the system.

---
Tags: software-engineering, game-loop, entity-system
---


# Question
Title: How to handle input for both UI and game
So I originally had my input system set up with only the game part in mind. It listens to keyup/down events, marks the key as pressed/unpressed and then when the next update comes around, it sends out the state, and marks the current state as the previous state.

When I started implementing more complex UI elements, I realized this was a problem. Textboxes want to be notified of repeated keydown events so you can hold a key, scrollbars want repeated mouse down events, etc. On the other hand, the game only wants to know if a key is down and needs to keep track of the current/previous state for hotkeys and such.

What I would like to do is find a way to design the input system so it works for both cases. How can I support the repeating \*down messages that the UI needs while also maintaining a current/previous input state that the game needs?

It occurs to me that I could perhaps just separate the two, using the input state manager only for the game input while hooking the UI manager directly into the keyboard/mouse input events. To me this seems less-than-ideal. For one, it seems a bit sloppy to be hooking the input in 2 different places. Also, doing so would remove the ability to send the current/previous input state to the UI. I'm not sure if this is even needed for the UI though. Maybe I'm just over-engineering things? I would like to have that ability if it's needed though. How have other people set up their input systems in such a situation?

# Answer
There's no reason that the input system has to deal with repeat events. Your text input class can keep a timer and repeat keys itself if the key is held down. Same with scroll bars. Keep your state in the objects that care about them rather than pushing the logic into lower layers of the stack.

You can implement a reusable event state manage for GUI controls if you want to avoid code duplication.

Just store a repeat delay (how long the key/button must be down before repeat input occurs) and a repeat rate (how many repeat events should be sent over time).
> 1 votes

---
Tags: c#, input, slimdx
---


# Question
Title: How to create character avatars without lots of artwork?
I am writing a mafia RPG game where it is required to hire "goons" to be part of your family, I have about 10 "goon" avatars/artwork (+ retina) already and am hitting a problem.

The problem is that for every avatar I imply a character (with stats), so if I have,

```
avatar001.png = {Character: Bob Health: 100 Skills: ... }
avatar002.png = {Character: Mike Health: 100 Skills: ... }
avatar003.png = {Character: Alan Health: 100 Skills: ... }

```

The implication is that these 10 pieces of artwork I have are 10 specific characters, with specific names and stats.

This causes me a problem in that in order to get a good selection of goons, I'm going to need a lot more than 10 avatars; probably even in the hundreds if not thousands.

*Bottom line, To do this, it's going to be expensive.*

The way Tiny Tower did it was to have a template and use this, and I've thought of a similar solution -- a faceset generation tool, but I'm mot sure if its going to work; all the current goon avatars I have are custom designed and would not lend themselves to 1-4 generic face templates.

The only solution I have right now is to,

> Just use the 10 avatars I have and randomly generate the name, stats, class levels or whatever -- and don't worry about it.

But I don't know if this is good enough and I'm looking for alternative solutions -- how would you create character avatars without spending loads on literally thousands of avatars?

Thanks.

# Answer
> 4 votes
Right now, you are mapping avatars to characters. The first thing I would do is flip that around. In my game, I have the following:

* Every object that has to updated and rendered (e.g. Enemy, Player) is a `GameObject`.
* A `GameObject` holds different modules, like one for rendering, one for collision detection, etc.
* Each child of `GameObject` holds state unique to that child.

As a result, I can now serialize my objects using a blueprint. I'm using protobuf for this. In your game, you could have the following blueprint:

```
name: "Bob"
type: eGoon
health: 10
skill {
    type: ePunching
    quality: 70
}
skill {
    type: eStabbing
    quality: 60
skill {
    type: eRunning
    quality: 100
}

```

This will create "Bob", who is a bit of a glass cannon.

As you can see, it's now very easy to define new blueprints for your goons. But back to the problem at hand: unique artwork. It really depends on your type of game, but you could store it in the following manner:

```
avatar {
    background: 2
    face: 1
    nose: 1
    mouth: 2
    eyebrows: 3
}

```

Now you create a bunch of different backgrounds (sea, docks, city, etc.), a bunch of different face templates (large, small, wide, thin, thick, etc.) and a bunch of different facial features (large nose, thin eyebrows, small mouth, etc.). Now you can create your avatar by combining these features.

However, you will have to be careful that the features match with each other. In your game logic, you could put constraints in your random generator. For example: don't generate a small mouth when you have a big nose, because that looks silly.

# Answer
> 3 votes
If you really need that many avatars I would look into combinations (like police does when making faces of suspects). Have 3-4 face shapes/colors, 3-4 colors of eyes, 3-4 shapes mouths and noses, ears, etc.. Maybe some more distinct features (eyepatch, cigar, scar). However this way will require additional effort to hide the fact that they are stitched from half a dozen of patches.

In 3D I would suggest morphing like many 3D RPGs do these days.

---
Tags: art, rpg, character, avatar
---


title: Best practice for saving items?

text:
# Question
Title: Best practice for saving items?
In a game that I'm working on, any player has (at max) 460 items within their inventory. Each item has simple attributes, such as owner and quantity, but equips have different attributes, such as strength, dexterity, luck, intelligence, speed enhancement, jump enhancement, etc.. To save all the items, I have a column in a MySQL table for every item (meaning that equips also are categorized as items), and another table for extra equipment data.

The player has the ability to change the stats of any item, via obtaining more of a certain item, removing some of the items they have, scrolling an item to change its stats, and so on.

What I'm trying to figure out is - what's the best method to save all this information? Currently, what I do is delete all items that the player owns within the item table (which the equip table is linked to, so those entries get deleted too), and then insert the items that the player has. The issue with that is that there's a very high chance of players losing their items in the event of the server crashing, and it seems kinda odd to be deleting entries.

My new proposed method is to set a flag within each item's instance, and (for example), if the flag is 0, the item has not changed and does not need to be resaved, if it's 1 then some attribute has changed and needs resaving, and if it's 2, the item needs to be deleted from the database. I'm not sure if this is any better though.

Additionally, how often should I be saving the items? Right now it's done after important events (like quest completion), but what about saving on a timely basis?

# Answer
> 1 votes
You should be committing the delete of items and the insert of the items in a single database transaction so if there is a crash there is no risk of items being lost. With a transaction its all or nothing!!

http://dev.mysql.com/doc/refman/5.0/en/commit.html

# Answer
> 7 votes
First, let's separate your data. A player table could look something like this:

```
Player
------------------
id      INTEGER PRIMARY KEY AUTOINCREMENT
name    VARCHAR(255)

```

While an item table could look like this:

```
Item
------------------
id      INTEGER PRIMARY KEY AUTOINCREMENT
name    VARCHAR(255)

```

Note that I haven't added anything fancy like effects or whatnot. This is the minimum information required to identify a certain name. Note also that every row in both tables has a guaranteed unique identifier.

Now we want to map certain stats to an item. We will in fact need two new tables. First the Stats table:

```
Stats
------------------
id      INTEGER PRIMARY KEY AUTOINCREMENT
name    VARCHAR(255)
value   INTEGER

```

Let's say we have a potion that generates health. First we'll add it to the Items table:

```
Item
------------------
id      name
0       Potion of Health

```

And then we'll add its stat to the Stats table:

```
Stats
------------------
id      name            value
0       Boost Health    100

```

So how do we link the Stats entry to the Items entry? We use a map table:

```
MapItemStats
------------------
id          INTEGER PRIMARY KEY AUTOINCREMENT
item_id     INTEGER
stats_id    INTEGER

```

And we'll add an entry:

```
MapItemStats
------------------
id      item_id     stats_id
0       0           0

```

Now we can map items to stats. First we'll need the items:

```
SELECT Item.id, Item.name
FROM MapItemStats
INNER JOIN Item
ON MapItemStats.item_id = Item.id;

```

This query will give us the following result:

```
id      name                stats_id
--------------------------------------
0       Potion of Health    0

```

Not very interesting, but we can a more complicated query. First we'll save the result of this as a temporary table. Note that this is not valid SQL and purely for demonstration purposes.

```
(
    SELECT Item.id, Item.name, MapItemStats.stats_id
    FROM MapItemStats
    INNER JOIN Item
    ON MapItemStats.item_id = Item.id
) AS ItemTemp

```

Now we can use this temporary table for additional look-ups:

```
SELECT ItemTemp.id, ItemTemp.name, Stats.name AS stat_name
FROM (
    SELECT Item.id, Item.name, MapItemStats.stats_id
    FROM MapItemStats
    INNER JOIN Item
    ON MapItemStats.item_id = Item.id
) AS ItemTemp
INNER JOIN Stats
ON ImageTemp.stats_id = Stats.id;

```

This will give us the following result:

```
id      name                stats_name
--------------------------------------
0       Potion of Health    Boost Health

```

Now, when we change any of the properties of an entry in the Stats table, none of the other tables are affected. Because everything is stored only once, it's very easy to delete references to an object. This is referred to as database normalization.

In your question, you talk about player's inventory. Well, we'll use the same trick:

```
MapPlayerItem
------------------
id          INTEGER PRIMARY KEY AUTOINCREMENT
player_id   INTEGER
item_id     INTEGER

```

So if you want to remove an item from a player's inventory, you simply look up the record in this table and delete it. For example, this would clear the inventory of a player:

```
DELETE
FROM MapPlayerItem
WHERE player = 0;

```

However, there is a major downside: queries become increasingly complex and expensive as you add more properties. Therefor it's often a good idea to selectively denormalize a database. For instance, if you just want amount of items a player has in her inventory, it's a bad idea to do the whole mapping thing I did above. Especially when you have a lot of records, this becomes very expensive.

So we'll change the Player table:

```
Player
------------------
id                      INTEGER PRIMARY KEY AUTOINCREMENT
name                    VARCHAR(255)
cache_inventory_count   INTEGER

```

This entry is not guaranteed to be 100% accurate, but that's okay. We only have to change it when an item is added to or deleted from a player's inventory.

# Answer
> 1 votes
I suggest to have 3 tables.

The first: **Items** with the columns:

```
itemId
itemName
itemDescription
itemPrice
... etc

```

The second table: **Players** with the columns:

```
playerId
playerName
playerEmail
... etc

```

And the third table: **Inventory** with the columns:

```
playerId
itemId
itemQty

```

All tables are linked to each other by playerId, itemId

Executing SQL query by Inventory table you can get a list of items for a particular player. Also via SQL update query you can update `Inventory` table for a particular player according to a particular item.

Commit changes to tables on game milestones, for instance when an achievement is unlocked, or level is passed.

---
Tags: java, databases
---


# Question
Title: For a real-time PvP game, what network service would get the job done?
The game is between two players, real time, and has to be very synchronized - latency will certainly favor one player over the other. It's built for iOS and Android and every touch on one end has to be instantanious on the other end.

The game will be built on Corona SDK and I'm looking to use a service to simplify communication (even if it involves additional costs). I'm currently considering PubNub or Parse.

I'm new to game dev and this is my first real time game. Please be as specific as possible.

# Answer
Network Architecture is difficult. The problem is your never going to get "Instantaneous" clicks on both sides. There will be some lag, and most games get around this by accepting it and building the architecture around it.

For example, most first person shooters use prediction. They keep the entire game state and logic on both ends, but the server sends constant updates on every object in the game. Then, when you do something like shoot something on a client, your side calculates what happened, and then shows you the result. It also sends the event to the server, and the server "should" calculate the same result, since both computers have the same state. If it does, then it tells the client. The client says "tell me something I don't know" and moves on. If the server disagrees, then it updates the client with what really happened, and the player sees a guy they just shot in the head stand up and run away.

The latency will be even worse with mobile phones. From this question https://stackoverflow.com/questions/1097937/latency-on-mobile-networks-android it looks like you can expect anywhere from 80 ms to 3000 ms.

My advice would be to use the lock step client-client architecture that most RTS's favor. You run deterministic game logic on both ends, then only send user input back and forth. Then you delay the time between input and when the input is given to the game logic so it can by synchronized on all sides. For more info check out http://www.gamasutra.com/view/feature/3094/1500\_archers\_on\_a\_288\_network\_.php/.

Here is an article on how to write the network code for Corona SDK: http://developer.coronalabs.com/code/multiplayer-networking.
> 5 votes

---
Tags: android, ios, corona-sdk, pvp
---


# Question
Title: How to handle multiple game sessions where players turn can timeout, using Python and Socket.IO?
I want to make a multi player card game, allowing several people to play with each other (each game session should be able to have between 5 - 10 players).

I'm doing this in Python (Django and Socket.IO).

Because you have to wait for all players to finish before you can move on to the next round, issues will arise if one player leaves his computer or is disconnected, thus leaving all the other players waiting.

To solve this, I want to give each player a time limit to act within.

If there are 1,000 games going on at the same time, and 5 players in each game, that would hypothetically mean that at one point, you could have 5,000 timers counting down at the same time (or if not timers, some other way of dealing with this issue).

What is the best way to do this in Python? Spawn loads of threads with timers? Have something more complex like a dictionary with 100 games in each dictionary, and for every second, iterate through the list and check each player? (seems a bit finicky)?

I really want to hear what the best approach to this would be.

# Answer
> 0 votes
This isn't so much of a Python issue as a Django issue - there are many ways in Python (and indeed most languages) of watching for a time to pass, but the problem is how you act upon it. With Django and websockets you'll need to tell it to send data down an existing websocket, and how to do that will depend on how exactly the websockets are implemented (which in turn is likely to depend on Django).

A threaded approach that is more effective than having one per timer is to have one timer thread manage all the timers. Keep a list of timers and game IDs and sort them by time, ascending. Then you only have to check the first timer to see if it's expired; if so, send a signal to that game, pop it from the list, and repeat. If the first timer has not expired, you can have that thread sleep for a while. The first complication with this approach is safely getting a timer into the thread, but you can probably use the Queue module to help there. The second complication, as hinted at in the first paragraph, is how to go from knowing a move has timed-out to actually notifying a player. You'd need some way of communicating back to the main Django thread, which is not simple, and it appears that most developers have to resort to using an external message queue. There's some discussion here: http://www.turnkeylinux.org/blog/django-celery-rabbitmq

Iterating through a list of all games and checking the timer would also work. It's unlikely to be a drain on resources unless you're doing it every millisecond. I don't know if there's any way to get Django to perform a task such as this every so often (eg. once a second) but the answers to this question are not very encouraging.

The unfortunate answer is that web applications are poorly suited to real-time systems like this. They're usually configured in a way that makes it difficult to respond at arbitrary times and the HTTP protocol makes it difficult to send that response even if you managed to form it. (This doesn't apply so much to Websockets - but unfortunately you're stuck within the structure of the traditional web application.) You might want to consider using a different server application that features a main loop and which would allow you to have more control over executing background tasks.

# Answer
> 0 votes
If you are going to use websockets, I wouldn't recommend django, since its not made to work with realtime applications (although this is a general problem with any wsgi application). You should use an async webserver, like tornado or twisted

Besides, tornado supports websockets natively, and i think there's a library to work with socket.io

---
Tags: python, websocket
---


# Question
Title: Handling of data sharing between framework module
I am currently developping a 3D game using C# / XNA 4.0 and i am currently thinking about how i should structure my game. The actual game is in fact not really important as the framework i am working on right know is pretty generic.

1st layer :

1. BaseFrameWork : This BaseFrameWork is managing all the different game modules

2nd layer :

1. ContentProvider : This module is a layer loading all the needed content (texture/sound/models) and providing it when needed
2. SoundManager : This module is handling all the audio request (music activation, music change, sound activation, ect)
3. InputEventHandler : This module is handling all the inputs of the player. Some flags are provided to each module to operate (for example there is a flag "toggleMusic" which is turned on when the player is pressing "M" while in game.
4. ObjectFactory : This module is creating all the different objects when it is needed (for example creating a floor, boxes and other stuff)
5. Player : This module is exclusively dedicated to the player.
6. HeadUpDisplay : This module is dedicated to write the HUD (2D) of the game

Currently the 3rd layer is not developped (i have a few different objects for the ObjectFactory but that's all).

My first question is : "Knowing how is structured my game, do you think i should do it differently, and why ? For example, should player be part of the ObjectFactory "

My second question is about the way these different modules should be linked together.

* The easiest option, but (i think) the nastiest one, is to provide to each module a reference of the other ones with everything public. Really easy to implement, really easy to use ingame, but really REALLY nasty.
* One other option could be to let the BaseFrameWork get the useful informations of a module to give it to an other module.
* Other options ?

These questions may seem basic and common sense, but last time i have been part of a game development, it looked nice (http://yapt.free.fr/) but i think we/I could have done better by spending more time into the game architecture beforehand instead of just diving the head in water.

Thanks for your comments/advice

Al\_th

# Answer
The way I read your question, is you know how you want your game objects to be structured, but you don't know how you want them to communicate. To answer "should I structure this differently" I would say no. It looks pretty standard to most other structures I have seen.

For the second question, the method I use for this is an EventManager. It is somehow globally accessed (singleton, global variable, static, ect). It has two parameters that go with each event: a type and a data object.

The type is an enum that stores various things that happen, like object created, moved destroyed, collisions, player moved forward, ect.

The data is a virtual class that has an implementation for each type. So object created event would be passed the ObjectCreatedData, which inherents from the EventData base class.

Then, when something happens in the game, like the physics system detects a collision, it triggers the event. Everyone that cares has set up event listeners to the events they care about. So for instance the SoundManager registered an event listener for collisions so it knows when to play the collision sound.

This way you can trigger anything you want, and other parts of the framework can manage whether or not they care. As many parts can listen to one event as you want, or none at all.

This keeps things from getting interdependent.

As a last note, I would like to mention that I have seen different ways to store the type of than enum. I use enumerations because they are simple and easy to expand, but they get large in bigger games. Some people perfer to use some Hashed Strings or some other generate-able GUID for the event type so they don't have to maintain the enum. I prefer having all the event types in one place though YMMV.
> 0 votes

# Answer
> The easiest option, but (i think) the nastiest one, is to provide to each module a reference of the other ones with everything public. **Really easy to implement, really easy to use ingame, but really REALLY nasty.**

That's where you're wrong: it may be easy to implement and to use, but it's a lot of boilerplate code, and it's hard to maintain.

**Example:**
You need to use IPatator in a Shooter class.
the class that creates your Shooter class doesn't have an IPatator, neither does his own parent, etc.
So because of your Shooter class, all previous classes in the hierarchy now depend on IPatator.

Another reason it's bad is circular dependencies a.k.a dependency hell.

You could either use a DI framework (MEF, Ninject... you name it) or a simple inversion of control container, a basic example can be found here.

It boils down to: have a Dictionary that stores implementations of interfaces used throughout the application (the IoC can be static), or a subset of the application (the IoC needs to be passed as dependency to child classes).
Then you can "resolve" dependencies from that Dictionary instead of passing them from constructor to constructor.
> 0 votes

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


# Question
Title: Does it make sense to build a text-based game Facebook app without using Facebook?
If I am building a text-based browser game, does it make sense to build it on you domain first, without using the Facebook API? I don't want to buy an SSL if I don't end up following through with everything. I already have a domain for testing.

In other words, can/should I build the whole thing outside of Facebook and then change it later to use the Facebook API?

# Answer
The majority of your code is not going to involve the Facebook API. It will be more work to integrate after code completion, but it's certainly possible to integrate it after the game has been written. Make sure you learn about any restrictions about Facebook apps that may impact the functionality of your game. So you can code around those.

Ultimately this is your decision. You need to weigh the possibility of completion against the cost of an SSL certificate. You should also consider the income that can potentially be generated from such a game, to see if you'd ever make your money back. Perhaps seek outside funding to get the SSL certificate.
> 1 votes

---
Tags: browser-based-games, facebook, text-based
---


# Question
Title: How should I learn about collision detection?
If I want to use physics engine for my game then how should I go to learn collision-detection algorithms?

When I read AI book for games, the book talks about collision detection, so I want to learn it, but what kind of book would be best?

If I had to choose to go and learn it what would you advise me to read?

1. A physics book. (Game physics H.Ebrely)
2. A real-time collision detection book. (Same author)

I don't know much about algorithms, some people say it's better to start with a physics book, because real-time collision detection book depend heavily on algorithms.

# Answer
> 0 votes
It depends on how complex simulations are you going to need in your game, and if you're writing your own physics engine, or using an existing one.

In most games, the collisions aren't more complex than in Pong or Arkanoid. Reading a game physics book might be overkill unless you have something more complex in mind. I recommend you to follow these steps:

1. Read an online tutorial on the basics of collision detection. There are dozens of good articles, just do a search. Start with rectangle and circle collisions in 2D.
2. Try to implement the stuff you've read in these tutorials. Once it's up and running, start playing with it, to see how it "feels", what are the caveats etc.
3. Once you see what should be improved in the collision detection you implemented, you can do the necessary research. Some examples keywords might be polygon collision, pixel-perfect collision, Verlet collision etc.
4. Then if you still think you need to know more about collision detection, to make your simulation (almost) perfect, then you should look for some books to read.

# Answer
> 0 votes
Most physics engines have collision detection algorithms already built in since that is one of the more basic functions in a physics engine. Still, it is a good idea to learn, at least the basics, of what such algorithms do since it will aid you in your usage of the engine.

Bullet is a well known open source physics engine, and you can download it here: http://code.google.com/p/bullet/downloads/list

In the zip-file for the latest version there is a manual which explains - among other things - some basics regarding collision detection.

Good luck! ///JmD

---
Tags: collision-detection, mathematics, physics
---