# Question
Title: Flex 4 + Apache Ant, Cannot Load FlashPunk Libraries
I have been searching google, Apache Docs\*, and FlashPunk forums looking for an answer to this: I cannot get Ant/Flex to find and compile the FlashPunk libraries.

Here is my build.xml.

```
<project>
<!-- Flex SDK Properties -->
<property name="FLEX_HOME" value="/opt/flex"/>
<property name="MXMLC.JAR" value="${FLEX_HOME}/lib/mxmlc.jar"/>
<!-- Project Properties -->
<property name="PROJECT_PATH" value="/media/Lexar_32G/Dev/ActionScript/FlashPunk/FP_Tut_Vid_ep01"/>
<property name="SOURCE_PATH" value="${PROJECT_PATH}"/>
<property name="OUTPUT_PATH" value="${PROJECT_PATH}"/>
<property name="FLASHPUNK_PATH" value="/media/Lexar_32G/Dev/ActionScrip/FlashPunk"/>

<!-- Fetch the JAR full of Flex tasks if it is not already in the source directory -->
<copy file="${FLEX_HOME}/ant/lib/flexTasks.jar" todir="${SOURCE_PATH}"/>
<!-- Add flextasks to the project -->
<taskdef resource="flexTasks.tasks" classpath="${SOURCE_PATH}/flexTasks.jar"></taskdef>

<!-- Release build Flash Player 10.1 -->
<target name="build">

<!-- Build the FlashPunk library -->
<echo message="building swc..." />
<compc output="FlashPunk.swc" keep-generated-actionscript="false" incremental="false" optimize="false" debug="true" use-network="false">
<include-sources dir="${FLASHPUNK_PATH}/net"
    includes="**/* flashpunk/utils/* flashpunk/masks/*"
    excludes="**/*.TTF **/*.png"/>
<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>
</compc>

<echo message="building swf..." />

<mxmlc
    file="${SOURCE_PATH}/epOne.as"
    output="${OUTPUT_PATH}/epOne.swf"
    debug="false"
    incremental="false"
    strict="true"
    accessible="false"
    link-report="link_report.xml"
    static-link-runtime-shared-libraries="true">

<optimize>true</optimize>

</mxmlc>
</target>

</project>

```

Results in many errors of the type "Definition net.flashpunk.masks:Grid could not be found" even though when I open the directories I can see the \*.AS files right there.

Sorry if this is very basic. I am piecing together knowledge of Ant from docs and tutorials.

\*I decided to use Ant because neither FlashDevelop for Windows nor Eclipse for Linux seemto work for me.

# Answer
> 1 votes
This was (basically) fixed. I did not meet my goal of having only one copy of the uncompiled FlashPunk library, but I was able to get the SWF to at least compile by copying the entire library to my source path. Good thing it wasn't that large anyway.

Apache Ant command looks like so:

```
<copy todir="${SOURCE_PATH}/net">
    <fileset dir="/media/Lexar_32G/Dev/ActionScript/FlashPunk/net"/>
</copy>

```

Did not turn out to need extra commands to let Flex set up the namespaces for me. Additionally, I stopped trying to compile the library as a SWC before I compiled the final SWF. Therefore, the resulting build.xml looks like so:

```
<!--
build.xml
SquareCrow, June 2011
Apache Ant makefile
-->

<project>
    <!-- Flex SDK Properties -->
    <property name="FLEX_HOME" value="/opt/flex"/>
    <property name="MXMLC.JAR" value="${FLEX_HOME}/lib/mxmlc.jar"/>
    <!-- Project Properties -->
    <property name="PROJECT_PATH" value="/media/Lexar_32G/Dev/ActionScript/FlashPunk/FP_Tut_Vid_ep01"/>
    <property name="SOURCE_PATH" value="${PROJECT_PATH}"/>
    <property name="OUTPUT_PATH" value="${PROJECT_PATH}"/>
    <property name="FLASHPUNK_PATH" value="/media/Lexar_32G/Dev/ActionScript/FlashPunk"/>

    <!-- Fetch the JAR full of Flex tasks if it is not already in the source directory -->
    <copy file="${FLEX_HOME}/ant/lib/flexTasks.jar" todir="${SOURCE_PATH}"/>
    <!-- Add flextasks to the project -->
    <taskdef resource="flexTasks.tasks" classpath="${SOURCE_PATH}/flexTasks.jar"></taskdef>

    <!-- Fetch the FlashPunk files and put them in their own folder -->
    <copy todir="${SOURCE_PATH}/net">
            <fileset dir="/media/Lexar_32G/Dev/ActionScript/FlashPunk/net"/>
        </copy>

    <!-- Release build Flash Player 10.1 -->
    <target name="build">

        <echo message="building swf..." />

        <mxmlc
            file="${SOURCE_PATH}/epOne.as"
            output="${OUTPUT_PATH}/epOne.swf"
            debug="false"
            incremental="false"
            strict="true"
            accessible="false"
            link-report="link_report.xml"
            static-link-runtime-shared-libraries="true">

            <optimize>true</optimize>

        </mxmlc>
    </target>

</project>

```

Simple, no?

---
Tags: flash, actionscript-3, ant
---


title: C# Network Game Programming

text:
# Question
Title: C# Network Game Programming
I already know how to write games in C#, and I've learned the concepts behind network game programming, and created a working multiplayer game that works over LAN.

As an example, somebody runs the game server, which keeps track of the position of... say, a ball. Every so often, the server sends the current location and velocity of the ball to each of the connected clients. If something goes prevents the server from sending the stuff to the clients, the clients can still calculate the position of the ball by using the velocity, and hopefully stay closely enough synchronized with the server until it can resume sending again.

This is all very well and easy over LAN... but how do the clients connect to the server over the internet?

# Answer
In exactly the same way as on the LAN. They report to the gameserver. If necessary, you can set up a centralized directory server that contains IP addresses and other relevant information about the game servers. From then on, it is exactly the same as on a LAN, where you probably ran over TCP/IP too.
> 5 votes

# Answer
The same way any internet app connects to any server over the internet. The client needs (either hard coded or in a config file or wherever) either a static IP address or a DNS hostname that will resolve into the server's (or the server's network border router's) IP address. You also have to make sure the ports you're using are forwarded through your router and opened in your various firewalls so the packets can get through.

If you don't have a static IP, you can use a service like DynDNS to dynamically update a hostname to point to your dynamic IP. I've used them for years and never had an issue.

For a gaming-related example, I run a TeamSpeak3 server at home. When I'm connecting to it over the LAN from my personal machine I don't need to do anything but enter the port and local IP. To connect from the public internet, I have to set up DynDNS to keep my hostname pointing to my dynamic IP and set up port forwarding on my router to forward the TS3 ports to my local server machine.
> 2 votes

---
Tags: c#, networking, client-server
---


title: Timer not going off

text:
# Question
Title: Timer not going off
I've got a timer in my game which is supposed to set off a Boolean back to false after a certain amount of time has passed it just doesn't seem to work despite me trying to debug the issue, although setting off the timer works perfectly fine. Any help with this would be much appreciated

```
for (int i = 0; i < cameras.Count; ++i)
            {
                DetectCamera camera = cameras[i];
                Stopwatch camTimer = new Stopwatch();

                if (player.InterferenceStart && player.EMPBoundingCircle.Intersects(camera.BoundingRectangle))
                    camTimer.Start();

                if(camTimer.ElapsedMilliseconds >= 2000.0f)
                {
                    camera.CameraInRange = false;
                    camTimer.Reset();
                }
                else if (camTimer.IsRunning)
                    camera.CameraInRange = true;
            }

```

# Answer
You declare camTimer inside a method, as soon as your code exits this method the timer will be stopped and garbage collected. Also Your code probably calls this method every frame, so camTimer is created newly everyframe, so the time is never more than a few miliseconds.

Both of these problems can be solved by moving the camTimer out of the method and into the class containing the method. For example:

```
public class MyClass()
{
    StopWatch camTimer;

    public MyClass(){
        camTimer = new camTimer();
    }

    public void StartTimer(){
        camTimer.Start();
    }

    public void StopTimer(){
        camTimer.Reset(); //stops and sets time at 0, alternatively use stop to not set at 0 but keep time
    }

    public void DoSomethingWithCameras(){
            ...
            ...
            if(camTimer.ElapsedMilliseconds > 2000.0f){
                ...
                camTimer.Restart(); //starts measuring from 0 again

            }
            ...
    }
}

```
> 5 votes

---
Tags: c#, software-engineering
---


title: Best way to manage in-game events?

text:
# Question
Title: Best way to manage in-game events?
I'm working on a game where some in-game events need to happen once in a while. A nice example would be a tutorial. You start the game, and at several points in the game an event occurs:

* You encounter your first enemy, the game pauses and you receive an explanation on how to kill it.
* You killed the first enemy, you receive a "good job" message.
* You gain a new item, a menu with the items stats popup.
* etc etc.

The game I'm working on is a puzzle game where the rules in the game are pretty much all the same, so it seems inefficient to hardcode all these events in separate levels.

Should I somehow define these events in an external source, like XML? Then write an interpreter that reads out the XML and sets the events requirements for the level? I'm not sure how I could define an event that should occur when you killed two enemies for example.

Just to be clear, I'm not looking for the best programming language or scripting language to do this, but more at the best method to handle this.

Thanks!

---

**Edit:** A second example since my question was pretty hard to understand:

The problem I'm having is to put some extra actions in the game in a procedure that is always pretty much the same. Like an RPG battle, everyone has a turn, picks a skill etc - it's always the same. But what if there was a case where I would like to display a cutscene somewhere in between. Modyfing the entire game structure to pass in an altered battle class with the cutscene included seems very inefficient. I'm wondering how is this usually done.

