# Question
Title: 3D collision detection with meshes using only raycasting?
I'm building a game using WebGL and Three.js, and so far I have a terrain with a guy walking on it. I simply cast a ray downwards to know the terrain height.

**How can I do this for other 3D objects, like the inside of a house?** Is this possible by casting many rays in every direction of the player?

If not, I would like to know how I can achieve the simplest collision detection possible for other meshes. Do you have to cast a ray to every triangle in every mesh nearby?

# Answer
Pick an open source 3D physics engine, and see how they do this. Better yet, use it and improve it if you need too, this would help the HTML5 community a lot.
> 1 votes

# Answer
You can use simpler, invisible objects like spheres and cubes to simulate the collisions. The person might have many many polygons, and he might be supposed to bounce off of a rock wall with many many polygons, but the person could be represented by a sphere and the rock wall as a simple plane, and have collisions detection work with those objects. There are many examples of code for colliding two spheres, two cubes (even easier if they're lined up with the axis) and many others.

If you need precise collision checking, you can start with the simple primitives and only if there's the chance of a collision between two objects do you try something more complicated.

http://en.wikipedia.org/wiki/Bounding\_volume#Common\_types\_of\_bounding\_volume
> 0 votes

---
Tags: collision-detection, raycasting
---


title: Collision Detection Problems

text:
# Question
Title: Collision Detection Problems
So I'm making a 2D tile based game but I can't quite get the collisions working properly. I've taken the code from the Platformer Sample and implemented it into my game as seen below.

One problem I'm having is when I'm on the ground for some strange reason I can't move to the left. Now I'm pretty sure this problem is from the `HandleCollisions()` method because when I stop running it I can smoothly move around with no problems. Another problem I'm having is when I'm close to a tile the character jitters very strangely.

I will try to post a video if necessary. Here is the `HandleCollisions()` method:

```
void HandleCollisions() {
    Rectangle bounds = BoundingRectangle;

    int topTile = (int)Math.Floor((float)bounds.Top / World.PixelTileSize);
    int bottomTile = (int)Math.Ceiling((float)bounds.Bottom / World.PixelTileSize) - 1;
    int leftTile = (int)Math.Floor((float)bounds.Left / World.PixelTileSize);
    int rightTile = (int)Math.Ceiling((float)bounds.Right / World.PixelTileSize) - 1;

    isOnGround = false;

    for(int x = leftTile; x <= rightTile; x++) {
        for(int y = topTile; y <= bottomTile; y++) {
            if(world.Map[y, x].Collidable == true) {
                Rectangle tileBounds =
                     new Rectangle(x * World.PixelTileSize, y * World.PixelTileSize,
                                           World.PixelTileSize, World.PixelTileSize);
                Vector2 depth = RectangleExtensions.GetIntersectionDepth(bounds,
                                                                         tileBounds);

                if(depth != Vector2.Zero) {
                    if(Math.Abs(depth.Y) < Math.Abs(depth.X)) {
                        isOnGround = true;
                        position = new Vector2(position.X, position.Y + depth.Y);
                    }
                    else {
                        position = new Vector2(position.X + depth.X, position.Y);
                    }

                    bounds = BoundingRectangle;
                }
            }
        }
    }
    ...
}

```

# Answer
> 2 votes
I saw something like this before in the platformer that I'm developing.

One possibility is that there's a rounding or precision error. If you're using the `Rectangle` class (in `Microsoft.Xna.Framework`), you're limited to the precision of integers. Try something equivalent that uses floats.

Also, if you're updating both and x and y positions, *then* checking for collisions, you might have problems. If that's the case, try moving on one axis at a time, check for collisions, then move on the other axis.

I suggested the same thing in another thread: How to determine collision direction between two rectangles?

Edit: Now that I think about it again, I'm pretty sure doing one axis at a time should solve this problem. But it's still a good idea to use higher precision for your geometries. (You should only be rounding geometry coordinates to integers when it's time to draw graphics.)

# Answer
> 0 votes
Sounds like the tile to the left might be slightly greater than the one to the right, try making sure all tiles are flush or make it so when moving it adjusts to small changes in height.

# Answer
> 0 votes
I had some problems myself with the platform starter kit. Check out the answer, maybe it would help. Platformer Starter Kit - Collision Issues

---
Tags: xna, c#, collision-detection, tiles
---


title: Queueing up character actions

text:
# Question
Title: Queueing up character actions
I'm developing a 2D platformer with action-fighter elements. Currently things are working relatively smoothly but I'm having difficulty sorting something out. For the time, keeping my character's states and actions separated and preventing them from stepping on each others' toes is working out well and properly, but I would like to add a feature to my character to get him to behave a little bit more fluidly for the player.

At the moment, he has numerous attacks and abilities that he can execute, all of them being executed with button presses. Here lies the problem: Being as everything is executed through button presses, while an action is in progress I flag the game to disregard further button presses until the action has completed. Therefore, consecutive actions cannot be performed until after the previous action has completed entirely. In runtime this behavior feels very icky, and very ungamelike.

In games that rest most memorably at the forefront of my mind the player is able to execute button commands during the process of actions, and at the end of the current action, the following action is executed (seems like some sort of a queue system or something)

Can anybody offer any guidance with this?

# Answer
> 4 votes
Always store the most recent button press, always let a new button press replace the currently stored one. You don't want more than one otherwise your game will feel squishy and unresponsive instead of icky.

The default action of "Idle" always wants to transition, acting on any stored button press immediately. Other actions like "Monkey Steals the Peach" might wait until they're almost done and then check for button presses before forcing a transition to "Idle."

The trick is to always accept a keyboard input and store it for later use. Once an input has been taken from this storage, set the storage to Idle. In this way if the player does **not** press any buttons he automatically goes to idle.

The second trick is to let all actions check for a stored input a short time before their animations are over and reverting to idle, this is where your smooth feel comes from.

---
Tags: xna, 2d
---


# Question
Title: How to fix OpenGL Co-ordinate System in SFML?
My OpenGL setup is somehow configured to work like so:

```
(-1, 1) (0, 1) (1, 1)
(-1, 0) (0, 0) (1, 0)
(-1, -1) (0, -1) (1, -1)

```

How do I configure it so that it works like so:

```
(0, 0) (SW/2, 0) (SW, 0)
(0, SH/2) (SW/2, SH/2) (SW, SH/2)
(0, SH) (SW/2, SH) (SW/2, SH)

```

SW as Screen Width. SH as Screen Height.

This solution would have to fix the problem of I can't translate significantly(\>1) on the Z axis. Depth doesn't seem to be working either. The Perspective code I'm using is that of my WORKING GLUT OpenGL code which has a cool 3d grid and camera system etc. But my OpenGL setup doesn't seem to work with SFML.

Help me guys. :(

Thanks in advance. :)

```
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include <SFML/OpenGL.hpp>
#include "ResourcePath.hpp" //Mac-only

#define _USE_MATH_DEFINES
#include <cmath>

double screen_width = 640.f;
double screen_height = 480.f;

int main (int argc, const char **argv) {
    sf::ContextSettings settings;
    settings.depthBits         = 24;
    settings.stencilBits       = 8;
    settings.antialiasingLevel = 2;
    sf::Window window(sf::VideoMode(screen_width, screen_height, 32), "SFML OpenGL", sf::Style::Close, settings);

    window.setActive();

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_NORMALIZE);
    glEnable(GL_COLOR_MATERIAL);

    glShadeModel(GL_SMOOTH);

    glViewport(0, 0, screen_width, screen_height);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    //glOrtho(0.0f, screen_width, screen_height, 0.0f, -100.0f, 100.0f);
    gluPerspective(45.0f, (double) screen_width / (double) screen_height , 0.f, 100.f);

    glClearColor(0.f, 0.f, 1.f, 0.f); //blue

    while (window.isOpen()) {
        sf::Event event;
        while (window.pollEvent(event)) {
            switch (event.type) {
                case sf::Event::Closed:
                    window.close();
                    break;

            }

            switch (event.key.code) {
                case sf::Keyboard::Escape:
                    window.close();
                    break;
                case 'W':
                    break;
                case 'S':
                    break;
                case 'A':
                    break;
                case 'D':
                    break;
            }
        }

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        glTranslatef(0.f, 0.f, 0.f);

        glPushMatrix();

        glBegin(GL_QUADS);

        glColor3f(1.f, 0.f, 0.f);
        glVertex3f(-1.f, 1.f, 0.f);

        glColor3f(0.f, 1.f, 0.f);
        glVertex3f(1.f, 1.f, 0.f);

        glColor3f(1.f, 0.f, 1.f);
        glVertex3f(1.f, -1.f, 0.f);

        glColor3f(0.f, 0.f, 1.f);
        glVertex3f(-1.f, -1.f, 0.f);

        glEnd();

        glPopMatrix();

        window.display();
    }

    return EXIT_SUCCESS;
}

```

# Answer
This might help you...

You'll need to change the camera's projection view. Normally, I don't think you use pixel values with a 3D view- unless I'm mistaken. But you can do it fairly easily in 2D:

```
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, XSize, YSize, 0, 0, 1);
glMatrixMode (GL_MODELVIEW);

```

where XSize and YSize are the screen width/heights. Check here for more on 2D drawing. If you want 3D drawing, you'll probably want to mess around with the gluPerspective method (GLU, not the standard GL)
> 1 votes

---
Tags: c++, opengl, c, sfml, perspective
---


# Question
Title: How to determine collision direction between two rectangles?
I am trying to figure out how to determine the direction a collision occurs between two rectangles.

One rectangle does not move. The other rectangle has a velocity in any direction. When a collision occurs, I want to be able to set the position of the moving rectangle to the point of impact.

I seem to be stuck in determining from what direction the impact occurs. If I am moving strictly vertically or horizontally I manage great detection. But when moving in both directions at the same time, strange things happen.

What is the best way to determine what direction a collision occurs between two rectangles?

# Answer
> 10 votes
> I seem to be stuck in determining from what direction the impact occurs. If I am moving strictly vertically or horizontally I manage great detection. But when moving in both directions at the same time, strange things happen.

tl;dr The solution is to move and check for collisions *one axis at a time*.

I had this very same problem. I bet that the update phase of your game loop looks something like this:

* object.x += object.vx
* object.y += object.vy
* check for collisions
* repsond to collisions

The trick here is to move *and* check for collisions one axis at a time. As you said, "If I am moving strictly vertically or horizontally I manage great detection." So you've already solved 99% of the problem. Just change your logic to look like this:

* object.x += object.vx
* check/respond collisions
* object.y += object.vy
* check/respond collisions

In simple cases, it doesn't matter which axis you do first. If you don't feel good about choosing one or the other arbitrarily, it's reasonable to check first the axis where the object's absolute velocity is the greatest.

# Answer
> 11 votes
As per larsbutler's answer, for simple cases, it doesn't matter whether you check for x or y collisions first. This can quickly lead to inaccuracy, later down the road, however (especially with more complex shapes, greater velocities, and more objects).

If anybody is interested in implementing a more sophisticated collision detection algorithm, here's a rundown of what's needed:

1. First, the algorithm does a sweep and prune to narrow down the number of objects needed to check. If you're checking *every* object against *every other* object, it can be quite expensive, computationally. Basically, you predict whether an object is likely to collide in the future; if its not very likely, you don't do the calculations.
2. After pruning, you perform a preliminary collision test. Each object has a bounding rectangle or circle (something that is easy to calculate collisions). Detecting whether two circles/rectangles collide is quite simple, and can quickly eliminate unnecessary calculations between two objects on opposite sides of the screen.
3. If a preliminary detection was made, you need to loop through the edges of each shape and detect any points of collision (intersection of two line segments). In Jon's case, this would be the collision point on the vertical axis and horizontal axis.
4. Once you have a list of collision points, you need to calculate the *exact* collision point. There are a number of ways you can do this, and it all depends on how accurate you want to be. One option is to half the time increment (of your physics integrator), recalculate the shapes' positions, and rerun the collision detection until there *is* only one collision point. Basically, you're approximating the "moment of impact". If your simulation doesn't have very many partial differential forces, you can just use the velocity of the previous integration, with subsequent time halvings.
5. The results of step four will give you the approximate collision points (within an upper/lower bound- like 3px or something). If there is more than one collision point, you'll have to treat them as an imaginary edge. You can then perform collision resolution calculations (velocity, momentum, friction, etc)

Hope this helps someone.

**Specific to Jon's question:**

The step you are missing of the collision algorithm is step #4. From what I understand, your rectangles intersect diagonally and end up getting two collision points (one horizontally and one vertically). Determining which collision point occurred first *really* depends on what you're using for physics integration.

From your description, it sounds like the rectangles don't rotate and things like partial differential forces aren't of much concern. *If this is the case,* finding which edge collides first is fairly simple. Here is some pseudo code:

```
/*
   Assume Obj1 is stationary
   Assume Obj2's velocity is -x and -y (to bottom left)
   From this, we know the collision edges are:
*/
colEdgesObj1 = [1,0]; //right, top
colEdgesObj2 = [0,1]; //left, bottom
//... where [0=left/1=right, 0=top/1=bottom]

//Calculate distances between Obj1 edges and Obj2 edges
distX = Math.Abs(Obj1[colEdgesObj1[0] ? "right" : "left"] -
                 Obj2[colEdgesObj2[0] ? "right" : "left"]);
distY = Math.Abs(Obj1[colEdgesObj1[1] ? "bottom" : "top"] -
                 Obj2[colEdgesObj2[1] ? "bottom" : "top"]);

//Calculate time object would take to go those distances
//(assuming Obj2 is the only moving object)
timeX = distX/Obj2.VelX;
timeY = distY/Obj2.VelY;

//If time is greater, that axis has been colliding longer
if timeX > timeY
    //collided X axis first
else if timeY > timeX
    //collided Y axis first
else
    //collided at a corner

```

---
Tags: c#, xna, collision-detection
---


# Question
Title: Turn-based tile game dynamic item/skill/command script files
I want to create a mechanism that could read text script, for example some kind of custom script such as ".skill" or ".item", which maybe contain some sort of simple script like

```
.item
Item.Name = "Strength Gauntlet";
Character.STR += 20;

```

..

```
.skill
Skill.Name = "Poison Attack";
Skill.Description = "Steal HP and inflict poison";
Player.HP += 200;
Enemy.HP -= 200;
Enemy.Status += Status.POISON;

```

It may be different from this, but just want to give some idea of what I desire. However, I do not know how to dynamically parse these things and translate it into working script. For example, in battle scenerio, I should make my game read one of this ".skill" file and apply it to the current enemy, or the current player. How would I do this? Should I go for String parsing? It is like a script engine, but I prefer C# than creating new language, so how would I parse custom files into appropiate status commands?

Another problem is, I have also created a command engine which would read String input and parse it into action such as "MOVE (1,2)" would move character to tile (1,2). Each command belong to separate class, and provide generic parsing method that should be implemented by hand. This is for the reason of custom number/type of arguments per each command. However, I think this is not well designed, because I desire it to automatically parse the parameters according to specify list of types.

For example, MOVE command in "MOVE 1 2" would automatically parse the parameters into int, int and put it into X and Y. Now, this form can change, and we should be able to manually specify all type of formats. Any suggestion to this problem? Should I change from string parsing to some hardcode methods/classes?

# Answer
> 2 votes
As far, as I understand your problem, you are approaching it from opposite direction.

Ultimately you will need to integrate all those values (I don't see script here, only values) into your game logic (that's where "script" part will actually be). So, the main problem here is not how to read or store it in file, but how it will be implemented in game logic. Create game logic (engine) which will be flexible enough for you, and then the task to code it in some sort of file is easy.

# Answer
> 1 votes
In terms of storing code in a text file, I personally like compile-time error checking. You'll lose that (if you have it -- Ruby, anyone?) by doing this.

If you're still keen, look up dynamic compilation. You can read the text file, compile it at runtime, and execute it.

# Answer
> 0 votes
I suggest you to **embed an interpreted language into your game engine**. This is a quite proven strategy, the main reason you should not write your custom "script parsing procedures" is that you will never get enough. You will add functionalities to your script engine over and over, until it will start to look like any general purpose interpreted language out of there (but more ugly).

Good choices are: Lua, Javascript, Python (maybe Ruby), Guile and probably many others.

The best way (in my experience) to manage this integration is to export a Façade that both simplifies your script manipulation duties and let you to decide what/how expose of your game engine functionalities.

In practice your **game engine adds the instance of the Facade to the interpreter context** and ask such interpeter to evaluate a script file; that **script will find an istance of that Facade** in the global context when executed.

A good strategy is to let your game engine to delegate to a script set (found in specific folders) the execution when something happens (onInit, onBattleBegins, onTick, onProgramCrash ect). This is how every -base plugin system works for every program usefull enough to deserve a plugin system for customization.

If you are good enough, your game engine has some sort of event management system. In this case you can write a **generic extension of your reactor** that looks for **scripts as event handlers**.

One last thing, consider to write **all your game engine using an interpeted language**. I can hear you from here *"what about interpreted slowness?"* This is a quite false problem: every interpreted languages allows extension at different level: to extend is easier than to embed.

*An higher level language let you to focus to the matters of your application*: when the things start to go slow you can profile your modules to see the bottlenecks. Once you have a bottleneck you can try to fix that or to reimplement that using a lower level language.

# Answer
> 0 votes
I am actually working on my own turn based tile game and have begun working out the ability system just recently. I am using the FlatRedBall game engine, which gives me a lot of good free functionality to support this sort of thing. There is still work that needs to be done, but here is the gist:

I have 2 main classes to handle abilities: BasicAbility and AbilityEffect. The numbers and names, etc for the abilities and effects will be stored in CSV format on disk, because FlatRedBall has some amazing code generation support for CSV files, which makes loading the data into C# objects trivial for me. A sample CSV entry for an ability might look like:

```
Poison Dart, new AbilityEffect(100, 0, 0, 0, 0, 1)
,new AbilityEffect(10, 0, 0, 0, 0, 5)

```

I could just as easily do these values as separate columns, but doing the above makes FlatRedBall hydrate the objects for me and link them to the ability dictionary. When I put a player type into a CSV file, I would simply add a list of ability names to the tacticalEntities.csv file as a column for the soldier for instance.

In short, you have data you need to load and not a scripting need necessarily.

BTW, I also wrote an EffectManager class to handle linking AbilityEffects to Entities in the game. It applies the effect values to the Entity objects over time based on the ticks.

Here are the classes:

```
public class BasicAbility : IAbility
{
    public BasicAbility(ICollection<IAbilityEffect> effects)
    {
        Effects = effects;
    }

    public void execute(TacticalEntity source, ICollection<TacticalEntity> destination)
    {
        foreach (TacticalEntity entity in destination)
        {
            EffectManager.AddEffectsToEntity(entity, Effects);
        }
    }

    public ICollection<IAbilityEffect> Effects
    {
        get;
        private set;
    }
}

public class AbilityEffect : IAbilityEffect
{
    public AbilityEffect(int healthPerTick, int speedEffect, int defenseEffect, float aggroRadiusEffect, int strengthEffect, int totalticks)
    {
        HealthEffectPerTick = healthPerTick;
        SpeedEffectWhileActive = speedEffect;
        DefenseEffectWhileActive = defenseEffect;
        AggroRadiusEffectWhileActive = aggroRadiusEffect;
        StrengthEffectWhileActive = strengthEffect;
        TotalTicks = totalticks;
    }

    public AbilityEffect(TacticalEntity source, TacticalEntity affectedEntity, IAbilityEffect that)
        : this(that.HealthEffectPerTick, that.SpeedEffectWhileActive, that.DefenseEffectWhileActive, that.AggroRadiusEffectWhileActive, that.StrengthEffectWhileActive, that.TotalTicks)
    {
        AffectedEntity = affectedEntity;
        SourceEntity = source;
    }

    public int HealthEffectPerTick
    {
        protected set;
        get;
    }

    public int SpeedEffectWhileActive
    {
        protected set;
        get;
    }

    public int DefenseEffectWhileActive
    {
        protected set;
        get;
    }

    public float AggroRadiusEffectWhileActive
    {
        protected set;
        get;
    }

    public int StrengthEffectWhileActive
    {
        protected set;
        get;
    }

    private int _TotalTicks;
    public int TotalTicks
    {
        get
        {
            return _TotalTicks;
        }
        private set
        {
            _TotalTicks = value;
            TicksRemaining = value;
        }
    }

    public int TicksRemaining
    {
        get;
        private set;
    }

    public bool Active
    {
        get
        {
            return TicksRemaining > 0;
        }
    }

    public TacticalEntity AffectedEntity
    {
        get;
        private set;
    }

    public void ApplyConstantEffects()
    {
        AffectedEntity.strength += StrengthEffectWhileActive;
        AffectedEntity.defense += DefenseEffectWhileActive;
        AffectedEntity.speed += SpeedEffectWhileActive;
        AffectedEntity.aggroCircle.Radius += AggroRadiusEffectWhileActive;
    }

    public void RemoveConstantEffects()
    {
        AffectedEntity.strength -= StrengthEffectWhileActive;
        AffectedEntity.defense -= DefenseEffectWhileActive;
        AffectedEntity.speed -= DefenseEffectWhileActive;
        AffectedEntity.aggroCircle.Radius -= AggroRadiusEffectWhileActive;
    }

    public void ApplyEffectTick()
    {
        if (Active)
        {
            AffectedEntity.health += HealthEffectPerTick;
            --TicksRemaining;
        }
    }

    public IAbilityEffect Clone(TacticalEntity source, TacticalEntity entity)
    {
        return new AbilityEffect(SourceEntity, entity, this);
    }

    public TacticalEntity SourceEntity
    {
        get;
        private set;
    }
}

public static class EffectManager
{
    private static Dictionary<TacticalEntity, ICollection<IAbilityEffect>> entityEffects = new Dictionary<TacticalEntity, ICollection<IAbilityEffect>>(20);
    private static double lasttick = TimeManager.CurrentTime;

    public static void AddEffectsToEntity(TacticalEntity entity, ICollection<IAbilityEffect> effects)
    {
        if (!entityEffects.ContainsKey(entity))
        {
            entityEffects.Add(entity, new List<IAbilityEffect>(effects.Count));
        }
        foreach (IAbilityEffect effect in effects)
        {
            AddEffectToEntity(entity, effect);
        }
    }

    public static void AddEffectToEntity(TacticalEntity source, TacticalEntity entity, IAbilityEffect effect)
    {
        IAbilityEffect newEffect = effect.Clone(source, entity);
        ICollection<IAbilityEffect> effects;
        if (!entityEffects.ContainsKey(entity))
        {
            effects = new List<IAbilityEffect>(1);
            entityEffects.Add(entity, effects);
        }
        else
        {
            effects = entityEffects[entity];
        }
        effects.Add(newEffect);
    }

    public static void AddEffectToEntity(TacticalEntity entity, IAbilityEffect effect)
    {
        AddEffectToEntity(null, entity, effect);
    }

    public static void Activity()
    {
        if ((TimeManager.CurrentTime - lasttick) > 1.0)
        {
            lasttick = TimeManager.CurrentTime;
            foreach (KeyValuePair<TacticalEntity, ICollection<IAbilityEffect>> pair in entityEffects)
            {
                TickAndRemoveInactiveEffects(pair);
            }
        }
    }

    private static void TickAndRemoveInactiveEffects(KeyValuePair<TacticalEntity, ICollection<IAbilityEffect>> pair)
    {
        List<IAbilityEffect> effectsToRemove = null;
        foreach (IAbilityEffect effect in pair.Value)
        {
            effect.ApplyEffectTick();
            if (!effect.Active)
            {
                if (effectsToRemove == null)
                {
                    effectsToRemove = new List<IAbilityEffect>();
                }
                effectsToRemove.Add(effect);
            }
        }
        if (effectsToRemove != null)
        {
            foreach (IAbilityEffect effect in effectsToRemove)
            {
                pair.Value.Remove(effect);
            }
        }
    }
}

```

---
Tags: xna, game-mechanics, interface
---


title: Observer Pattern Implementation

text:
# Question
Title: Observer Pattern Implementation
To teach myself basic game programming, I am going to program a clone of Pong. I will use the Observer design pattern, with an interface between the input and the game engine. However, I'm not sure what the interface should do. One idea I had was for the input interface to tell the game engine that (e.g.) the screen was clicked, then to let the game engine decide what to do with that information (shoot a bullet, for example). Another idea I had was for the input interface, having caught the mouse click, to tell the game engine to shoot a bullet.

Which method would be better for me to use?

# Answer
The first method is an implementation of the observer pattern, the second is not. The observed object (your input interface) should not need to know what the observing object (your game engine) will do with the notification, only that it wants to be notified.

However, I am not sure why you have decided to use the observer pattern here. Unless you are going to be having multiple observers, it seems like a complication that can be avoided. If clicking always does the same thing, then just have the interface tell the game engine to do that one thing. Keeping things as simple as possible makes it easier on yourself. This is not to say never use design patterns, but generally you approach their application in the opposite direction from what you are doing. IE: start with the problem and pick the design pattern to solve it, rather than starting with the design pattern and figuring out how to solve your problem with it.
> 7 votes

# Answer
If you want to stick with the Observer pattern, then it has to be the first idea. The strongest argument I could think of is that the input interface is a generic component that you will probably want to reuse in other games too. So it makes sense to keep it free from any game specific information, otherwise you wouldn't be able to use it in another context. In general, think carefully about the responsibilities of your classes, and try to keep them focused, and limited to the context of the class.
> 2 votes

---
Tags: input, architecture
---


# Question
Title: Matrix loading problems with jbullet and lwjgl
The following code does not load the matrix correctly from jbullet.

```
//box is a RigidBody
Transform trans = new Transform();
trans = box.getMotionState().getWorldTransform(trans);
float[] matrix = new float[16];
trans.getOpenGLMatrix(matrix);
// pass that matrix to OpenGL and render the cube
FloatBuffer buffer = ByteBuffer.allocateDirect(4*16).asFloatBuffer().put(matrix);
buffer.rewind();
glPushMatrix();
glMultMatrix(buffer);
glBegin(GL_POINTS);
glVertex3f(0,0,0);
glEnd();
glPopMatrix();

```

the jbullet is configured as so:

```
CollisionConfiguration = new DefaultCollisionConfiguration();
dispatcher = new CollisionDispatcher(collisionConfiguration);
Vector3f worldAabbMin = new Vector3f(-10000,-10000,-10000);
Vector3f worldAabbMax = new Vector3f(10000,10000,10000);
AxisSweep3 overlappingPairCache = new AxisSweep3(worldAabbMin, worldAabbMax);
SequentialImpulseConstraintSolver solver = new SequentialImpulseConstraintSolver();

dynamicWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, solver, collisionConfiguration);
dynamicWorld.setGravity(new Vector3f(0,-10,0));
dynamicWorld.getDispatchInfo().allowedCcdPenetration = 0f;
CollisionShape groundShape = new BoxShape(new Vector3f(1000.f, 50.f, 1000.f));
Transform groundTransform = new Transform();
groundTransform.setIdentity();
groundTransform.origin.set(new Vector3f(0.f, -60.f, 0.f));
float mass = 0f;
Vector3f localInertia = new Vector3f(0, 0, 0);
DefaultMotionState myMotionState = new DefaultMotionState(groundTransform);
RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, groundShape, localInertia);
RigidBody body = new RigidBody(rbInfo);
dynamicWorld.addRigidBody(body);
dynamicWorld.clearForces();

```

Nothing is rendered on the screen. What am I doing wrong?

# Answer
Figured it out..

```
FloatBuffer buffer = ByteBuffer.allocateDirect(4*16).order(ByteOrder.nativeOrder()).asFloatBuffer().put(matrix);

```
> 1 votes

# Answer
In LWJGL you can use:

```
FloatBuffer buf = BufferUtils.createFloatBuffer(16);
buf.put(matrix);
buf.flip();

```
> 2 votes

---
Tags: opengl, java, 3d, collision-detection, lwjgl
---


# Question
Title: Particle System in XNA - cannot draw particle
I'm trying to implement a simple particle system in my XNA project. I'm going by RB Whitaker's tutorial, and it seems simple enough. I'm trying to draw particles within my menu screen. Below I've included the code which I think is applicable.

I'm coming up with one error in my build, and it is stating that I need to create a new instance of the `EmitterLocation` from the `particleEngine`. When I hover over `particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);` it states that `particleEngine` is returning a `null` value. What could be causing this?

```
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
abstract class MenuScreen : GameScreen

    ParticleEngine particleEngine;

    public void LoadContent(ContentManager content)
    {
        if (content == null)
        {
            content = new ContentManager(ScreenManager.Game.Services, "Content");
        }
        base.LoadContent();
        List<Texture2D> textures = new List<Texture2D>();
        textures.Add(content.Load<Texture2D>(@"gfx/circle"));
        textures.Add(content.Load<Texture2D>(@"gfx/star"));
        textures.Add(content.Load<Texture2D>(@"gfx/diamond"));
        particleEngine = new ParticleEngine(textures, new Vector2(400, 240));

    }

    public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                   bool coveredByOtherScreen)
    {
        base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

        // Update each nested MenuEntry object.
        for (int i = 0; i < menuEntries.Count; i++)
        {
            bool isSelected = IsActive && (i == selectedEntry);

            menuEntries[i].Update(this, isSelected, gameTime);
        }

        particleEngine.EmitterLocation = new Vector2(Mouse.GetState().X,      Mouse.GetState().Y);

        particleEngine.Update();
    }

    public override void Draw(GameTime gameTime)
    {
        // make sure our entries are in the right place before we draw them
        UpdateMenuEntryLocations();

        GraphicsDevice graphics = ScreenManager.GraphicsDevice;
        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
        SpriteFont font = ScreenManager.Font;

        spriteBatch.Begin();

       // Draw stuff logic

       spriteBatch.End();
       particleEngine.Draw(spriteBatch);

    }

```

# Answer
you call to base.LoadContent() inside LoadContent and the method is not overrided.

Maybe adding the override tag and removing the content manager parameter will do the trick ...

```
public override void LoadContent()
{
}

```
> 3 votes

# Answer
I figured it out. Thanks guys, I learned a bit from your answers nonetheless.

I was trying to draw the particles in the wrong class. Instead of MenuScreen it should have been done in BackgroundScreen, which is where all of my Drawing is done for those screens.
> 2 votes

# Answer
I think we need to see more code. Is GameScreen from the state management sample? What should be calling LoadContent? Is it a DrawableGameComponent? Don't forget the override keyword in the LoadContent declaration, otherwise you're just hiding the member function.
> 1 votes

# Answer
I'm not that knowledgeable about particles but don't you need to go ParticleEngine particleEngine = new ParticleEngine(); ? Try that, no guarantee that's the fix though.
> 0 votes

# Answer
The only way that would be the case would be if `LoadContent` was never invoked. Looks like you probably want to double check the screen manager that you're using to make sure that it's going to call `LoadContent` before ever calling `Update`
> 0 votes

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


# Question
Title: Viewport / Camera Calculation in 2D Game
we have a 2D game with some sprites and tiles and some kind of camera/viewport, that "moves" around the scene. so far so good, if we wouldn't had some special behaviour for your camera/viewport translation.

normally you could stick the camera to your player figure and center it, resulting in a very cheap, undergraduate, translation equation, like :

vec\_translation -/+= speed (depending in what keys are pressed. WASD as default.)

buuuuuuuuuut, we want our player figure be able to actually reach the bounds, when the viewport/camera has reached a maximum translation.

---

we came up with the following solution (only keys a and d are the shown here, the rest is just adaption of calculation or maybe YOUR super-cool and elegant solution :) ):

```
if(keys[A])
{
    playerX -= speed;

    if(playerScreenX <= width / 2 && tx < 0)
    {
        playerScreenX = width / 2;
        tx += speed;
    }
    else if(playerScreenX <= width / 2 && (tx) >= 0)
    {
        playerScreenX -= speed;
        tx = 0;

        if(playerScreenX < 0) playerScreenX = 0;
    }
    else if(playerScreenX >= width / 2 && (tx) < 0)
    {
        playerScreenX -= speed;
    }
}
if(keys[D])
{
    playerX += speed;

    if(playerScreenX >= width / 2 && (-tx + width) < sceneWidth)
    {
        playerScreenX = width / 2;
        tx -= speed;
    }
    if(playerScreenX >= width / 2 && (-tx + width) >= sceneWidth)
    {
        playerScreenX += speed;
        tx = -(sceneWidth - width);
        if(playerScreenX >= width - player.width) playerScreenX = width - player.width;
    }
    if(playerScreenX <= width / 2 && (-tx + width) < sceneWidth)
    {
        playerScreenX += speed;
    }
}

```

---

i think the code is rather self explaining:

keys is a flag container for currently active keys, playerX/-Y is the position of the player according to world origin, tx/ty are the translation components vital to background / npc / item offset calculation, playerOnScreenX/-Y is the actual position of the player figure (sprite) on screen and width/height are the dimensions of the camera/viewport.

this all looks quite nice and works well, but there is a very small and nasty calculation error, which in turn sums up to some visible effect.

let's consider following piece of code:

```
if(playerScreenX <= width / 2 && tx < 0)
{
    playerScreenX = width / 2;
    tx += speed;
}

```

it can be translated into plain english as : if the x position of your player figure on screen is less or equal the half of your display / camera / viewport size AND there is enough space left LEFT of your viewport/camera then set players x position on screen to width half, increase translation (because we subtract the translation from something we want to move). easy, right?! **doing this will create a small delta between playerX and playerScreenX.**

after so much talking, **my question** appears now here at the bottom of this document:

*how do I stick the calculation of my player-on-screen to the actual position of the player AND having a viewport that is not always centered aroung the players figure?*

here is a small test-case in processing:

http://pastebin.com/bFaTauaa

thank you for reading until now and thank you in advance for probably answering my question.

# Answer
> 4 votes
You flip it around.

Right now, your player influences the camera. When you press the `A` key, the `playerScreenX` variable changes.

In terms of the camera, that means that when you press the `A` key, it moves the view. Logically, you are now having a hard time trying to separate the two views (world and camera).

A variable that holds the screen position of an object is a good start, but I would extend it further:

* Every object has a position in world space.
* The camera has a transformation matrix holding its position in world space and its rotation.
* To place an object on the screen, you do this: `m_ScreenPosition = GetCamera()->Transform(m_WorldPosition);`
* To move the camera, you give it a new position (the position of the player in world space).

How does this solve the problem at hand?

In this system, the player can move to any location, even invalid ones. It doesn't matter, because his render location is determined by the camera.

The camera knows about the bounds of the level and how large its viewport is. When it receives an invalid position (too far on the left or too far on the right) it can turn that into a valid position.

For example, let's say our level is 1000x1000 pixels, our viewport is 640x480 (with edges of 160 and 160) and our player is at (200, 200).

After applying our camera transform, we get a position in screenspace: (200, 200). Cool. Let's move the player to (700, 200). This doesn't fit in our viewport (which extends until 640-160 = 480), so we have to move the camera:

```
x = player_pos.x - (screen_width.x - edge.x - edge.x);

```

Now our new position for the camera is 380.

**Bonus:** You are now transforming the *player* with the *camera*, instead of the *camera* with the *player*. What does this mean? Now your camera can rotate, scale, skew, whatever and it doesn't affect the rest of the game in the slightest! You can even add more camera's, from different angles, or put the camera on rails to show off a cool feature.

# Answer
> 0 votes
For a game I was working on I used a fairly simple process you can probably make use of in this case, if I have understood the problem that is.

I wanted the camera to track the player, but I also didn't want to show the areas outside of the 2D world. So what I did was define a collision rectangle for the world, a rectangle for the camera and a rectangle for the player. Then, after moving the player (and therefore the camera tracking it) I would test that the camera rectangle and the player rectangle were completely within the world rectangle. If they weren't I would move them before drawing.

On top of this, I added an extra detail to prevent the camera collision with it's boundaries being too harsh while also giving it a fairly natural movement. What I did was simply store an average of where I want the camera to be and put the camera there, rather than specifically where the player is. So I would work out, for my game, I always want the camera to be 5 meters ahead of my player. So I would take the player position plus 5 * normalised direction of the player movement vector. I would add this to my rolling average which takes 50 samples in a ring buffer and I would put the camera at the average position. This causes the camera to always slightly lag behind the player giving it a natural smoothe movement witout require complex sping physics. It also mean that, when I work out the desired position, I could check if this would put the camera out of bounds and change the position appropriately.

---
Tags: 2d, camera
---


title: How can I create a rain effect?

text:
# Question
Title: How can I create a rain effect?
I'm making a game in which I want a rain effect, like rain is coming and game play normally.

# Answer
> 3 votes
There are two ways to create a rain effect in andengine.

1. You can use sprite for rain drop and generate sprite at random position in the screen of the device. This will create a illusion of rain.
2. You can use a particle for creating rain effect. You have to generate particle randomly on the screen.

# Answer
> 4 votes
While this isn't how, it should be noted that: (this will help with speed) You almost never see rain by itself, you only see it when it hits the ground or passes through a lit object (like a light post). The simplest way to mimic rain without drawing any rain particles is to add fog to the world and add raindrops to the world, with maybe a few rain streaks. That will give you more realistic rain IMO. While this effect works better in 3D (you can see it discussed here: Link), if done right it could probably still look good in 2D

---
Tags: box2d, andengine
---


# Question
Title: Why does setting a geometry shader cause my sprites to vanish?
My application has multiple screens with different tasks. Once I set a geometry shader to the device context for my custom terrain, it works and I get the desired results.

But then when I get back to the main menu, all sprites and text disappear. These sprites don't dissappear when I use pixel and vertex shaders.

The sprites are being drawn through D3D11, of course, with specified view and projection matrices as well an input layout, vertex, and pixel shader. I'm trying `DeviceContext->ClearState()` but it does not help. Any ideas?

```
    void gGeometry::DrawIndexedWithCustomEffect(gVertexShader*vs,gPixelShader* ps,gGeometryShader* gs=nullptr)
{
    unsigned int offset = 0;
    auto context = mp_D3D->mp_Context;

    //set topology
    context->IASetPrimitiveTopology(m_Topology);

    //set input layout
    context->IASetInputLayout(mp_inputLayout);

    //set vertex and index buffers
    context->IASetVertexBuffers(0,1,&mp_VertexBuffer->mp_Buffer,&m_VertexStride,&offset);
    context->IASetIndexBuffer(mp_IndexBuffer->mp_Buffer,mp_IndexBuffer->m_DXGIFormat,0);

    //send constant buffers to shaders
    context->VSSetConstantBuffers(0,vs->m_CBufferCount,vs->m_CRawBuffers.data());
    context->PSSetConstantBuffers(0,ps->m_CBufferCount,ps->m_CRawBuffers.data());
    if(gs!=nullptr)
    {

        context->GSSetConstantBuffers(0,gs->m_CBufferCount,gs->m_CRawBuffers.data());
        context->GSSetShader(gs->mp_D3DGeomShader,0,0);//after this call all sprites disappear
    }

    //set shaders
    context->VSSetShader( vs->mp_D3DVertexShader, 0, 0 );
    context->PSSetShader( ps->mp_D3DPixelShader, 0, 0 );

    //draw
    context->DrawIndexed(m_indexCount,0,0);
}

//sprites
    void gSpriteDrawer::Draw(gTexture2D* texture,const RECT& dest,const RECT& source, const Matrix& spriteMatrix,const float& rotation,Vector2d& position,const Vector2d& origin,const Color& color)
{

    VertexPositionColorTexture* verticesPtr;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    unsigned int TriangleVertexStride = sizeof(VertexPositionColorTexture);
    unsigned int offset = 0;

    float halfWidth = ( float )dest.right / 2.0f;
    float halfHeight = ( float )dest.bottom / 2.0f;

    float z = 0.1f;

    int w = texture->Width();
    int h = texture->Height();

    float tu = (float)source.right/(w);
    float tv = (float)source.bottom/(h);
    float hu = (float)source.left/(w);
    float hv = (float)source.top/(h);

    Vector2d t0 = Vector2d( hu+tu, hv);
    Vector2d t1 = Vector2d( hu+tu, hv+tv);
    Vector2d t2 = Vector2d( hu, hv+tv);
    Vector2d t3 = Vector2d( hu, hv+tv);
    Vector2d t4 = Vector2d( hu, hv);
    Vector2d t5 = Vector2d( hu+tu, hv);

    float ex=(dest.right/2)+(origin.x);
    float ey=(dest.bottom/2)+(origin.y);

    Vector4d v4Color = Vector4d(color.r,color.g,color.b,color.a);

    VertexPositionColorTexture vertices[] =
    {
        { Vector3d( dest.right-ex,  -ey,              z),v4Color, t0},
        { Vector3d( dest.right-ex,  dest.bottom-ey ,  z),v4Color, t1},
        { Vector3d( -ex,             dest.bottom-ey ,  z),v4Color, t2},
        { Vector3d( -ex,             dest.bottom-ey ,  z),v4Color, t3},
        { Vector3d( -ex,             -ey ,              z),v4Color, t4},
        { Vector3d( dest.right-ex,  -ey ,              z),v4Color, t5},
    };

    auto mp_context = mp_D3D->mp_Context;

    // Lock the vertex buffer so it can be written to.
    mp_context->Map(mp_vertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);

    // Get a pointer to the data in the vertex buffer.
    verticesPtr = (VertexPositionColorTexture*)mappedResource.pData;

    // Copy the data into the vertex buffer.
    memcpy(verticesPtr, (void*)vertices, (sizeof(VertexPositionColorTexture) * 6));

    // Unlock the vertex buffer.
    mp_context->Unmap(mp_vertexBuffer, 0);

    //set vertex shader
    mp_context->IASetVertexBuffers( 0, 1, &mp_vertexBuffer, &TriangleVertexStride, &offset);

    //set texture
    mp_context->PSSetShaderResources( 0, 1, &texture->mp_SRV);

    //set matrix to shader
    mp_context->UpdateSubresource(mp_matrixBuffer, 0, 0, &spriteMatrix, 0, 0 );
    mp_context->VSSetConstantBuffers( 0, 1, &mp_matrixBuffer);

    //draw sprite
    mp_context->Draw( 6, 0 );
}

```

# Answer
Once you call `DrawIndexedWithCustomEffect` with a non-null geometry shader, that shader is bound to the device and it remains bound until you either bind another one or until you unbind it (by calling `GSSetShader` with a null pointer).

Consequently, if you call `DrawIndexedWithCustomEffect` and pass it a non-null geometry shader, and then you call your sprite `Draw` method, the sprites will still be rendered with the geometry shader active, which will likely do unexpected things to their geometry, causing them to be unrenderable or to render way off screen or something.

You have a separate method for rendering sprites, and that method is currently *assuming* that no geometry shader is present, but that's no longer the case.

You should solve this problem by ensuring you set all state that is relevant in your draw methods. In this case you probably want to ensure the geometry shader is unbound in your `gSpriteDrawer::Draw` method by calling `GSSetShader` with a null pointer prior to issuing a draw call.
> 3 votes

---
Tags: c++, directx11, geometry-shader
---


title: iOS Game Development on PC?

text:
# Question
Title: iOS Game Development on PC?
> **Possible Duplicate:**
> Can we develop a game for iPhone on Windows platform?

Are there any available game engines that I could use to develop on Windows instead of on Mac?

I'm aware there is XCode for Mac, but I'm looking at a game engine for iOS on Windows.

I'm open to paid or free engines, but mainly free ones (to keep my operating cost low, unless that paid engine is really, really good)

# Answer
> 1 votes
Look into Unity. It's free to develop with for PC/Web, so you can develop your entire game, test it, and then port it to iOS with little effort. The iOS exporter is $400.

Whichever route you go, though, I think you'll probably still need access to a Mac to actually compile your app for iOS.

This question: (which may be a duplicate) may also be useful to you.

**Notes:**

It seems you are confusing the terms "IDE" and "game engine." XCode helps you write code; it's an IDE. A game engine, on the other hand, provides a framework for your code to run in once you've written it. Unity encompasses both: it includes an IDE *and* a game engine.

# Answer
> 0 votes
Corona is a very good tool for developing 2D mobile games; you can develop for Android on Windows and then compile to iOS on a Mac.

---
Tags: ios
---


title: Xna performance

text:
# Question
Title: Xna performance
I'm thinking about starting to write a game and my primary concern is performance. I was thinking about writing it in xna (client), and then also writing the server in c#. Will this be fast enough for any game that requires twitch reactions (like a top down shooter).

# Answer
Yes. The XNA Framework is perfectly capable of building any type of game. If I were you, I would worry more about building a game first, rather than how well it will run once built.
> 4 votes

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


# Question
Title: How To Smoothly Animate From One Camera Position To Another
The Question is basically self explanatory. I have a scene with many cameras and I'd like to smoothly switch from one to another. I am not looking for a cross fade effect but more to a camera moving and rotating the view in order to reach the next camera point of view and so on. To this end I have tried the following code:

```
    firstCamera.transform.position.x = Mathf.Lerp(firstCamera.transform.position.x, nextCamer.transform.position.x,Time.deltaTime*smooth);
    firstCamera.transform.position.y = Mathf.Lerp(firstCamera.transform.position.y, nextCamera.transform.position.y,Time.deltaTime*smooth);
    firstCamera.transform.position.z = Mathf.Lerp(firstCamera.transform.position.z, nextCamera.transform.position.z,Time.deltaTime*smooth);

    firstCamera.transform.rotation.x = Mathf.Lerp(firstCamera.transform.rotation.x, nextCamera.transform.rotation.x,Time.deltaTime*smooth);
    firstCamera.transform.rotation.z = Mathf.Lerp(firstCamera.transform.rotation.z, nextCamera.transform.rotation.z,Time.deltaTime*smooth);
    firstCamera.transform.rotation.y = Mathf.Lerp(firstCamera.transform.rotation.y, nextCamera.transform.rotation.y,Time.deltaTime*smooth);

```

But the result is actually not that good.

Thank you all, I fixed it this way

```
 var pos:Vector3 = firstCamera.transform.position;
    var rot:Quaternion = firstCamera.transform.rotation;
    firstCamera.transform.position = Vector3.Lerp(pos, nextCamera.transform.position,Time.deltaTime*smooth);
    firstCamera.transform.rotation = Quaternion.Lerp(rot, nextCamera.transform.rotation,Time.deltaTime*smooth);

```

# Answer
> 5 votes
Consider using Quaternion.Lerp or Quaternion.Slerp instead of lerping the euler angles directly.

# Answer
> 1 votes
You need to save the original position/rotation of `firstCamera`. It seems to be using the current values.

---
Tags: unity, animation, camera
---


# Question
Title: Which is the best DirectX 9 SDK version?
I've seen a lot of Microsoft's DirectX releases through these years. Actually I'm working with version 9 right now and I read in a book that the October 2006 is one of the best version 9's releases. Though, there are newer and updated version 9's SDK and I don't know which of them is really the most clean and bug-free.

# Answer
You should use the latest (non-beta) version of the SDK (which is the June 2010 SDK as of this writing). It will be the most well-supported.

Really, the only reason to use an older release of the SDK is if you are working on maintaining a legacy project that has a dependency on a technology that has been deprecated, such as DirectPlay.
> 4 votes

# Answer
Agreed, the latest release of the SDK is generally the best one to use, but there are other considerations.

From sometime in 2004 (IIRC) onwards the D3DX stuff moved from being statically linked to dynamically linked. In order to handle this, the player needs a version of D3D that is up to date. In a fit of ingenuity, MS didn't include these up to date versions with either Windows Vista or 7 - I've personally been in a position where people have said "I've D3D11, I'm up to date" but yet don't have the up to date D3DX DLLs for 9. That sucks (and is actually quite difficult to explain to someone).

What sucks even more about this is that certain "power user" (i.e. - someone who has just about enough knowledge for it to be a dangerous thing) websites provide direct downloads of individual DLLs, so people grab these rather than running the proper installer from MS. Cue random and mysterious crashes.

So, in summary, for 9 you have 2 options. Either use use the latest version (and tell people to update their DX install - *even* if they *think* it's already up to date), or backtrack all the way to 2004 or thereabouts when D3DX was statically linked and none of this was a problem.
> 4 votes

---
Tags: directx9
---


# Question
Title: Defining and selecting an area from an image
I want to create a game, where the world is loaded from an image file, much like Paradox Interactive does it for their games. If I have this image:

Then the red, green, blue, cyan, magenta, white, black and grey should be different provinces. I know how to loop through them, and check if it's a new province, the problem is that I don't know how to define the region of the province for selection: I don't know how I can load in data, to make sure you can click anywhere on that province, and make sure it gets selected.

# Answer
> 2 votes
You could also define your areas using a Voronoi diagram, where multiple same coloured *sites* define an area. A map file will at the minimum contain a list of "sites", with their x,y coordinates and the area id they belong to (one of 1 through 5 in the image below).

You will probably need to create a specialized tool for map-creation, but your map will always be well defined (you won't have pseudo-degenerate pixels making your life hard, like the intersection of areas 6, 7 and 9 in your picture) and detecting collision/selection will be as easy as checking the nearest site.

To make the borders more natural you could opt to add more sites in the map file and/or use a specialized drawing method in your engine.

# Answer
> 0 votes
I assume that each area actually have a unique colour, even tough it doesn't look like it in you picture, as that is how system you are trying to copy does it.

I think the way they, Paradox Interactive, solved this problem is by having the image loaded in memory and translate the mouse position into texture coordinates. The colour read at the coordinates is then used to look up witch area it belongs to. It is probably easiest to have a map of areas with the area colour as the key or something.

EDIT: After looking into it a bit more this isn't how they do it. They create collision data from the map and then uses that.

---
Tags: c++, sdl
---


title: Javascript A* path finding

text:
# Question
Title: Javascript A* path finding
I am trying to learn A\* path finding. I am using this library - https://github.com/qiao/PathFinding.js

But there is one thing I don't understand how to do.

To find a path from player.x/player.y (player.x and player.y are both 0) to 10/10 I use this code

```
var path = finder.findPath(player.x, player.y, 10, 10, grid);

```

This gives an array of where I need to move, but how do I apply this array to my player.x and player.y?

The path structure looks like this

```
path = [[0, 0], [1, 0], [1, 1], ..., [10, 10]]

```

# Answer
Try to use a timer to make changes to your player object. For example:

```
function makeMove() {
    var nextPath = path.pop();
    player.x = nextPath[ 0 ];
    player.y = nextPath[ 1 ];
    // draw your player object here
}

setInterval( makeMove, 1000 );

```
> 4 votes

# Answer
There are two ways you can use the information, the simplest to work with is to simply grab the next step, then throw away the path. This has the obvious downside that you waste a lot of resources by calculating the path the next frame again when you already knew:

```
var path = finder.findPath(player.x, player.y, 10, 10, grid)
player.x = path[1][0]
player.y = path[1][1]
path = null

```

The second, better option, is to store the path with the player

```
if (!player.path)
{
  var path = finder.findPath(player.x, player.y, 10, 10, grid)
  path.reverse() // To put the first steps last in the array so we can use pop
  path.pop() // The first point in the array is the starting position
  player.path = path
}
var step = player.path.pop()
if (step)
{
  player.x = step[0]
  player.y = step[1]
}

```

This code will move along the path to the destination, one step each time its called, the first time it calculates the path and then it reuses the existing path until the destination has been reached. To change where the player is going simply set a new path, or clear the existing one.
> 2 votes

---
Tags: javascript, path-finding
---


# Question
Title: How do I connect the seams between my terrain?
I'm using c++ and D3D11 and I'm trying to create a (pretty) large terrain, lets say 4096x4096, maybe larger. I've got the basics of terrain creation and already split it up into chunks.

But, when I'm rendering them (every chunk has its own vertex and index buffer, as well as its own heightmap), there are still little pieces missing between them. I read a lot about LOD(Level Of Detail) and GMM(Geometry Mipmap), but I can't really implement the theory I read. At the moment, it looks like this:

I could really use some help, everything is welcome. If you have some good tutorials on any of this, please share them.

# Answer
> 1 votes
You can check out my answer to a similar question here.

The part of the answer which is most pertinent to your question are these link; General Linking Page, Hugues Hoppe. In these links you should be able to find a technique similar to the one you are using and you should be able to use one of their solutions to the problem.

What you need to do here is create a vertex buffer to fill the gaps in the transition points between LOD levels. If you're system allows for the assumption that each chunk is half, equal or double the detail of the chunk next to it, it should be fairly simple.

Take this example for the transition zone of two chunks, one double the detail of the other;

```
1---2---3---4---5

6-------7-------8

```

You have these points defining the edges of one transition zone. You need to put these in a vertex buffer and create an index buffer which goes, 162, 627, 273, 374, 748, 485. Once you have a method to do this, you just need to repeat it for all transition zones.

Another way to do this is to interpolate another point half way between 6 and 7 and another between 7 and 8. This would allow both edges to have the same number of points making a vertex and index buffer trivial to create. It would also promote better use of the vertex cache since a triangle strip can be used instead of a triangle list. If you look at the index order in the example above you can see that 273 - 374 would stop you being able to use a triangle strip, but maybe you can find a better way of ordering them than me.

---
Tags: c++, directx
---


title: How to break out of if statement

text:
# Question
Title: How to break out of if statement
I'm not sure if the title is exactly an accurate representation of what I'm actually trying to ask, but that was the best I could think of. I am experiencing an issue with my character class. I have developed a system so that he can perform chain attacks, and something that was important to me was that 1)button presses during the process of an attack wouldn't interrupt the character, and 2) at the same time, button presses should be stored so that the player can smoothly queue up chain attacks in the middle of one so that gameplay doesn't feel rigid or unresponsive.

This all begins when the player presses the punch button. Upon pressing the punch button, the game checks the state of the dpad at the moment of the button press, and then translates the resulting combined buttons into an int which I use as an enumerator relating to a punch method for the character. The enumerator is placed into a List so that the next time the character's Update() method is called, it will execute the next punch in the list. It only executes the next punch if my character is flagged with acceptInput as true. All attacks flag acceptInput as false, to prevent the interruption of attacks, and then at the end of an attack, acceptInput is set back to true. While accepting input, all other actions are polled for, i.e. jumping, running, etc.

In runtime, if I attack, and then queue up another attack behind it (by pressing forward+punch) I can see the second attack visibly execute, which should flag acceptInput as false, yet it gets interrupted and my character will stop punching and start running if I am still holding down the dpad.

Included is some code for context.

This is the input region for my character.

```
//Placed this outside the if (acceptInput) tree because I want it
//to be taken into account whether we are accepting input or not.
//This will queue up attacks, which will only be executed if we are accepting input.
//This creates a desired effect that helps control the character in a
// smoother fashion for the player.
if (Input.justPressed(buttonManager.Punch))
{
    int dpadPressed = Input.DpadState(0);

    if (attackBuffer.Count() < 1)
    {
        attackBuffer.Add(CheckPunch(dpadPressed));
    }
    else
    {
        attackBuffer.Clear();
        attackBuffer.Add(CheckPunch(dpadPressed));
    }
}

if (acceptInput)
{

    if (attackBuffer.Count() > 0)
    {
        ExecutePunch(attackBuffer[0]);
        attackBuffer.RemoveAt(0);
    }

    //If D-Pad left is being held down.
    if (Input.DpadDirectionHeld(0, buttonManager.Left))
    {
        flipped = false;
        if (onGround)
        {
            newAnimation = "run";
        }
        velocity = new Vector2(velocity.X - acceleration, velocity.Y);
        if (walking == true && velocity.X <= -walkSpeed)
        {
            velocity.X = -walkSpeed;
        }
        else if (walking == false && velocity.X <= -maxSpeed)
        {
            velocity.X = -maxSpeed;
        }
    }

    //If D-Pad right is being held down.
    if (Input.DpadDirectionHeld(0, buttonManager.Right))
    {
        flipped = true;
        if (onGround)
        {
            newAnimation = "run";
        }
        velocity = new Vector2(velocity.X + acceleration, velocity.Y);
        if (walking == true && velocity.X >= walkSpeed)
        {
            velocity.X = walkSpeed;
        }
        else if (walking == false && velocity.X >= maxSpeed)
        {
            velocity.X = maxSpeed;
        }
    }

    //If jump/accept button is pressed.
    if (Input.justPressed(buttonManager.JumpAccept))
    {
        if (onGround)
        {
            Jump();
        }
    }

    //If toggle element next button is pressed.
    if (Input.justPressed(buttonManager.ToggleElementNext))
    {
        if (elements.Count != 0)
        {
            elementInUse++;

            if (elementInUse >= elements.Count)
            {
                elementInUse = 0;
            }
        }
    }

    //If toggle element last button is pressed.
    if (Input.justPressed(buttonManager.ToggleElementLast))
    {
        if (elements.Count != 0)
        {
            elementInUse--;

            if (elementInUse < 0)
            {
                elementInUse = Convert.ToSByte(elements.Count() - 1);
            }
        }
    }

    //If character is in the process of jumping.
    if (jumping == true)
    {
        if (Input.heldDown(buttonManager.JumpAccept))
        {
            velocity.Y -= fallSpeed.Y;
            maxJumpTime -= elapsed;
        }

        if (Input.justReleased(buttonManager.JumpAccept) || maxJumpTime <= 0)
        {
            jumping = false;
            maxJumpTime = 0;
        }
    }

    //Won't execute abilities if input isn't being accepted.
    foreach (PlayerAbility ability in playerAbilities)
    {
        if (buffer.Matches(ability))
        {
            if (onGround)
            {
                ability.Activate();
            }
            if (!onGround && ability.UsableInAir)
            {
                ability.Activate();
            }
            else if (!onGround && !ability.UsableInAir)
            {
                buffer.Clear();
            }
        }
    }
}

```

When the attackBuffer calls ExecutePunch(int) method, ExecutePunch() will call one of the following methods:

```
private void NeutralPunch1() //0
    {
        acceptInput = false;
        busy = true;
        newAnimation = "punch1";
        numberOfAttacks++;
        timeSinceLastAttack = 0;
    }

    private void ForwardPunch2(bool toLeft) //true == 7, false == 4
    {
        forwardPunch2Timer = 0f;
        acceptInput = false;
        busy = true;
        newAnimation = "punch2begin";
        numberOfAttacks++;
        timeSinceLastAttack = 0;

        if (toLeft)
        {
            velocity.X -= 800;
        }

        if (!toLeft)
        {
            velocity.X += 800;
        }
    }

```

I assume the attack is being interrupted due to the fact that ExecutePunch() is in the same if statement as running, but I haven't been able to find a suitable way to stop this happening.

Thank you ahead of time for reading this, I apologize for it having become so long winded.

# Answer
> 2 votes
Pretty long question, but if I read it correctly: `acceptInput` could change after you've check it? So check it again:

```
if (acceptInput)
{
    if (attackBuffer.Count() > 0)
    {
        ExecutePunch(attackBuffer[0]);
        attackBuffer.RemoveAt(0);
    }

    // ## Inserted additional check here
}
if (acceptInput)
{
    // The rest of your code

```

---
Tags: xna, 2d, xna-4.0
---


# Question
Title: Game programming course materials: What should it include?
I am tasked to create the course materials for a game programming class, and I’d like your opinion on what aspects and areas of game programming, such as game state management, game object storing or simple AI, should I include in it? The course is intented to be the first step into game programming for students with novice skills in programming.

There will be mathematics as well, but I found that there are multiple questions, with good answers, on that subject already.

# Answer
> 5 votes
For this question I will assume that the course name might be something along the lines of "Introduction to Computer Games".
I remember taking a game programming course once, and one of the things I had appreciated the most was the fact that the prof. actually took time to teach us a little about game storytelling. In fact, our first assignment was to create a text-based game which would be evaluated on how good the story was.
A lot of the students argued and complained that creating a story was outside of their skill set, and that it was unjust to evaluate them on such a thing. However, if I may paraphrase the prof., the goal in making a game is not only to create something pretty and efficient/fast, but also to entertain your intended audience. Thus, for indie game developers, it's a good idea to start developing storytelling skills as early as possible.
Another thing I think was useful was teaching how to find our intended audience through the Bartle Test. The Bartle Test is a test to define what kind of gamer you are, and therefore to define what kind of games you like. Knowing for whom you are making a game can greatly help reduce the "useless" features your game has and expand on what will eventually be your greatest selling points.
Finally, one thing I would talk about are distance metrics and mathematics. Both of these things are very important in game development and are some of the most underestimated challenges a beginning game programmer will face. Things such as 3D rotation (quaternions) are often ignored until they are needed.
These all have to do with general game creation practices, and are not limited to a single development environment/language/technology. Thus, I think, at least in the long run, that they would be very useful to teach aspiring game-developers :)
EDIT: As a closing note, I would like to add that although taking a course in game development is a great step in the right direction, you should tell the students that the best way to gain some skills and experience is to "get their hands dirty" by making their own small games. To reuse an already overused truism, practice makes perfect!

# Answer
> 2 votes
You could make it for the **first** part of semester for theory to describe about all subsystems that are common for games (introduction, main loop, resource loading, memory management, **math** \- general and 2d math) and for theory for **second** part of semester to move to more advanced topics such as game engines their architecture, and how earlier described common subsystems are extended to next level which is required for bigger games supported by big engines, then introduce them to **more math** \- 3d math and advanced topics , opengl, directx, and maybe, just maybe, short intro to few *game engines*.

At the end of first part of semester it would be good if they get guidelines for *game design* (story telling, and other related stuff).

For practice part, first part of semester they could do exercises on per class basis, that is they themselves write small main loop, write short resource loading, etc.

Before second part of semester, they form groups of 3-4 students, and design a game (before second part and after game design guidelines), and during second part of semester they do implementation using some *framework* that has all the boring stuff implemented (resource load, pathfinding, gui, etc...). This *framework*, should **not** be some game engine, or big name game framework but something small and compact, and easy to use. Also they should have game art ready to use if they'll make a game.

This would actually be interesting, you give them building blocks (framework, art) and they connect the dots, but they need to know how things work under the hub.

# Answer
> 1 votes
First. Maybe the start of the course could be a quick introduction to Unity and animated/textured character import and static mesh import. I think it is important to get this out of the way as early as possible because it:

* is empowering to get something rendering and moving correctly.
* implies the question, "Okay, wow, it' rendering and moving, now what?"
* allows the rest of the quarter/semester to focus on programming.

Second. Player control (mouse clicking (rts/diablo) and game-pad (action/splinter cell)) and camera control. Some discussion about ray-casting (and corresponding collision queries), transformations, and quaternions. First exposure to ideas of collision, intersection tests, etc...

Third. Game state/character state/FSM. Discussion on logic flow/state transitions and good modular design with Unity's component system. Could couple this with triggers/collision boxes to work on getting characters to respond to the environment, hug and shimmy across walls, grab pick-ups, etc..., for example. Would give second exposure to collision system and related considerations.

Forth. Introduce NPCs and AI. Can complete mouse clicking player control with A\* path-finding. Move to flocking behavior and behavior trees (or other interesting topics).

Fifth. Networking.

Sixth+. Other items, depending on course length.

I think it might be cool to have class assignments be limited to making Unity components that implement things related to various topics. This would implicitly force (hopefully) good modular design. It would also be cool to work on a class level game, where friends can plug-in each others components and see the differences.

Making a "full" game could be extra credit/grade booster/separate final assignment and students can be informed of this at the start of the quarter. This way, there is extra motivation for them to start thinking about the design of their code and how best to make it work for them and their own projects.

Anyways, just trying to throw some ideas out there.

---
Tags: software-engineering, game-mechanics
---


# Question
Title: Starting Game Programming in C++, where to begin for optimal cross-platform development?
I wish to begin learning game development in C++. I have knowledge in syntax and the console using Visual C++ 2010, however I want to begin programming. My only problem is that I want to be able to support many platforms including Windows, Mac OS, and Linux. As I get better, I also hope I can submit games to XBLIG (or XBLA) and Steam, and even the Google Play Store (But that would take some porting and major redesign of controls).

I have looked into c++ and SDL but I have no idea how to get started. I have Visual C++ 2010 installed and I hope I can still use that as other C++ IDEs are quit outdated. Because I want to stick with Visual C++ and SDL (unless there is a better library than SDL), there is not much room for debate but rather how to create projects to support cross-platform development.

# Answer
A compiler will often define macros indicating what compiler is being used, what OS is being used, etc...

The following might be useful to you: http://sourceforge.net/apps/mediawiki/predef/index.php?title=Main\_Page

One approach is to architect your code in layers, where one of the lowest level layers would be the platform independence layer. Here, you would write code that uses these compiler macros to fulfill some interface. This interface abstracts the platform specific stuff and is used by the higher level layers (or by users) to avoid direct exposure to these kinds of details.
> 2 votes

# Answer
Begin by not beginning.

Seriously - while there are various libraries and frameworks that can help you, overall true cross-platform programming is *bloody difficult*. I'd suggest that you're trying to achieve too much too soon. Game programming itself is hard enough and you have enough to be getting on with in learning that on it's own. Wanting to learn true cross-platform programming *as well* and *at the same time* is only going to make things even *harder* for you.

So - focus on learning game programming on a single platform. Learn the concepts, the algorithms, the mathematics, the optimal strategies. The great big dirty secret is that *these will all transfer easily to other platforms*. By focussing on a single platform you get to learn them without any peripheral stuff to distract you, and then - when you're comfortable with them - start branching out.
> 2 votes

---
Tags: c++, sdl
---


# Question
Title: How to calculate continuous motion with angular velocity in 2d
I'm really new with physics. Maybe someone would be able to help me to solve the next problem: I need to calculate position of an agent on the plane(2D) in next time step where time step is large(20+ seconds) What I know about agent's motion:

* Initial Position
* Direction(normalised vector)
* Velocity(linear function from time ) - object always moves along it's direction
* Angular Velocity(linear function from time)

Optional:

* External force direction
* External force (linear function from time)

Running discreet simulation with t-\>0 is not an option.

# Answer
It's a little difficult to figure out what you're trying to do here, so let me start out by rephrasing the question as I interpreted it.

An object has a known initial position and is initially facing a specified direction. It can only move in the direction it is currently facing, but this direction is variable; the object rotates. The rotation is described by an angular velocity which is a linear function of time. The magnitude of the velocity is also a linear function of time. You want to know where the object is after it has flown about for a set period, but you are unable to simulate its motion in timesteps small enough to simply keep track of where it is, how fast it is moving and in what direction at all times.

Since both absolute as angular velocity are linear functions of time, the differential equations describing this motion can be solved analytically, but their solutions are ugly nonetheless, involving a bunch of Fresnel functions:

Where **(x(t), y(t))** is the object's position as a function of time, **b** is the angular acceleration, **v** is the velocity (in x- and y-components), **a** is the acceleration, also in components, **ω** is the angular velocity, **φ** is the angle of rotation and **C(x)** and **S(x)** are the Fresnel integrals.

As the result is probably equally disturbing as unhelpful all by itself, I have omitted calculations that lead to it. Unfortunately, no simple approximations are available either. I fear discrete simulation is the only reasonable way of tackling this problem.
> 2 votes

# Answer
To my knowledge, this is not possible exactly as you want it.

The best you can do it calculate a tight-fitting bounding volume for the rotating object (generally this will end up being a sphere centered on the objects center of mass) and use continuous collision detection on that. You can then approximate when the objects will collide.

At that point, you can then use discrete collision detection and a "binary search" over t values to narrow in on a more precise collision time.

Won't be perfect, but then the limitations of floating point math negate any chance of perfect accuracy anyway.
> 0 votes

---
Tags: physics
---