# Answer
> 7 votes
This depends a lot on how the events are actually communicated between objects in your game. For example, if you are using a central messaging system then you could have a tutorial module that listens for certain messages and creates tutorial popups whenever it hears certain messages. Then you could set what message to listen for, along with what popup to show, in an XML file or something that is parsed by the tutorial module. By having a separate tutorial object that monitors the game state and displays tutorial popups when it notices stuff in the game, you can change the tutorial object at will without needing to change anything else about your game. (Is this the Observer pattern? I'm not familiar with all the design patterns.)

Overall though it depends on the complexity of your tutorial if it is worth worrying about this. Hard-coding the events in your code and/or levels doesn't seem like a big deal to me for just a handful of tutorial popups. I am curious what exactly you have in mind that makes you think it'll be inefficient, since all you should be doing every trigger is just dispatching a message to the tutorial module, something like TutorialModule.show("1st\_kill");

# Answer
> 7 votes
Here's the design constraints as I understand them:

1. The core gameplay code doesn't care about level requirements and shouldn't be coupled to the code that deals with them.
2. At the same time, it's the core gameplay code that knows when the specific events meeting those requirements occurs (getting an item, killing an enemy, etc.)
3. Different levels have different sets of requirements and those need to be described somewhere.

Given those, I'd likely do something like this: First, make a class that represents a game level. It will encapsulate the set of specific requirements a level has. It has methods that can be called when game events occur.

Give the core gameplay code a reference to the current level object. When gameplay events occur, it will tell the level by calling methods on it: `enemyKilled`, `itemPickedUp`, etc.

Internally, `Level` needs a few things:

* State to track which events have already occurred. This way it can distinguish the *first* enemy killed from others, and knows the first time you've picked up a given item.
* A list of `LevelRequirement` objects that describe the specific set of goals you need for that level.

When you enter a level, you'll create a `Level` with the right `LevelRequirement`s, set up the gameplay code, and give it that level.

Each time a game event occurs, gameplay passes it to `Level`. That in turn calculcates aggregate data (total number of enemies killed, enemies of that type killed, etc.) It then walks through its requirement objects, giving each one the aggregegate data. A requirement tests to see if it's met, and if so spawns whatever resulting behavior is appropriate (showing tutorial text, etc.)

`LevelRequirement` basically needs two things:

1. A description of a *test* to tell if the requirement has been met. This can just be a function if your language makes that easy, otherwise you can model it in data. (I.e. have a `RequirementType` enum with stuff like `FIRST_KILL` and then a big `switch` on that knows how to check each kind.)
2. An action to perform when the requirement is met.

There's still the question of where those sets of requirements are described. You could do something like XML or another text file format. That's useful if:

1. Non-programmers will be authoring levels.
2. You want to be able to change requirements without recompiling and/or restarting.

If neither of those is the case, I'd probably just construct them directly in code. Simpler is always better.

# Answer
> 7 votes
I thought You need to know how to make these events and the rest of post is about it, If You want just to store these events then use some relational database or decribe them by text and use scripting language (he will do parsing and evaluating for You). :)

What You want is to recognize events happened (1) and then do some actions which are demanded by these events (print message, check for keypress...) (2). You also want to make these events happen only once (3).

Basically You want to check for conditions and then schedule some behaviour.

**How to recognize events (1)**

* You want to recognize events like these "first enemy encountered", "new item gained"
* if generic part happens, "**enemy encountered**", "**item gained**" You check for specific part "**first** ...", "**new** item gained"

**What are events made of**

In more general view, each such event is made of:

* **preconditions**, You check them
* **actions** which will be done when preconditions are met (say ""You slained first enemy!", say ""make combos by pressing A and B buttons", say "press 'enter' to continue", require-key "enter")

**How to store these events**

In some data structure:

* have list of preconditions (strings or code if You are writing it in some high-level language)
* have list of actions (they might be strings, Quake engine uses strings for events)

You can also store it in relational database, althought it looks like it is not necessary, if You want to make this game in big You might need to make one.

You then have to parse these strings/things. Or You can use some scripting language like Python or LUA or language like LISP, they all can parse and execute it for You. :)

**How to use these events in game loop (2)**

You will need these two data structures:

* queue of events (events which are scheduled to be run are put here)
* queue of actions (scheduled actions, events imply which actions are done)

Algorithm:

* If You recognize some of **event**'s **preconditions** are met You put him into **event queue**
* (3) Then You should make sure this event happened only once if You want :) (for example with boolean array has\_this\_event\_happened\["first enemy encountered"\])
* (if **action queue** is empty, then) If there is event in **event queue** You put his **actions** into **action queue** and remove him from **event queue**
* If there is **action** in **action queue** You start doing what is demanded by it
* If such **action** is done You remove it from **action queue**

**How to make these actions itself (2)**

You make list of objects, which have function "update". They are sometimes called entities (in Quake engine) or actors (in Unreal engine).

1. You start these objects when they are demanded to start in action queue.
2. these object can be used for other things such as some other timers. In Quake these entities are used for whole game logic, I recommend You to read some material about it.

Action "say something"

1. You print something on screen
2. You want this message to appear for few seconds
3. in "update":
    * make variable remove\_me\_after and decrease it by time which passed
    * when variable is 0 You remove this action from **action queue**
    * You also remove this object (or schedule it to be removed...)

Action "require key"

1. It depeneds on how You want to make it, but I think You You make a message
2. in "update"":
    * You just check for wanted keypress event
    * You probably need some array/queue to hold keypress events
    * then You can remove it from **action queue** and remove the object

**What methods to learn**

---
Tags: architecture, events
---


# Question
Title: How can I set up a flexible framework for handling achievements?
Specifically, what is the best way to implement an achievement system flexible enough to handle going beyond simple statistics-driven achievements such as "kill *x* enemies."

I'm looking for something more robust than a statistics based system and something more organized and maintainable than "hardcode them all as conditions." Some examples that are impossible or unwieldy in a statistics based system: "Slice a watermelon after a strawberry", "Go down a pipe while invincible", etc.

# Answer
> 39 votes
I think a kind of robust solution would be to go the object oriented way.

Depending on what kind of achievement you want to support, you need a way to query the current state of your game and/or the history of actions/events the game objects (like the player) have made.

Let's say you have a base Achievement class such as:

```
class AbstractAchievement
{
    GameState& gameState;
    virtual bool IsEarned() = 0;
    virtual string GetName() = 0;
};

```

`AbstractAchievement` holds a reference to the state of the game. It's used to query the things that are happening.

Then you make concrete implementations. Let's use your examples:

```
class MasterSlicerAchievement : public AbstractAchievement
{
    string GetName() { return "Master Slicer"; }
    bool IsEarned()
    {
        Action lastAction = gameState.GetPlayerActionHistory().GetAction(0);
        Action previousAction = gameState.GetPlayerActionHistory().GetAction(1);
        if (lastAction.GetType() == ActionType::Slice &&
            previousAction.GetType() == ActionType::Slice &&
            lastAction.GetObjectType() == ObjectType::Watermelon &&
            previousAction.GetObjectType() == ObjectType::Strawberry)
            return true;
        return false;
    }
};
class InvinciblePipeRiderAchievement : public AbstractAchievement
{
    string GetName() { return "Invincible Pipe Rider"; }
    bool IsEarned()
    {
        if (gameState.GetLocationType(gameState.GetPlayerPosition()) == LocationType::OVER_PIPE &&
            gameState.GetPlayerState() == EntityState::INVINCIBLE)
            return true;
        return false;
    }
};

```

Then it's up to you to decide when to check using the `IsEarned()` method. You could check at each game update.

A more efficient way would be, for instance, to have some kind of event manager. And then register events (such as `PlayerHasSlicedSomethingEvent` or `PlayerGotInvicibleEvent` or simply `PlayerStateChanged`) to a method that would take the achievement in parameter. Example:

```
class Game
{
    void Initialize()
    {
        eventManager.RegisterAchievementCheckByActionType(ActionType::Slice, masterSlicerAchievement);
        // Each time an action of type Slice happens,
        // the CheckAchievement() method is invoked with masterSlicerAchievement as parameter.
        eventManager.RegisterAchievementCheckByPlayerState(EntityState::INVINCIBLE, invinciblePiperAchievement);
        // Each time the player gets the INVINCIBLE state,
        // the CheckAchievement() method is invoked with invinciblePipeRiderAchievement as parameter.
    }
    void CheckAchievement(const AbstractAchievement& achievement)
    {
        if (!HasAchievement(player, achievement) && achievement.IsEarned())
        {
            AddAchievement(player, achievement);
        }
    }
};

```

# Answer
> 14 votes
Well, in short, achievements are unlocked when a certain condition is met. So you need to be able to produce if statements to check the condition you want.

For example, if you want to know that a level was completed or a boss was defeated, you'd need to have boolean flag turn true when these events happen.

Then:

```
if(GlobalFlags.MasterBossDefeated == true && AchievementClass.MasterBossDefeatedAchievement == false)
{
    AchievementClass.MasterBossDefeatedAchievement = true;
    showModalPopUp("You defeated the Master Boss!  30 gamerscore");
}

```

You can make this as complex or simplistic as needed to match the condition that you're wanting.

Some info on Xbox 360 achievements can be found here.

# Answer
> 8 votes
What if you every action the player takes posts a message to the `AchievementManager`? Then the manager can check internally whether certain conditions have been met. First objects post messages:

```
AchievementManager::PostMessage("Jump", "162");

AchievementManager::PostMessage("Slice", "Strawberry");
AchievementManager::PostMessage("Slice", "Watermelon");

AchievementManager::PostMessage("Kill", "Goomba");

```

And then the `AchievementManager` checks if it needs to do anything:

```
if (!strcmp(m_Message.name, "Slice") && !strcmp(m_LastMessage.name, "Slice"))
{
    if (!strcmp(m_Message.value, "Watermelon") && !strcmp(m_LastMessage.value, "Strawberry"))
    {
        // achievement unlocked!
    }
}

```

You'll probably want to do this with enumerations instead of strings though. ;)

# Answer
> 3 votes
The last design I used was based around having a set of per-user persistent counters and then have achievements key off a certain counter hitting a certain value. Most were a single achievement/counter pair where the counter would only ever be 0 or 1 (and the achievement triggered on \>=1), but you can use this for "killed X dudes" or "found X chests" too. It also means you can setup counters for something that has no achievements, and it will still be tracked for future use.

# Answer
> 3 votes
When I implemented achievements in my last game, I made it all statistic based. Achievements are unlocked when our statistics reach a certain value. Consider Modern Warfare 2: the game is tracking tons of stats! How many shots have you taken with the SCAR-H? How many miles have you sprinted while using the Lightweight perk?

So in my implementation, I simply created a statistics engine, then created an achievement manager that runs really simple queries to check the status of achievements throughout gameplay.

While my implementation is pretty simplistic, it gets the job done. I wrote about it and shared my queries here.

# Answer
> 2 votes
Use Event Calculus. Then make some preconditions and actions which are applied after preconditions are met:

* preconditions: you killed 1000 enemies, you have 2 legs
* actions: give me lollypop, give me super-duper-shotgun-13
* first-time-actions: say "you are so awesome!"

Use it like (non-optimized for speed!):

* Store all statistics.
* Query statistics for preconditions.
* Apply actions.
* Apply one-time actions once.

If You want to make it fast:

* Cache whatever You want, store parts of it in some trees, hashes ...
* Make changes incremental so You dont apply all the actions all the time but these which are new ...)

**Note**

It is hard to give **best** advice since all things have pros and cons.

* "What is best datastructure?" implies "What operations You want to do with it most? Searching, removing, adding ..."
* You basically think in these properties: ease of coding, speed, clarity, size ...

# Answer
> 0 votes
What's wrong with an **IF** checks after the achievement event occurs?

```
if (Cinimatics.done)
   Achievement.get(CINIMATICS_SEEN);

if (EnemiesKiled > 200)
   Achievement.get(KILLER);

if (Damage > 2000 && TimeSinceFirstDamage < 2000)
   Achievement.get(MEAT_SHIELD);

InvitationAccepted = Invite.send(BestFriend);
if (InvitationAccepted)
   Achievement.get(A_FRIEND_IN_NEED);

```

---
Tags: architecture, achievements
---


# Question
Title: How to design a game engine in an object-oriented language?
Whenever I try and write a game in any object-oriented language, the first problem I always face (after thinking about what kind of game to write) is how to design the engine. Even if I'm using existing libraries or frameworks like SDL, I still find myself having to make certain decisions for every game, like whether to use a state machine to manage menus, what kind of class to use for resource loading, etc.

What is a good design and how would it be implemented? What are some tradeoffs that have to be made and their pros/cons?

# Answer
I doubt somebody is going to be able to say 'You have to do this and that and this and this slots with that using pattern X'.

However, some useful resources:
Enginuity \- a series of engine building articles on Gamedev.net.
Game Coding Complete \- I own this book, and it goes over every (well, almost) aspect of game programming well. It also does have an engine built throughout the book.
Game Engine Architecture \- This is another great book for engine design.
C4 Engine Layout \- Taken from my comment, but this shows a high-level way of fitting each part of the engine together.

These may be a little too much for what you need, but you can't know too much about something, and I'm sure you'll get a good plan from them.

EDIT: I forgot the Gamedev articles have been archived since the new site, fixed :)
> 24 votes

# Answer
As an example, here's how my current roguelike project is structured (in Java). It is using a 2D graphics engine so a lot of the rendering code was already taken care of for me. Criticism is welcomed.

`class Game`
This class sets up the state machine that manages the current state of the game. (in a menu vs. starting a new game vs. playing a saved game)

`interface State`
Each State class contains two loops: a loop for updating the logic and a loop for rendering. They also contain code for calling the `Game` class and requesting a change to a different state.

`class ResourceManager`
A singleton that is initialized by the `Game` class that loads all the needed resources and allows access to them. I don't like this design because it makes it hard to load/unload resources on different levels, for example. I would probably design this differently if I were starting over.

`class Map`
A map contains an array of tiles and a list of all the creatures and items on the map. It's a pretty basic class.

`class Creature`
Creatures contain information about themselves including movement calculations (requiring them to know which Map they're in, and and to be able to query it to find out about obstacles). Deciding whether to do this, or have some kind of manager class take care of it for all the creatures is something I struggle with.

`interface AITask`
Creatures can have a list of AITasks, which are executed every time the creature's logic loop is run. The AITask has its own logic loop that issues commands to the creature, and a termination condition that determines if the task was completed successfully or not.

`interface UIElement`
I implemented my own UI for this engine. Each UIElement has a rendering loop and a logic loop. They also have a loop for processing keyboard/mouse input. All elements can have a number of child elements, which are rendered after their parents, and take over the keyboard/mouse input. This lets you have menus with submenus, for example.
> 8 votes

# Answer
The first important point to make is that there is no one 'good' answer to this question.

The closest thing to a right answer would be something like: It very much depends on the type of game, target platform, constraints (time) etc.

That said there are some really good articles out there that will show you how other people have tried to answer this problem (as i have tried to find info on this in the past).
As The communist duck mentioned the enginuity article on game dev helped me understand some parts of game architecture.

My current design is a hybrid of Quake3/Doom3 and a little bit of the .NET class library :)

I have two libraries (static or dynamic depends on how you want to build/deliver) the `Framework` and the `Library`.

The Library contains all helper classes which are there to help with the production of game software but aren't limited to this kind of product. ie it has an implementation of a linked list which is optimized for game code but could be used by anything which needs the service of a linked list.

The Framework is the guts of the 'engine' if you want to call it that. A lot of this follows Quake3's design philosophies (just in a more object orientated way). It contains the CLI, timing management, OS specific code, and eventually networking layers etc.

These two are then linked against the actual app that is being produced. The `Game` if you like, which contains the game specific code. In much the same way Quake3 loads DLL's depending on which 'mod' is being played.

To give you an idea of structure here is a quick breakdown of folders and contents for each lib:

---

* **Framework**
    + **IO** (Specialist file management classes, Text Printing classes (eg to the CLI), and logging etc.)
    + **Network**
        - **Client** (classes which represent what the Framework considers to be a 'person playing/connected to the game')
        - **Server** (classes to manage connection into the framework and manage the player(s))
    + **Platform** (Keyboard/mouse/controllers handling classes, OS specific routines like getTime())
    + **System** (very low level classes like an error class to aid printing of error messages, Timing classes, and the CLI itself.)
    + **Renderer** (self explanatory)
    + etc.

---

* **Library**
+ **Collections** (classes which represent collections of data, linked lists/hashtables etc.)
    + **Math** (basic math helper classes like Vectors and matrices)
    + etc.

---

HTH! Should give you some pointers...
> 7 votes

# Answer
**Things to consider**

* Object oriented languages have problems because they usually don't have first class functions or not all data is object (like integer or float in Java). Design patterns adress these problems with several patterns. It is generally faster to code and easier to mantain to use language which can do them (first class objects); for example Python (which also allows object oriented design), You will have slower speed thuough.
* Event Calculus, to AI at least
* Hoare logic, use preconditions and postconditions to at least test Your code
* Agents, look at Quake entities
* Relational Databases, powerful way to store data

**Good design**

* make ER diagram
* make it correct
* create your database, objects or data strutures from it

Data is key to programming. If You desing Your data good, algorithm usually emerge from them (if You don't count some numerical algorithms, like computing determinant).
> -3 votes

---
Tags: architecture
---


# Question
Title: Tile based map and collision; getting stuck
I'm trying to make my character move around a tile map with collisions. Everything works fine except for one thing. I show you a picture with the problem:

https://i.stack.imgur.com/ZWI7x.jpg

That is, when I reach a tile above then I can not move anywhere. If you come from the left, I can not move either up or down. If you reach the bottom, I can move to the left but not right. And when you reach the right I can move in any direction.

Honestly I have no idea what may be failing. I think it has to do with if (...), because if I change the order, the addresses where I can move change :/

Here I leave some code:

```
boolean collision = false;

if(Keyboard.isKeyDown(Keyboard.KEY_UP)) {
    for(int i = 0; i < map.GetNumLayers(); i++) {
        if(UpTile(map, i) > 128) {
            collision = true;
        }
    }

    if(!collision) AddPos(0.0f, -vel);
}
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {
    for(int i = 0; i < map.GetNumLayers(); i++) {
        if(LeftTile(map, i) > 128) {
            collision = true;
        }
    }

    if(!collision) AddPos(-vel, 0.0f);
}
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN)) {
    for(int i = 0; i < map.GetNumLayers(); i++) {
        if(DownTile(map, i) > 128) {
            collision = true;
        }
    }

    if(!collision) AddPos(0.0f, vel);
}
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) {
    for(int i = 0; i < map.GetNumLayers(); i++) {
        if(RightTile(map, i) > 128) {
            collision = true;
        }
    }

    if(!collision) AddPos(vel, 0.0f);
}

public int UpTile(Map map, int layer) {
    return map.GetValue(layer, (int) (x/size), (int) (y/size));
}

public int LeftTile(Map map, int layer) {
    return map.GetValue(0, (int) (x/size), (int) (y/size));
}

public int DownTile(Map map, int layer) {
    return map.GetValue(layer, (int) (x/size), (int) (y/size + 1));
}

public int RightTile(Map map, int layer) {
    return map.GetValue(layer, (int) (x/size + 1), (int) (y/size));
}

public int GetValue(int layer, int x, int y) {
    return array[layer][y][x];
}

```

The map is an array with 3 componentes: \[LAYER\]\[Y\]\[X\]. So, in RightTile by example, with GetValue, I'm getting the value from the array in the position \[layer\]\[y/size\]\[x/size + 1\], x/size + 1 because I want to get the kind of tile that is to my right (same with the others). size = 64, that is the width and height of each tile.

Thanks \>.\<

# Answer
The upper right of the shown screens is misleading, you are only prevented from moving right in that situation if you try to move down at the same time. The reason that trying to move in another direction can block your movement is that you don't reset you variable `collision` to `false` between checks, thus as soon as one direction has set it to `true` it will it will block the following move directions.

Take a visual glance at what points you are actually checking, the upper left corner of your character twice, the upper right, and the lower left. Seems like a strange pattern, right?

To get things working as you'd want them in a simple fashion I suggest you use an 8 points method, 2 points for each direction, positioned at the corners of your character, moved out at least as far as the maximum moving speed.

Left: Current test. Right: Suggested test.
> 4 votes

# Answer
I agree with Maik - **debugging** will help you here.

To do this you could walk to the top of the screen, then insert a breakpoint after:

```
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)) {

```

And then press left and follow your code through to see if it does what you think it does. My best bet is that there is a problem indexing the map array; you should verify that the coordinates that are accessed are the correct coordinates.

I did notice some things that could potentially be the cause:

You said the map is an array with three components: \[LAYER\]\[**Y**\]\[**X**\] but then your calls to GetValue index in another order: LAYER, **X**, **Y** (although I guess your GetValue function probably does switch those around).

Also I'm not sure why you are doing (x/size) in UpTile/DownTile/RightTile/LeftTile - if x is smaller than 64 (and is an int) you'll get 0.

Also, I presume:

```
public int LeftTile(Map map, int layer) {
    return map.GetValue(0, (int) (x/size), (int) (y/size));
}

```

should be:

```
public int LeftTile(Map map, int layer) {
    return map.GetValue(layer, (int) (x/size), (int) (y/size));
}

```
> 2 votes

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


# Question
Title: How can I implement a command system for a point-and-click style adventure game?
I'm making a point and click adventure game, and I'm currently trying to figure out the best way to implement a command system.

Assume a Monkey Island or Maniac Mansion style interface, with a palette of verbs, and objects in the scene and in the inventory. Clicking on these, you build up a sentence to execute.

for example, you might click `look at` and then a tree to get "look at tree" or click on an apple, and then `give`, and then a girl, to get "give apple to girl".

There are three possible forms of a sentence:

* `verb`, for example "save"
* `verb noun`, for example "pick up apple", "look at octopus"
* `verb noun noun`, for example "give pickle to rabid dog", "use crowbar with pickle jar"

In different situations, I'll want the action to be carried out to be defined by different objects.

For example, for the `give` verb, there might be a default action defined that makes the character say something like "I'd prefer to hang on to that", or the rabid dog might define an action where it eats anything you attempt to give it.

If the interface is to work like Maniac Mansion, then you build the sentence, and then tell it to execute (in Maniac Mansion, by either clicking the sentence, or clicking again on the last thing you clicked on).

If it's to work like Monkey Island, the sentence executes as soon as it's complete, which poses a problem for verbs like `use` which might sometimes take one noun, and other times two.

So how would you implement a system that handles this?

# Answer
> 10 votes
Your may find it easier to use if you reverse the selection order. So the user clicks a *noun* and then the game displays the set of verbs that can be performed on that noun. If the verb requires an object (i.e. "give to \___", then the game waits for the user to select the object before performing the action.

Something like:

1. User clicks a cheeseburger.
2. Game shows a menu: "pick up, eat, look at, give to \___".
3. User selects "give to \___".
4. Game says "give to whom?" and waits for the user to click another noun (or a cancel button).
5. User clicks a monkey.
6. Game gives the cheeseburger to the monkey.

Implementation-wise, each object in the game needs to have data for:

1. Which set of verbs you can apply to it.
2. For verbs it allows that take an object, which set of objects can be applied.
3. For each verb or verb-object pair, the behavior to perform when the user does that.

Since the grammar doesn't really nest or anything, you shouldn't need something as complicated as an interpreter pattern.

# Answer
> 2 votes
I present simplistic solution. It can be extended of course.

I think simple list of **(verb, object1, object2)** would solve it:

* if player clicked object (verb) "use" and clicked object "balloon" and player clicked object "pump" and there exists triplet ("use", "ballon", "pump") then You "used ballon with pump"
* Sometimes object2 would be NULL like in "use helium" (use, helium, NULL)
* Require player to click on object verb first
* if player clicks on something which does not match anything say "I can't do this, this is nonsense"
* Of course You should check after every click if the sequence is correct.

How to handle defaults:

* If first click is not on verb object, search for possible default action.
* One way to store defaults would be to make quadruplet **(verb, object1, object2, is-default)**
* Other way to store them would be to have list of default triplets
* ...

Some examples:

* (use, ballon, pump)
* (give, John, potato)
* (walk, piranhas, NULL)
* (use, ballon-in-inventory, pump)
* (open, door-to-roof, NULL) , default .... example of default action

It can be extended:

* add some events to be triggered (give player something, player will say "I can't do that because I am a mighty pirate", start cut-scene, change something in world ...)
* add some preconditions. Sometimes the ballon might be in cage, so You would need to express "if ballon is not in cage". I think I might approach this with event calculus or prolog or do it with function pointer ...
* sometimes the sentence in commandline would not be "look at hole" but would be rewritten to "look into hole", this requires just a variable :)

# Answer
> 1 votes
There's two problems here: Interpretting the player's input into a syntax tree, then exectuing that tree.

For the first stage, I'd have each verb button create a concrete verb instance derived from some verb interface. That instance would be passed further nouns or verbs for validation. If valid, it would attach the noun to its internal syntax tree, else it would reject with an appropriate error.

After each button press, you could ask the verb tree if it was in a valid state to proceed (for the Monkey Island-style input).

Once on to the second stage, the concrete verb would be responsible for parsing its own tree and updating the game state.

A more complex solution would involve parsing the tree externally to the verb. Each tree element would be responsible for small actions that together produced the desired result. This approach would allow you to make more emergent sentences from small building blocks.

Check out the Interpreter pattern for more info on the parsing stage.

---
Tags: adventure-games
---


title: Character Animation Library

text:
# Question
Title: Character Animation Library
I am looking for character animation library which can be included in my game engine.

I prefer FOSS but, paid is good if it's price is reasonable.

So, far what Ive found is Cal3d.

Can anyone tell, what are the other options?

I am also interested in Havok Animation which comes in the free bundle of Havok. Any thoughts about this one?

# Answer
You could try Animadead, but that's about as dead as Cal3d. Assimp is also a possibility if you design your models using some sort of modeling software. There may be better options out there though... This gamedev post may be helpful.
> 3 votes

# Answer
Ive also noticed I can use ogre animation code. Though, I wonder how easy/hard its gonna be. But, its also another possibility.
> 1 votes

---
Tags: c++, animation
---


title: Component-based entities without IDs?

text:
# Question
Title: Component-based entities without IDs?
I'd like to know if someone has found a way to build a component-based entity system in their game(s) without using IDs. I find that IDs tend to do away with one of the major (possible) advantages of OOP: not having to be aware of the type of a certain object.

# Answer
Your entities *need* ID's in some form or another, if you want to persist them to disk, or pass them over a network. Thus, what you probably want is not to *get rid* of ID's, but to *dynamically generate* them so you don't have to set them manually in the code every time you create a new Entity-class.

I've done this in my latest C# project by creating a special List class that assigns a unique index to every item added to the list. Unlike a normal list, when an item is removed, the indices for the rest of the items don't change (Internally it's implemented using a `Dictionary`).

Thus, as long as the entities are added to the list in the same order every time the executable is run (or, for networking, between all clients), they will always have the same ID.

---

The problem with this solution is that it's not in a human-friendly format. To fix this, you could use reflection to prepend the type-name.
> 2 votes

# Answer
I use IDs (for entities, not components), though I could do without them if I didn't want weak referencing for purposes of persistence + lazy loading. Mine do not defeat polymorphism as you describe, though. Try having your IDs provided by a universal registry and accessed via a standard interface.
> 1 votes

---
Tags: component-based, entity-system, polymorphism
---


# Question
Title: Build a handshake server for a multiplayer game
I'm making a multiplayer mode for a game I developed, and it works over UDP.
What I need now is a server to let a player know another player, and send each one the other's IP.
I own a VPS that I'm currently using to host a few websites, so I guess I can use it for this purpose too.

I would choose Python as a language to build it. But I don't know where to start...
Should I make it on HTTP or TCP?
Is there any library I can use to simplify the work?
Or any example of something similar?

Any help will be appreciated.

# Answer
> 6 votes
First of all, HTTP and TCP are protocols for entirely different purposes.

TCP is a transport layer protocol designed to transport information inside a network from one end to the other in a reliable way.

HTTP is an application-layer protocol designed to get application-specific information across a given connection. It does not care about how the information is transported (other than the fact that it uses TCP to transport data), it just cares about how the information is formatted.

Asking "Should I use TCP or HTTP" is like asking "Should I use a hammer or nails to put that picture on the wall?".

As for your problem: I would strongly suggest that you simply build your own protocol and use it. It's not that hard. You get your connection up (usually through UDP, but since latency won't be an issue for your handshake server, TCP will be fine and easier to handle, too) and literally just send a bunch of text messages across the connection.

For example, a basic network protocol for your needs could look like this:

```
-Client sends "HELLO, I'M [YOUR NAME]"

-Server registers name.

-Client sends "GIVE LIST" to server

-Server sends the names of a whole bunch of players

```

After client selects server in your GUI or whatever you have set up:

```
-Client requests IP address of player by sending "GET [PLAYERNAME]"

-Server sends IP address of player

-Client connects

```

It's literally as simple as that. Thanks to TCP your server will know who sent the requests and can answer accordingly, and TCP also handles packet transfer, so you don't have to worry about ACKing and such.

Of course, it is not **that** simple. If your server would run like that, it would be pretty vulnerable to distributed denial of service attacks (although your v-server provider might already take care of that for you) and there are of course other issues, like player identification (you might not want anyone to log onto your server), traffic minimization (making the messages a little more cryptic in order to send a few characters less per message) and so forth. But you should be able to figure out the rest.

If you're asking about how to transfer stuff across a network in general, you should google "sockets" in addition to the name of the programming language that you're using.

# Answer
> 3 votes
Because this server will be handling relatively little traffic and only has to be talked to to set up a game, it probably wouldn't be *terrible* to make it an HTTP-based service. I would tend to advise rolling your own application-level protocol over TCP anyway, though, if only because it's of fairly major concern here whether a client is still there and waiting for a game, and HTTP complicates that considerably with its pesky statelessness.

As far as examples go, here, have some pretty good, well-commented example code for a general network service daemon in Python that you can start building from.

---
Tags: multiplayer, server
---


# Question
Title: Best practices for playing sounds in iPhone games
What are the best practices for playing sounds in iPhone games? Specifically, what are the best practices while playing sounds simultaneously without affecting other processing much. Is there any recommendation about how sound files must be made to suit the processing?

# Answer
> 6 votes
From Technical Note TN2199, relative to the use of OpenAL

* Use the alBufferDataStatic API, found in the oalStaticBufferExtension.h header file, instead of the standard alBufferData function. This eliminates extra buffer copies by allowing your application to own the audio data memory used by the buffer objects.
* If your application renders several audio buffers simultaneously, you should typically use a lower sample rate, such as 22kHz. When rendering a single source, a 44.1kHz sample rate may be most efficient. Experiment and analyze the performance of your application. Individual circumstances determine the best tradeoff between sample rate and the number of audio sources being rendered.

A link with general audio tips for iPhone.

And my personal opinion:

* Preload the sounds into memory ( load screens is the better place for this ).
* Use formats with high compression to take less memory. Like .ogg.
* To the musics, try to load them via streaming, because them can occupy a lot of memory.
* The spacial sounds ( sounds with a position ) needs to be mono, if the game needs them, it's a memory saving.
* Put a sample limit, more than 5 or six sounds at same time can be confusing and they don't contribute.
* If your game is developed in c++, you can use a library like cAudio or make yourself a OpenAL wrapper, these approach has the benefit that you only has the functionality that you needs.
* **Rule of thumb**: don't allocate/deallocate memory into gameplay. This is applicable to sounds and the other resources like images.

# Answer
> 1 votes
there is a game engine named cocos2D, and it contains an audio engine named cocosdenshion. it's a three layer object oriented sound engine. you can easily select a layer and starting working with that. and it's all based on openAL, you can surly get enough ideas from cocosdension even if you don't want to use it directly. and it's under **MIT License** so you can use that without any worry.

---
Tags: iphone, sound, openal
---


# Question
Title: How do you handle animations that are for transitioning between states?
How does one usually handle animations that are for going between a game object's states? For example, imagine a very simple game in which a character can only crouch or stand normally. Currently, I use a custom Animation class like this:

```
class Animation{
 int numFrames;
 int curFrame;
 Bitmap spriteSheet;
 //... various functions for pausing, returning frame, etc.
}

```

and an example Character class

```
class Character{
 int state;
 Animation standAni;
 Animation crouchAni;
 //... etc, etc.
}

```

Thus, I use the state of the character to draw the necessary animation.

```
if(state == STATE_STAND)
    draw(standAni.updateFrame());
else if(state == STATE_CROUCH)
    draw(crouchAni.updateFrame());

```

Now I've come to the point where I want to draw "in-between" animations, because right now the character will just jump immediately into a crouch instead of bending down. What is a good way to handle this? And if the way that I handle storing Animations in the Character class is not a good way, what is?

I thought of creating states like STATE\_STANDING\_TO\_CROUCHING but I feel like that may get messy fast.

# Answer
If anyone is curious, this is how I ended up implementing it:

USing my example, I got rid of exclusive playerStates, and simply used different boolean flags like isCrouched.

Then I would have something like this in my PlayerObject's update() function

```
if(isCrouched)
{
    if(currentAnimation == startingCrouchAnimation && startingCrouchAnimation.isFinished())
        currentAnimation = crouchedAnimation;
}

```

and to draw the animation

```
draw(currentAnimation.update());

```
> 3 votes

# Answer
In between states are still states, more in general transient states should be modelled as states if their duration exeedes the frame duration; otherwise one should consider if appropriate on a case by case basis.
> 5 votes

---
Tags: animation, sprites, state
---


# Question
Title: How can I hook into OpenGL initialization on Windows?
I want hook all OpenGL games/applications. I want load my library only if application actually use OpenGL. Something like `Direct3DCreate9` for Direct3D 9 or `CreateDXGIFactory` for Direct3D 10/11.

I thought this function `wglDescribePixelFormat`, but some app's/games not use it.

# Answer
`wglCreateContex` is what creates an OpenGL context on Windows, but it isn't the only way anymore. There is also `wglCreateContextAttribARB`, which is an extension function (and thus paradoxically means that you need to have created an OpenGL context already). This is used to create OpenGL 3.2+ core contexts.

I don't know what you intend by "load my library," but if you're trying to hook into all of OpenGL's stuff, to get every OpenGL call, then glIntercept is probably the place to look.
> 2 votes

# Answer
I am not sure about it, but `wglCreateContext` seems to be the first one. PIXELFORMATDESCRIPTOR is a structure.

and platform to platform context creating is the first one and its initialization varies. Like when you are using glut/freeglut, you can get started without creating context manually or describing pixel format.
> 0 votes

---
Tags: opengl, windows
---


# Question
Title: Changing multisample count or disable/enable multisampling while the program runs?
How can I disable or enable multi-sampling live while the program is rendering?

I tried this.

```
    public override void Draw(GameTime gameTime)
    {

        GraphicsDevice.PresentationParameters.MultiSampleCount = 0;

        ... draw stuff ...

    }

```

But it doesn't disable the multisampling while drawing, because setting "PreferMultiSampling" to true under the presentation parameters when starting the program apparently overwrites this. Or am I wrong?

How can I do this?

# Answer
> 3 votes
`PresentationParameters` tells you the current settings of the `GraphicsDevice`. It's a readout. You're not supposed to modify it.

You need to change the settings on the `GraphicsDeviceManager` (see MSDN, the default template creates one called `graphics` as a member of your `Game` class), and then call `ApplyChanges()`.

---
Tags: xna
---


# Question
Title: Which 3D file format should my engine use if I don't want to have to change it later?
Is there a de facto format for exporting a 3D model from modeling software to a game engine?

I know it varies by engine and situation, but what is the general idea that comes to a skilled game developers mind when this question comes up?

In my mind obj format comes up, but it doesn't support animation.

So, what could be the best format which supports/covers more or less every feature that an modern engine can cover? FBX? Collada?

Some professional insight would help.

# Answer
> 9 votes
There is no "best format"; there is only varying levels of annoying.

Collada does pretty much everything you could possibly want to do, at the cost of doing everything you *don't* want to do as well. This makes it a useful interchange format, but not something you should probably be looking to load directly into your game.

FBX isn't quite as widely supported, being a proprietary format. And it's... a proprietary format, but at least the format specification is available.

Most game developers need to massage the data, whatever the kind, into something their game can load and throw onto the screen as fast as possible. Therefore, most game engines that support the interchange formats will use an off-line tool to transform them into their game-specific formats.

And that's generally a good way to work. You have a good separation of code: the code that massages the data is separate from the code that loads it into your game. You get fast loading performance, while still having the ability to format the data as you need for maximum speed and use. And you still can see what the data looks like in your original exported file format, which is generally some kind of text file.

---
Tags: file-format
---


title: Android landscape mode game

text:
# Question
Title: Android landscape mode game
I am beginner in android game development. I want my game to run only in landscape fullscreen mode (currently I have Optimus 2X with resolution 800x480 in landscape), and I don't know how to set it.

I found the fullscreen mode settings, and tried some landscape mod (set orientation:landscape in AndroidManifest), but the game is now crashing and its very unstable (eg. when i change phone orientation).

So is there any way to do that?

# Answer
> 2 votes
I'm currently working on a full-screen Android game that runs exclusively in landscape mode. Here are the tweaks I've made to force landscape mode and prevent application restarts:

# Intercept orientation change events

Add the following **android:configChanges** to your AndroidManifest.xml

```
<activity android:name=".FirstGame"
          android:label="@string/app_name"
          android:configChanges="orientation|keyboardHidden">

```

Override onConfigurationChanged in your Activity to prevent application restart

```
@Override
public void onConfigurationChanged(final Configuration newConfig)
{
    // Ignore orientation change to keep activity from restarting
    super.onConfigurationChanged(newConfig);
}

```

# Forcing full-screen landscape orientation

In the onCreate function of your Activity, add the following code to set window fullscreen and remove title bar, and force landscape orientation

```
import android.view.Window;
import android.view.WindowManager;
import android.content.pm.ActivityInfo;

@Override public void onCreate(Bundle savedInstanceState)
{
    ...

    // Set window fullscreen and remove title bar, and force landscape orientation
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    ...
}

```

# Answer
> 1 votes
If you have more than one activity that you are using, you are going to need to set the orientation for all of them to landscape, if you have one as landscape and another as portrait. When you switch over to the other activity it will crash unless you have it set up properly to do that. If I knew how to post the code from my manifest to where it shows up I would.

The link explains if you want to switch between orientations.
http://developer.android.com/resources/articles/faster-screen-orientation-change.html

---
Tags: 2d, android
---


# Question
Title: How do I prevent loop that moves character to run twice? (Javascript)
I managed to make a simple loop to move my character, onmousedown I move the character diagonally to where the user clicked. It's working but my problem is that I don't know how to prevent more loops to start over the first if the user clicks more than once.

Right now if you click more than once the character moves faster and faster since more loops are running at the same time.

This is the loop:

```
(function move() {
    if(cframes<frames) {
    cframes = cframes+1;
        character.style.left=parseInt(character.style.left)+pxsecx;
        character.style.top=parseInt(character.style.top)+pxsecy;
        setTimeout(move, 20);
}
})()
}

```

How do I prevent this loop from starting if it already has? or stop it and start another? Thanks

# Answer
> 6 votes
One way of solving it is to not call the move function when clicking but only set the desired destination where you want to move the character (and trigger a main loop if it's for some reason not already running) and let the main loop move the character towards the destination.

See tips for writing the game loop question and this StackOverflow question titled best way for simple game-loop in Javascript.

# Answer
> 1 votes
setTimeout() returns a timer ID that can be passed to clearTimeout() later to cancel it. Store it in a variable somewhere and cancel the old one in the event callback. See https://developer.mozilla.org/en/window.setTimeout for more details.

# Answer
> 0 votes
**Do not allow click() handler to cause movement until some time passes**

Basically do not allow clicking faster than some value and allow it only once at the same time. :)

There is how You can do it:

Create global variable:

```
var not_yet; // it represents delay
// * when someone clicks it is set to nonzero
// * timer will decrease it until zero
// * if it is zero, then it will wait for user click
// * if it is zero and user clicks, then character is moved and it is set to nozero

```

Add a timer, which You will call each few miliseconds, and which will do this:

```
if (0 < not_yet) {
// it is a clock which is decreasing since the previous click
// this way together with this (1) check You prevent from
    not_yet -= 1;
}

```

In handler of the click event :

```
if (0 < not_yet) { // (1)
    return;
// user clicked few milliseconds ago
// it is not right time yet
} else {
    // do whatever You did there previously

    not_yet = 5; // start the timer and set it to delay for 5* units
    // *5 is arbitrary, set it to whatever value will work the best for You
}

```

---
Tags: javascript
---


# Question
Title: Better animation of elements in SFML/C++
This is not about animating individual characters or elements, I'm happy with spritesheets for that. What I'm looking for is the animation of elements on screen.

For example my game starts and the logo comes in flying from a random direction, then rotates or something and stops in one position, then a game character (one or more) comes from the side and does some action.

I haven't done many projects yet, I have written just one complete game, so I don't know whether I've correctly worded the question.

What I've been doing is giving the element an initial and final position and make it move accordingly and using status flags to check its state. The problem is when I want to move it in more than one way. Of course, I can just use the state variables and make it move, but I've been thinking there's got to be an elegant method for it

EDIT: I'm looking at animations such as in World of Goo etc.

# Answer
> 4 votes
This seems like you want to manipulate the position and rotation of objects over time. AFAIK sfml does not provide this functionality out of the box, but it should be pretty easy and straightforward to implement this on your own.

I once built a similar solution for a three dimensional simulation, but it should translate well to a 2D graphical application.

First of you have two concepts: the `Manipulator` and the according `ManipulatorManager`. `Manipulator` is an abstract base class for all kinds of manipulations of a specific object, for example a sprite. Manipulated can be all properties like position or rotation, move on a path or anything similar. The `Manager` watches the state of the `Manipulators` and updates them every frame.

The interface for the manipulator looks something like that:

```
class Manipulator {
public:
    Manipulator(float expiration_time) : expiration_time(expiration_time);
    bool is_expired() { return expiration_time < 0.f; }
    void update(float dt) { this->expiration_time -= dt; }
protected:
    float expiration_time;
}

```

An implementation of this class is the `SimpleLineManipulator` which influences the position of a sprite over a certain time on a straight line:

```
class SimpleLineManipulator {
    SimpleLineManipulator(Sprite *spr, Vector2f begin, Vector2f end, float expiration_time);
    ...
private:
    Sprite* sprite;
    Vector2f begin, end;
    float total_time; // initialized with expiration_time
}

```

And this is how the update method looks like (where the most of the work takes place):

```
void SimpleLineManipulator::update(float dt) {
    Manipulator::update(dt);
    Vector2f position = lerp(end, begin, total_time/expiration_time);
    spr->SetPosition(position.x, position.y);
}

```

All you have to do now is call the `update()` method every frame. It should be easy to implement a rotatory manipulator or manipulators that work on a path (a list of positions). You can now also combine these manipulators to create combined effects.

I hope I could outline the architecture in a clear manner. Feel free to ask :)

# Answer
> 1 votes
Constantinius already provides a good starting point from where you might start with actual coding, but in case you want to know about what you're doing here in general, I'd like to add a few words.

Translating objects over time from point A to point B is done by applying a function f(x) to the position of the object, where x can be anything, ranging from simply the current position of the sprite to the amount of time that elapsed between two frames, etc.

This process is usually done via the help of a sub field of numerical analysis which is called interpolation.

A common example would be linear interpolation. If you know the constant starting point A and end point B, one possible function would simply be f(t) = A + (B - A) * (t\_max - t) , where

* t is the time elapsed since the object started from point A
* t\_max is the time you want the object to take until it reaches its destination
* 0 \<= t \<= t\_max .

As you see, the function is returning a vector, so you can apply it to the position of your object without problems.

This is of course only a rough introduction to maybe let you taste a little blood and wake your interest, hence I shall redirect you to Google if you want to know more about it.

---
Tags: c++, animation, sfml
---


# Question
Title: The best way to communicate between multiple iPhones/iPads in a card game
I have been looking around for information about this topic but not found what i need.

Here is the scenario, i am planning a card based game (cocos2d) where the idea is that up to four players should be able to play.

One player will hand out the cards to all four and then they play. Next round the next player should do this and so on..

On the screen i would like the actual player to see his/her own cards as well as the others cards that they have played out meaning that each player should see the others active cards.

I would like to ask the following:

1. How would be the best way of implementing this from a communication point of view?
2. Would this go via game center?

A reference to information is appreciated.

Cheers

# Answer
> 0 votes
Peer-2-Peer has advantages (scalability, no server cost), but several disadvantages:

* you need lots of communication with more than 2 players
* cheating
* handling of dropping players
* master election (dealing cards, decisions etc)

iScat from Mobilebits for example uses an authorative (client/server) based approach.

* Photon
* free for up to 100 CCUs (concurrent users)
* support iOS, Android, HTML5, Flash, ...

You can easily combine this central matchmaking with gamecenter as well.

# Answer
> 1 votes
I always suggest to try to stay peer-to-peer in communications. This generally avoids bottlenecks and single-point-of-failures, in other words it scales.

In you case i would set up an Reliable UDP connection and use a reactor to unify network and gui events.

Obviously this does not resolve the problem with Service advertising beyond the local network, in this case an index server can not be avoided.

I am aware that this is only an arhitectural indication; I can't help you more to the point because of my lack of experience with cocos2d but I hope this can help anyway

---
Tags: iphone, networking, cocos2d-iphone
---


# Question
Title: in XNA 4.0, How to get the matrix or Vector3 of a model?
I'm trying, for many days, to get the Matrix or the Vector3 of my 3D model, I don't want to use the World matrix because I need first to idenfy the axes of my object for animation (= rotation of a second object around my first object).

If you have an idea or a tutorial for this ?

Many thanks,

Jeangil

# Answer
> 6 votes
The "matrix" of an object in model space with no transformations applied is simply:

```
Matrix.Identity

```

Similarly the position would simply be:

```
Vector3.Zero

```

The "world" matrix is responsible for transforming an object that is in model space into world space.

To make object A orbit object B you could do this with object B's world matrix. Simply apply an appropriate orbit matrix (translation then rotation), followed by object B's world matrix, to object A. This will then be object A's world matrix.

Alternately: you could take object B's world matrix and use the appropriate `Matrix` properties: `Translation` to get the position and `Forward`, `Left`, `Up`, etc (MSDN), to get the appropriate axes for constructing the series of transformations to orbit object B.

# Answer
> 1 votes
It sounds like you may be looking for the **bone transforms**, which define transforms for each mesh in a model relative to the model's coordinate system. This lets you, say, rotate a car wheel about its own axis, and keep it correctly positioned relative to the car chassis.

Assuming that you have already loaded a model with

```
var model = Content.Load<Model>(@"mymodel")

```

You can easily get to the bone transforms with

```
model.CopyAbsoluteBoneTransformsTo(transforms)

```

See this link for a decent explanation, or this one from Riemer's.

This XNA App Hub sample demonstrates loading a tank model, and having its wheels and turret move relative to the model.

The basic idea is that different meshes (in this case, the wheels and tank) are connected via "bones." Bones represent a hierarchical relationship between model elements (despite the name, they are not exclusive to animal or human models).

In your 3D modeling app of choice, you define bones connecting child meshes (wheels) to parent meshes (the tank chassis), and define transforms in the child mesh's space that transform the mesh relative to its parent.

By using the `.CopyAbsoluteBoneTransforms()` method, you can quickly concatenate the child's transforms with the parent. This has the effect of putting the child mesh in the parent's coordinate space, so that you'll get a valid result when you multiply the result by the view and projection matrices.

---
Tags: xna-4.0
---


# Question
Title: Determining the location of installed/on disk game assets
I've been thinking a lot about the best way to store and load assets in your filesystem. By this I mean where in the file system to store them, and how to retrieve them when loading etc., as opposed to how their stored when the program is actually running. I would imagine that this would be a fairly common question, but I can't seem to find it anywhere else, perhaps because I'm not asking it properly.

So far, I have found two strategies, and I would like to know what other ones there are.

1. Storing the assets in an absolute path on the system. You may have to get the users home directory if the user doesn't need to be an admit/root to install the game, and other OS dependant stuff would probably need to be done to ensure that the path is actually valid, but it seems like this could work well.
2. Get the game's location on the system, and assume that assets can be found in an adjacent directory. I don't think there is any OS independent way to do this, but it does seem feasible. This might be nice as it doesn't require the user to install the game, making it all around more portable, but it does seem like it would destroy an OS paradigm where specific portions of the game when in a certain place in the os (say /usr/games, and the executable would go in a different directory).

Both of these ways do seem a bit clunky, so are there any other ways to get the location of your assets? Otherwise, which is used more in games you've worked on? Thank you.

# Answer
You're over-engineering this =)

Windows games have two different storage areas:

The first is for static data with the installed program and these files are almost always referenced relative to the application itself, or defined in a file (XML usually) that the program loads when it starts up so there are no hard-coded references. Using the Windows Registry to store paths has fallen out of favor.

The second is for user data like saved games, and there is a standard API for working with that directory. On recent Windows the standard security setting stops a user from saving data to the program area, which is why this is done. On Linux, which I am no expert, I'd assume this directory would be a convention to use /usr/games or something in the /usr directory space.
> 8 votes

# Answer
I think that the most elegant form is to abstract the filesystem and to do it operating system independent. This abstraction is responsible of determine the operating system that is running the game and get the real path of the game executable. Then all your code that accesses to resource paths are always relative to the directory that you want. For example, separate always the directories with / ( unix, window, osx ) the operating system doesn't matter because the wrapper abstract this.

Normally the resources are grouped, because if you are in main menu, you only wants to load the resources in main menu. Then the wrapper can have the hability to generate groups, and maybe to search inside this by name. ( this approach doesn't use paths, once the groups has been created ).

The boost file system library here is a form to facilitate the creation of the filesystem wrapper.
> 1 votes

---
Tags: assets, filesystem
---


title: Loading a Texture2D Array in DirectX11

text:
# Question
Title: Loading a Texture2D Array in DirectX11
How does one create a Texture2D Array in DirectX11? The texture I am trying to create is not multisampled, and I want only one mip level. I can't find a working example of a Texture2D Array. I have a buffer of 2D images that I want to use as a Texture2DArray in a shader.

The following code snippet works when sTexDesc.ArraySize=1 (as a Texture2D). With sTexDesc.ArraySize=2 the subsequent call to CreateTexture2D crashes with this Access violation inside DirectX:

> `Unhandled exception at 0x000007fef5d6771a in test.exe: 0xC0000005: Access violation reading location 0xffffffffffffffff.`

With larger values of ArraySize CreateTexture2D returns E\_INVALIDARG. ubImageStorage contains valid data. As a Texture2D I can add multiples of the slice offset to this buffer address when assigning pSysMem and read each slice from a shader. What am I missing? I have tried all combinations of bind and usage flags and various values for MipLevels with no success.

```
D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = 1024;
sTexDesc.Height = 1024;
sTexDesc.MipLevels = 1;
sTexDesc.ArraySize = 2;
sTexDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_IMMUTABLE;
sTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA sSubData;
sSubData.pSysMem = ubImageStorage;
sSubData.SysMemPitch = (UINT) (1024 * 4);
sSubData.SysMemSlicePitch = (UINT) (1024 * 1024 * 4);

ID3D11Texture2D* pTexture;

hr = m_pd3dDevice->CreateTexture2D(&sTexDesc,&sSubData,&pTexture);

```

Here are the relevant pages from MSDN:
ID3D11Device::CreateTexture2D Method
D3D11\_TEXTURE2D\_DESC Structure

# Answer
> 5 votes
(Note: This is the answer originally provided in the question body by the OP).

Problem solved. I needed to create an array of D3D11\_SUBRESOURCE\_DATA elements, one for each element in the Texture2DArray. Like this:

```
D3D11_TEXTURE2D_DESC sTexDesc;
sTexDesc.Width = m_uTextureWidth;
sTexDesc.Height = m_uTextureHeight;
sTexDesc.MipLevels = 1;
sTexDesc.ArraySize = 16;
sTexDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sTexDesc.SampleDesc.Count = 1;
sTexDesc.SampleDesc.Quality = 0;
sTexDesc.Usage = D3D11_USAGE_IMMUTABLE;
sTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
sTexDesc.CPUAccessFlags = 0;
sTexDesc.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA *sSubData = new D3D11_SUBRESOURCE_DATA[16];
for(int i=0; i<16; i++) {
    sSubData[i].pSysMem = ubImageStorage;
    sSubData[i].SysMemPitch = (UINT) (1024 * 4);
    sSubData[i].SysMemSlicePitch = (UINT) (1024 * 1024 * 4);
}

ID3D11Texture2D* pTexture;

hr = m_pd3dDevice->CreateTexture2D(&sTexDesc,sSubData,&pTexture);

delete [] sSubData;

```

Note that I've replaced the variables in the code above with constants, but allocated the D3D11\_SUBRESOURCE\_DATA array dynamically because its size is unknown at compile time.

Why would you ever have different slices with different pitches? Is that even really supported? That seems really strange.

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


# Question
Title: In an artillery game how do I mask out the part of the terrain that was hit
Let's say I want to make a **really** simple artillery game, something like Gorillas. I don't have any experience in games, just some basic understanding of OpenGL. I want to do this for fun and to learn something.

I figured out how to simulate gravity and generate simple terrain and how to do some collision detection. But I have no idea how do they mask out the part of the terrain that is hit with a projectile that leaves a hole in form of a circle.

I tried enabling stencil buffer and put a quad which has a circle texture on it expecting to mask out only the circle part, but it masked out the whole quad -- I mean it was a rectangle shaped hole and not a circle shaped one. Next I thought maybe some blending will do the trick but I didn't figure it out how. Or should I just draw a polygon with many edges to look like a circle and use that instead (with the stencil buffer)? I'm just curious how it is done. Can someone point me in the right direction?

# Answer
I ended up using only one texture and I drew holes in it. Circles with 0 alpha values. My original idea was to separate the mask from the terrain somehow but I'm a total noob to opengl, I don't know what can be and can't be done. I used the information from here: Implementing a 2D destructible landscape (like Worms) and this also helped How do I draw anti-aliased holes in a bitmap.
> 1 votes

---
Tags: opengl, c#, terrain, opentk
---


# Question
Title: Is the 3.x version of the Android SDK compatible with a version 2.1 phone?
i am just starting android app development. I was downloading SDK via the Android Manager. I had to select the SDK versions. I have a phone of android 2.1 So i selected only SDK 2.1 and its samples as to download all it takes too much time. If i download the latest SDK 3.X will it be compatible with my mobile?

# Answer
> 2 votes
By default, if you use the 3.x SDK, earlier phone won't be compatible. But if you need special features from a SDK level (for example Open GL ES 2.0 is only available since 2.2), you can force compatibility in your manifest :

```
<uses-sdk android:minSdkVersion="7" />

```

You should then detect in your code which version of the OS is used at runtime and change your implementation accordingly :

```
switch (android.os.Build.VERSION.SDK_INT){
    case android.os.Build.VERSION_CODES.ECLAIR :
        // do something
        break;
    case android.os.Build.VERSION_CODES.FROYO:
        // do something else
        break;
    case android.os.Build.VERSION_CODES.HONEYCOMB:
        // do something else
        break;
}

```

Finnaly, i'd suggest you take a look at the Target Devices page to choose which version to target (unless again you need a specific feature from the 3.x SDK).

---
Tags: android
---


# Question
Title: LWJGL Rendering a 2D Object at a Certain Position On-Screen
Okay, so in LWJGL, how can I render a 2D object (maybe for like a menu, or meter that shows up on screen during the game), and have control over size and position on screen? So I can tell it what position relative to the screen. It is a 3d game using gluPerspective (as opposed to glOrtho).

# Answer
You can render the normal game objects using perspective view, and then when the render func is done with that, switch to orthographic view and render your GUI or whatever it is, this way.

Using glOrtho you can define your screen going exactly from left 0 to right 1 and the same for bottom and up. Since there is no perspective distortion anymore, those coordinates directly map to screen coordinates then.
> 3 votes

---
Tags: 2d, 3d, rendering, lwjgl, screen
---


# Question
Title: CubeRealm OpenGL rotation problems, need help. :\
I'm totally new to OpenGL and I'm working on a Sandbox game called CubeRealm. My problem you see is rotation. I've got it in my head that to rotate the 'camera' I just rotate all the scene by the negative value of the camera's rotational values. However so far it seems to not be working.

Here's the code snippets:

```
glPushMatrix();

lighting();
/*
 (640^2)/(64^2)=amount of cubes on one 640x640 plane(409,600,4,096)
 */
//TODO: fix z axis problem for translating
glRotatef(-player.camera.rotation.x,1.0,0.0,0.0);
glRotatef(-player.camera.rotation.y,0.0,1.0,0.0);
glRotatef(-player.camera.rotation.z,0.0,0.0,1.0);
renderGrid();

glPopMatrix();

glutSwapBuffers();

//SNIPPET2...

case LOOK_UP:
    if(player.camera.rotation.y!=-90.0){ //if they are not looking up
        //make them look up
        player.camera.rotation.y-=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case ROTATE_LEFT:
    if(player.camera.rotation.x!=0.0){
        player.camera.rotation.x-=90.0;
        //TODO: set direction the camera is facing in
    }else{
        player.camera.rotation.x=360.0;
        player.camera.rotation.x-=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case LOOK_DOWN:
    if(player.camera.rotation.y!=90.0){ //if they are not looking down
        //make them look down
        player.camera.rotation.y+=90.0;
        //TODO: set direction the camera is facing in
    }
    break;
case ROTATE_RIGHT:
    if(player.camera.rotation.x!=360.0){
        player.camera.rotation.x+=90.0;
        //TODO: set direction the camera is facing in
    }else{
        player.camera.rotation.x=0;
        player.camera.rotation.x+=90.0;
        //TODO: set direction the camera is facing in
    }
    break;

```

When I press the right arrow key(rotate to the right) it doesn't rotate also when I rotate up(up arrow) it goes weird instead of allowing me to see the top of the skybox it still shows me my test cubes.

So guys how do I fix the rotation, what am I doing wrong?

Note the 'TODO: set direction' stuff is for my local axis system. Those TODOs are irrelevant to the question.

# Answer
> 0 votes
LOOK\_UP and LOOK\_DOWN must rotate around the x-axis, not around the y-axis.

ROTATE\_RIGHT and ROTATE\_LEFT must rotate around the y-axis, not around the x-axis.

Immediately rotating around 90 degrees or initializing your angles with 90 degrees will bring your system into a Gimbal Lock state, resulting in weird rotations. You might want to use smaller angles and step-sizes for starters, particulary not 90 degrees or multiples of it.

Initialize all angles with 0 and start from there:

```
    // init your angles at startup, i.e. main or camera constructor
    player.camera.rotation.x = 0.0;
    player.camera.rotation.y = 0.0;
    player.camera.rotation.z = 0.0;

    // change the step-size and rotation-axis like this:
    case LOOK_UP:
        player.camera.rotation.x+=5.0;
        break;
    case ROTATE_LEFT:
        player.camera.rotation.y-=5.0;
        break;
    case LOOK_DOWN:
        player.camera.rotation.x-=5.0;
        break;
    case ROTATE_RIGHT:
        player.camera.rotation.y+=5.0;
        break;

```

---

Edit: After reviewing your code, here is the list of the bugs, the most important ones are 3), that messed up all the rendering, and 4) the correction for the camera rotation code

1. Off by one error in void setupGrid(), change "\<=" to "\<" in the while

```
while(_i<GRID_SIZE){

```
2. set the initial camera position to {0, 0, 5} in Initialize(), otherwise you wont see the boxes:

```
player.camera.position.x=0;
player.camera.position.y=0;
player.camera.position.z=5;
player.camera.rotation.x=0;
player.camera.rotation.y=0;
player.camera.rotation.z=0;

```
3. in Reshape change 3rd param of gluPerspective to 1.0

```
gluPerspective(45.0,(double)screenWidth/(double)screenHeight,1.0,CUBE_UNIT*100.0);

```
4. Finally the correction of the camera rotation code in Keyboard2() like already written above

```
    void Keyboard2(int key,int x,int y){
        switch(key){
            case GLUT_KEY_F1:
                if(!wireframe){
                    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
                    wireframe=TRUE;
                }else{
                    glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
                    wireframe=FALSE;
                }
                break;
            case LOOK_UP:
                player.camera.rotation.x+=5.0;
                break;
            case ROTATE_LEFT:
                player.camera.rotation.y+=5.0;
                break;
            case LOOK_DOWN:
                player.camera.rotation.x-=5.0;
                break;
            case ROTATE_RIGHT:
                player.camera.rotation.y-=5.0;
                break;
        };
        return;
    }

```

# Answer
> 0 votes
The problem is that you can't simply add and subtract values from rotation. These values need to be calculated using math formulas using trigonometry. I was designing a project a while back and needed a camera to move in 3d space. Check out this project and the camera class from it. It will do precisely what you need granted you want to move freely in 3d space with minimal code.

http://www.paulsprojects.net/opengl/q3bsp/q3bsp.html

Edit: Here is another more straightforward example with the math involved as well: http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=Quaternion\_Camera\_Class

Nehe's OpenGL tutorials are a fantastic reference for beginners but if you are going to go much further, grab an OpenGL book with current standards/practices.

---
Tags: opengl, camera, c, rotation
---


title: Collision response for 2D racing game

text:
# Question
Title: Collision response for 2D racing game
The title is fairly self-explanatory. I have a 2D racing game that utilizes per-pixel collision detection (the track is essentially two bitmaps, one for the graphics, one for collision data). The problem I'm running into is that I can't figure out how to implement the collision response. I can figure this out for situations where I have a box colliding with another box, but the fact that my objects can essentially be any shape has me stumped.

The one approach that I've had some success with is to just sample a couple of pixels near the pixels that collide, build vectors out of those and then take the cross product of that, but it fails in many scenarios. Plus, it just seems like overengineering. In fact, I'm about 103% sure that I'm just overthinking the whole problem.

Has anyone tackled this problem?

# Answer
When you have a collision you should try to understand where the collision occurred, the involved forces, the consequences of the involved forces.

Simplest case (I can tink of):

* The impact occurs in the frame the collision is detected (no compenetration)
* The colliding objects are perfectly elastic (no energy loss due deformation)
* The colliding object are disks (to be removed as soon as possible)

Under those circumstances there is conservation of total momentum and kinetic energy.

When a collision occours, there is a contact surface between the colliding bodies: they can exchange energy only through this surface; in other words the impact forces are always perpendicular to this surface.

The main conseguence to this is that you can decompone the kinetic energy vector in a radial component (perpendicular to the contact surface) and a tangential component (parallel to the contact surface) seeing that the tangential one stays the same.

Knowing the value for a component, we can consider the collision be monodimensional, restricted to the radial direction.

If we consider the second body to be still, we have some formulas for the velocity after the collision:

It is possible to compute the velocity after impact knowing the velocity before the impact for the radial coponent we needed. (the kinetic energy is ½·m·v²).

You can resolve the case where the second body is moving, by superimpose the collision effects (first-moving-second-still + first-still-second-moving) or by change the inertial reference to be linked to the second body before the impact; it is the same.

---

We can spice up the simulation by removing the geometric simplification.

First you need to compute the contact surface and to find the contat point. (I left the problem to you but you can consider to simplify the contat mode to *colliding boxes*)

With your contact surface you can compute the resulting kinetic energy vector - as explained before - but then? We have to "allocate" this energy because a rigid body can move and rotate and some energy is required to change linear or angular velocity.

To know around what point our body will rotate, we need to know the position for the center of mass: this can be precomputed since depends just by the object shape and mass distribution.

If you have a collision bitmap you can consider to sum up the position for each "on" pixel then divide for how many "on" pixel there are: this implies that the object has the same density in each point.

If you like you can use a graymap to store the density for each point: black for 0 density (body absence) and white for maximum density; by multiplying the position by the density, you can compute a weighted average: your center of mass

When you know the center of mass you need to know the moment of inertia: multiply the density of each point by the square of the distance from the center of mass and sum up.

Knowing the center of mass and the collision point, you can decompose the kinetic energy vector in a radial component (starting from collision point and pointing toward the center of mass) and a tangential component.

The radial component tells us how many impact enercy becomes kinetic energy, while the tangential component tells us how many impact enercy becomes rotational energy.

As well as the velocity is bounded to the kinetic energy so **Et = ½mV²**, also the angular velocity is bounded to the rotational energy so **Er = ½Iω²**, where I is the moment of inertia and ω the rotational velocity in radians per second.

Using those two formulas you can compute the velocity vector and the angular velocity to add to your body.

The last triky part is how to know if ω has to be clock/counterclok wise, since you will ever get a positive value.

Let *I* be the impact point and *M* the center of mass point, compute *d* = *C* \- *I*;

Let *Er* be the tangential component for the impact kinetic energy, compute , this will give you a right-handed perpendicular vector.

Now compute *d*·*E* if positive the rotation is CW else CCW
> 2 votes

# Answer
Well, In my flash games, I do have a lot of per-pixel collision detection. Since you have not mentioned your platform I'm assuming you use AS3 since, I code in as3. Well, even if you are not an Actionscript Developer, You will surely find this library useful. Just call a PixelPerfectCollisionDetection.isColliding() and pass obj1, obj2, stage, and \[(true for per-pixel collision detection) or default value of false uses bounding boxes for collision checking\]

PixelPerfectCollisionDetection

Hoping, you'd find this useful.
> 0 votes

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


# Question
Title: Creating an mouse-friendly GUI in a "sort of" Python console mode
I'm developing a real-time rogue-like game during my spare time, using Python and libtcod, to learn programming (and have some fun). I would like to create some sort of mouse-friendly GUI, just like in Goblin Camp.

This game is 90% mouse-driven, with menus, scrollbars, buttons etc. As a total noob with graphical interfaces, I just can't figure out how to do this. Example: How to display the name of a monster when the cursor is over it? I tried some ways, which more or less worked, but were always awful, impossible to maintain, hard to scale, and resource-consuming.

Is there a "simple" way to have something more like an object.OnClick() ?

# Answer
> 0 votes
If you simply need to do an Object.onSomething() probably you need to write a reactor over a object data model.

What I mean? Put every relevant objects into a container make this container available to everyone. This container will implement the method

```
def castEvent(self, eventName, args, kargs):

```

In this method you iterate the containing object looking for the method "does%s" % eventName. something like:

```
for item in self.items:
    f = getattr(item, "does%s" % eventName, lambda *x, **k : False)

```

if f evaluates True using the parameters passed to the function then you call the "do%s"%eventName with the same parameters:

```
for item in self.items:
    f = getattr(item, "does%s" % eventName, lambda *x, **k : False)
    if f(*args, **kargs):
        f = getattr(item, "do%s" % eventName, lambda *x, **k : False)
        f(*args, **kargs)

```

Every time you need to send an event - say *Click* \- you simply need to:

```
container.castEvent("Click",[],{"x":10,"y":20})

```

every object interested in Clicks has to provide a

```
def doesClick(self, x, y):

```

that manage the click events returning False or

```
def doesClick(self, x, y):
[...]
def doClick(self, x, y):

```

The first returning whether (x,y) hits the object and the second doing the click routine.

You can implement the first in a generic superclass and let the clickable classes to extend.

This is a very basic implementation whit a lot of room for improvements.

---
Tags: python
---


# Question
Title: Can I use quaternions to control an helicopter?
I'm trying to make a simplified helicopter (for the moment, it's a cube) simulation in 3D and I'm having some problems with rotation. An helicopter can rotate along the three axes :

* rotate on itself using the rear propeller : y axis rotation
* tilt left and right to go left or right : z axis rotation
* tilt up and down to go backward or forward : x axis rotation

I need to be able to control each axis individually. So far I've tried using euler angles, but whatever the order of rotation I use, either I run into a gimbal lock or some axes "switch places".

I seems that I need to use quaternions, but I don't know how to control each individual axis, since quaternions uses a direction and an angle. Should I create three quaternions and multiply them together? Wouldn't I end up with the same problems?

The weird thing is, if I use my finger to represent the three axes of my helicopter (thumb up = y, index = z, middle = x), I don't seems to run into those problems. Why?

# Answer
> 4 votes
You should be able to use either a matrix or a quaternion to store the current orientation of your helicopter. The problem you're running into is how you apply change in pitch/yaw/roll to the helicopter.

I think you want to apply pitch/yaw/roll to the helicopter in local space each frame. You can do this by taking the change in pitch/yaw/roll for that frame and constructing a rotation matrix (you can do this with euler angles). Then you rotate the helicopter's previous orientation by this matrix (with the previous orientation represented either as a matrix or as a quaternion). It will give you the orientation for the new frame.

Representing the helicopter's orientation as a quaternion has the advantage that interpolating between quaternions is much easier than interpolating between matrices. So if in the future you have a current orientation and you want to figure out the per-frame rotation that will bring you to a new orientation at a desired time, the quaternion representation may be more friendly to you.

# Answer
> 3 votes
Basically you can use every other representation of rotations, but Euler Angles. Matrices, Quaternions even Axis Angles will do what you want.

```
Should I create three quaternions and multiply them together? Wouldn't I end up with the same problems?

```

You are right, you would end up with the same problems. The key is to store the current orientation (matrix, quaternion) of your object and apply only a *delta* when changing the orientation.

When you want to turn 10 degrees around y, just create a *delta* matrix/quaternion for that and post multiply it with your current orientation (if you use post multiplication for matrices). If you multiply it the other way around, it will rotate the system around world's y-axis rather than around object's y-axis.

I find this resource very useful, it also comes with source code and explains the theory very well.

# Answer
> -1 votes
The trouble I think you might be seeing is a difference in axis rotation and velocity vectors (and also that you're missing a direction). When a helicopter tilts forward to move forward, the propulsion of the helicopter blades pushes air both down and backwards at a perpendicular angle to what you've labeled the X axis.

You have a fourth degree of freedom that you've missed: the speed of the blades controls the volume of air being pushed, which also controls the amount of lift the helicopter generates.

But even so, your "tilt left and right" and "tilt up and down" generally control the helicopter on a given plane. That is to say, a helicopter shouldn't fly downward when it tilts forward, backward, or to the side - but the lift amount might have to change and the speed will be controlled by the "opposite" side of the right triangle formed by connecting the helicopter to the ground with a straight line down (gravity), and the hypotenuse (lift). That should give your velocity vector to use.

You should be able to use quaternions to do this, but don't base your quaternion values on the tilt of the helicopter itself - try using the forces of motion the helicopter generates instead.

---
Tags: 3d, rotation
---