# Question
Title: Conversion from matrix defining rotation and position to camera matrix
I have a matrix that defines the rotation and translation of an object, relative to (0, 0, 0). Assuming that the identity matrix defines the camera to be at (0, 0, 0) pointing at (0, 0, 1), how would I go about constructing the view matrix from the world + rotation matrix?

# Answer
> 2 votes
Assuming I've understood the question correctly, you need to inverse the matrix. The inverse of the matrix is a matrix such that a multiplication between it and the matrix it is an inverse of will result in the identity matrix (i.e. 1,0,0,0 ,0,1,0,0, 0,0,1,0, 0,0,0,1). I'm not sure if you're using Opengl, D3d or whatever but your library should include functions to calculate the inverse. Bear in mind that calculating the inverse is not trivial and shouldn't be done say, once per vertex - you should calculate the inverse of the view matrix only as often as you change the view position. HTH.

---
Tags: 3d, camera, matrix
---


# Question
Title: Programming the combat sequence in a role playing game
I'm trying to write a short "game" where a player goes around and fights monsters but I have no idea how to handle the combat.

For example, say I have a "Warrior" and a "Troll". How do the two fight each other? I know I can do something like

```
Conan = Warrior.new();
CaveTroll = Troll.new();
Conan.attack(CaveTroll);
CaveTroll.attack(Conan);

```

But what part of the game controls the monster? Do I just stick the above sequence in a loop until one of them dies? Or does the game "engine" need to have a part that deals specifically with combat? Or is this an aspect of the Troll's artificial intelligence that needs to take care of it's actions?

Also, who/what determines the actions that the monster takes? Maybe a Troll can bash, kick, bite, cast spells, drink potions, use a magical item. Does the game engine determine what action the Troll takes or is that something the Troll class manages?

Sorry I can't be more specific but I need some guidance on which direction to go with this.

# Answer
> 12 votes
I imagine a battle sequence as a minigame within your game. Update ticks (or turn ticks) are directed to a component handling these events. This approach encapsulates the battle sequence logic in a separate class, leaving your main game loop free to transition between game states.

```
void gameLoop() {
    while(gameRunning) {
        if (state == EXPLORATION) {
            // Perform actions for when player is simply walking around
            // ...
        }
        else if (state == IN_BATTLE) {
            // Perform actions for when player is in battle
            currentBattle.HandleTurn()
        }
        else if (state == IN_DIALOGUE) {
            // Perform actions for when player is talking with npcs
            // ...
        }
    }

}

```

The battle sequence class would look like this:

```
class BattleSequence {
    public:
        BattleSequence(Entity player, Entity enemy);
        void HandleTurn();
        bool battleFinished();

    private:
        Entity currentlyAttacking;
        Entity currentlyReceiving;
        bool finished;
}

```

Your Troll and Warrior both inherit from a common superclass called Entity. Within HandleTurn, the attacking entity is allowed to move. This is equivalent to an AI think routine.

```
void HandleTurn() {
    // Perform turn actions
    currentlyAttacking.fight(currentlyReceiving);

    // Switch sides
    Entity temp = currentlyAttacking;
    currentlyAttacking = currentlyReceiving;
    currentlyReceiving = temp;

    // Battle end condition
    if (currentlyReceiving.isDead() || currentlyAttacking.hasFled()) {
        finished = true;
    }
}

```

The fight method decides what the entity is going to do. Note that this does not need to involve the opposing entity, like drinking a potion or running away.

**Update:** To support multiple monsters and a player party, you introducte a Group class:

```
class Group {
    public:
        void fight(Group opponents) {
            // Loop through all group members so everyone gets
            // a shot at the opponents
            for (int i = 0; i < memberCount; i++) {
                Entity attacker = members[i];
                attacker.fight(opponents);
            }
        }

        Entity get(int targetID) {
            // TODO: Bounds checking
            return members[targetID];
        }

        bool isDead() {
            bool dead = true;
            for (int i = 0; i < memberCount; i++) {
                dead = dead && members[i].isDead();
            }
            return dead;
        }

        bool hasFled() {
            bool fled = true;
            for (int i = 0; i < memberCount; i++) {
                fled = fled && members[i].hasFled();
            }
            return fled;
        }

    private:
        Entity[] members;
        int memberCount;
}

```

The Group class will replace all occurences of Entity in the class BattleSequence. Selecting and attacking will be handled by the Entity class itself, so the AI can take the whole group into account when selecting the best course of action.

```
class Entity {
    public:
        void fight(Group opponents) {
            // Algorithm for selecting an entity from the group
            // ...
            int targetID = 0; // Or just pick the first one

            Entity target = opponents.get(targetID);

            // Fighting algorithm
            target.applyDamage(10);
        }
}

```

# Answer
> 1 votes
I would have a dedicated Combat object that manages combat. It'd encapsulate the full combat state including things such as the list of player characters, list of enemies, current turn, battle terrain, and so on. Combat can then have an update method which manages the battle logic. It's not a good idea to just put the combat code in a simple loop, because it'd end really fast. Normally you'd have some timing and different battle stages.

For the actions taken, you can certainly just make it random, but it'd make little sense for a monster with full HP to cast a healing spell. It pays to have some basic logic for determining which action to take. For example, some actions could have more priority than others (e.g. troll kicks 30% of the time), as well as other conditions to make battles more interesting (e.g. when troll HP is less than 10% of full HP, there's a 20% chance of casting healing spell, otherwise the chance is 1%). This could be as complex as you like.

I think the monster class should handle selecting what action to make, the battle object asks the monster for an action and the monster makes a choice and then proceeds to apply it. One idea is to have a strategy object that you plug into monsters and which selects from the list of possible monster actions based on priorities, categories, and conditions assigned to each battle action. Then you can have a OffensiveStrategy class for example which prioritizes attacks over defensive skills, and another CautiousStrategy which is more likely to heal. A boss might be able to dynamically change strategy based on its current condition.

One last thing. You might want to either have both player characters and monsters inherit from the same class, be instances of the same class (actor or combatant for example), or share a common object that encapsulates the common functionality. This reduces code duplication and it'd also allow you to have AI-controlled NPCs on your side which can implement the same strategies you already coded for monsters.

# Answer
> 1 votes
Yes, you need to have a special part in your engine that handles combat.

I don't know how exactly you're doing your combat but I'll assume players roams aroud the game world, meet with monsters and the battle goes real time. If so then, the troll needs to know the surrounding within a certain area, maybe define how far the troll can see something in front of it (troll handles this).

About the AI, I think the engine needs to handle it itself, so that let's say you have more than one kind of enemy that can do the same thing (bite), you can just assign the AI to another monster and there you go!

# Answer
> 0 votes
Your player and your troll are nothing but sets of data, what we call the data Model which describes your world. Life, inventory, attack capabilities, their knowledge of the world even -- all consists in the data model.

Keep a single, main Model object which holds all data describing your world. It will hold general world information such as difficulty, physics parameters etc. It will also hold a list/array of specific *entities*' data as I've described above. This main model can consist of many subobjects in order to describe your world. Nowhere in your model should you have any functions that control game logic or display logic; getters are the only exception, and would be used only to allow you to get data from the model more readily (if public members don't already do the trick).

Next, create functions in one or more "controller" classes; you can write them all as helper functions in your main class, although this may get a bit large after a while. These will be called every update to act upon the entities' data for different purposes (movement, attack etc.). Keep these functions outside of an entity class is more resource-efficient, and once you know what *describes* your entity you will automatically know what functions need to act on it.

```
class Main
{

//...members variables...
var model:GameModel = new GameModel();

//...member functions...
function realTimeUpdate() //called x times per second, on a timer.
{
    for each (var entity in model.entities)
    {
        //command processing
        if (entity == player)
            decideActionsFromPlayerInput(entity);
        else //everyone else is your enemy!
            decideActionsThroughDeviousAI(entity);

        act(entity);
    }
}
//OR
function turnBasedUpdate()
{
    if (model.whoseTurn == "player")
    {
        decideActionsFromInput(model.player); //may be some movement or none at all
        act(player);
    }
    else
    {
        var enemy;
        for each (var entity in model.entities)
        {
            if (entity != model.player)
            {
                enemy = entity;
                decideActions(enemy);
                act(enemy);
            }
        }
    }
}

//AND THEN... (common to both turn-based and real-time)
function decideActionsThroughDeviousAI(enemy)
{
    if (distanceBetween(enemy, player) <= enemy.maximumAttackDistance)
        storeAttackCommand(enemy, "kidney punch", model.player);
    else
        storeMoveCommand(player, getVectorFromTo(enemy, model.player));

}

function decideActionsFromPlayerInput(player)
{
    //store commands to your player data based on keyboard input
    if (KeyManager.isKeyDown("A"))
        storeMoveCommand(player, getForwardVector(player));
    if (KeyManager.isKeyDown("space"))
        storeAttackCommand(player, "groin slam", currentlyHighlightedEnemy);
}
function storeAttackCommand(entity, attackType, target)
{
    entity.target = target;

    entity.currentAttack = attackType;
    //OR
    entity.attackQueue.add(attackType);
}
function storeMoveCommand(entity, motionVector)
{
    entity.motionVector = motionVector;
}
function act(entity)
{
    entity.position += entity.motionVector;
    attack(entity.target, entity.currentAttack);
}
}

class GameModel
{
    var entities:Array = []; //or List<Entity> or whatever!
    var player:Entity; //will often also appear in the entity list, above
    var difficultyLevel:int;
    var globalMaxAttackDamage:int;
    var whoseTurn:Boolean; //if turnbased
    //etc.

}

```

A final note is that it is also useful to keep your display logic separate from your game logic. Display logic would be, "Where do I draw this on the screen and in what colour?" vs. game logic being what I've outlined in the pseudcode above.

(Dev's note: While using classes, this loosely follows a functional programming approach which considers all methods as ideally stateless, allowing for a clean data model and processing approach that minimises bugs caused by retained state. FP is the ultimate MVC, since it achieves MVC's goal of separation of concerns explicitly. See this question.)

---
Tags: game-design, game-mechanics, game-loop
---


title: C++ OpenGL Game Timer

text:
# Question
Title: C++ OpenGL Game Timer
> **Possible Duplicate:**
> Tips for writing the main game loop?

I am attempting to make a game using OpenGL and C++ but i haven't been able to find any good tutorials..or anything that could assist me in setting up my main game loop with some kind of timer/tick system...i would prefer to use as little external libraries as possible...i am using Win32 any help would be appreciated

# Answer
This is called timer based movement. The premise is that game should run at the same speed regardless of your hardware or the current frame rate. Your program needs to ask the system its current time so that the objects will appear to move at the same speed on all computers. Started unzipping a huge file? Your character will still walk the same speed, only instead of taking 500 frames to do it he'll do it in 50, moving 10 times the distance each frame.

Be careful of pausing! You'll have to distinguish between system time and game time. I do this by subtracting out the accumulated pause time, otherwise things will appear to "jump" ahead. For example, if you had a sun/moon cycle based on the system time, where an in game day was equal to 15 real minutes, pause the game while it's day. Come back in 15 minutes, unpause it a WOW! it's magically nighttime.

In my games, I have all speeds expressed in terms of meters per second, or, if it is a 2D game, pixels per second. This is much easier to work with than using "units per frame." At the beginning of my game loop, I call the tick() function which calculates the time difference in seconds between this call to tick() and the last call to tick(). This difference is stored in a variable called df which I multiply all speeds by before adding them to object positions. If you do this then BAM! your game has timer based movement.

Windows has functions called QueryPerformanceCounter and QueryPerformanceFrequency that you can use to pull this off. Last time I checked, there *may* be some problems with df being negative if you get shuffled to another processor. Frank Luna recommends clamping df to the nonnegatives in this situation. Don't worry about external libraries, in my game engine the timer functionality is all contained in one small class.
> 1 votes

---
Tags: opengl, c++, game-loop, timer
---


# Question
Title: Position of XNA.Rectangle is changing the position a spritre is rendered to?
I'm having this weird problem where the position ocmponent of a rectangle of the XNA type is offsetting the position the sprite is rendered to as well.

I guess a broader question I'm trying to have answered is: how can I make 4 integer values: top, left, bottom, right (in texture space) the equivalent of an XNA rectangle?

# Answer
> 3 votes
There are two rectangles when drawing a texture with spritebatch (also depends on which overload you are using), the source rectangle specifies where in the texture the image is take from (you can specify this as null to use the entire texture), the destination rectangle specifies where this image will be drawn on screen.

The source rectangle is mainly used to load sprite animations that are stored in one texture.

For example this is a sprite sheet in which 3 animations are encoded.

---
Tags: xna, sprites
---


title: Font library for XNA

text:
# Question
Title: Font library for XNA
Is there a free type library kind of implementation available for XNA? I wish to use it on WP7, so it should be a managed code. I know can alternatively use spritefont, but I wish to know if other implementations exist for complex requirements.

# Answer
The nuclex library has more than one font renderer.

Developer's blog, article discussing why XNA 4 fonts don't render as well as they could with spritebatch, with before and after comparisons of Nuclex font rendering vs Spritebatch in XNA4.

Nuclex Fonts wiki.

Nuclex Vector fonts (very useful for large fonts or fonts that need to be drawn well in 3D).

XNA 4 uses DXT compression on it's font textures, which causes the edges of fonts to be a little uglier than they need to be. XNA also has no Vector font implementation, which Nuclex does.

The Nuclex font **source code** can be found here: https://devel.nuclex.org/framework/svn/graphics/fonts/
> 5 votes

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


title: Android sidecroller template

text:
# Question
Title: Android sidecroller template
I want to create a sidescroller game for Android but it seems stupid to reinvent the wheel and since there are a lot of android sidescroller games already out I though that there must be some sort of template or something so I can get started quicker, so I can keep developing from there.

# Answer
There is Replica Island by Chris Pruett. The game is open-source, and his blog takes you through the entire development as he works on the game, and solved issues that pop up. Definitely worth the read.
> 4 votes

---
Tags: 2d, java, android, side-scroller
---


title: Fanmade game copyright?

text:
# Question
Title: Fanmade game copyright?
> **Possible Duplicate:**
> Legal issues for a “fangame” of a commercial franchise?

What if I decide to make a fanmade game from a popular, recent game release?

* 100% non-profit. I will just post my game in a forum.
* Graphic work is 100% mine.
* I DO have some sounds from the original game. I have credited the developers.
* The game's title might include the original game's title, but I do have other unique words in it.

Is that possible?

# Answer
I am not a lawyer, and you should consult a real lawyer for legal advice.

However, it is *possible* to do what you ask, but (depending on where you are) it is almost certainly not *legal*. Basing your game on somebody else's game without their permission probably violates some intellectual property laws, reusing their assets (such as sounds) probably constitutes copyright infringement, et cetera -- it typically does not matter if you charge for the product or credit the authors. You need their permission, that's what matters.

IP law varies from country to country. In the US, you pretty much can't do this without permission from the IP holders and consulting a lawyer, otherwise you run the risk of getting a C&D and/or a lawsuit.
> 3 votes

---
Tags: copyright
---


title: AI algorithms for Strategy Game

text:
# Question
Title: AI algorithms for Strategy Game
I am working on building a Strategy Game (Animal Colonies fighting each other).

It is going to be simple game targeting Kids, the beta version will only support single player playing against AI opponent.

I am going to hire Algorithm programmers to build the AI algorithms of the opponent, BUT :

1. I am not sure what information I need to give for the programmers in order to build these algorithms.
2. I want to have different AI levels difficulties (easy, medium, hard), BUT if the AI opponent is too easy to defeat, the game is boring, while if it is too difficult to defeat, the game is too frustrating, and the player will quit, so I need this issue to be addressed when building AI for different levels.
3. I am not sure if the AI opponent should behave like a human player? I mean should the specification allow AI opponent to have access to all game resources ? or AI should behave like human player to use scouts to collect information about resources and enemy?

I need to identify these points. I want to write detailed specification so algorithm programmers can do the work as expected. All what I have at the mean time is Colonies design (characters/elements), maps with objects (grass, rocks, hills, tree .. etc).

So, what exactly do I need to give them in order to build opponent AI?

# Answer
As a short answer, the best thing to do is to develop the AI and use the different difficulty settings as different levels of randomness/thinking ahead. Thus, easy will very often not take the best path whereas hard will more often.

As for trying to get the difficulties right, you cannot judge human perception through code. Your only option really is to get testers to play it and comment.
> 2 votes

# Answer
Thought I'd give a vague overview of an RTS AI so you know what to expect.

There two large and seperate components: the higher-level planner, and the individual unit AI.

The job of the planner will be to win the game by building new units and issuing orders to them, like a general behind friendly lines. It may use a complex planning system like a hierarchical task network, or may take a simpler approach. This is a highly active area of research, so there's lots to read.

Whatever approach you take, you'll probably need a system to record information about the environment and enemies. This will probably be spatial. Possibilities here include blackboards, heat maps, and influence maps.

Each individual unit will have its own AI responsible for following orders from the planner. It will be responsible for picking and attacking targets, pathfinding around the environment, and even choosing when to override the planner's orders to preserve itself.

None of these issues are trivial. For any sufficently interesting RTS I'd expect a team of three or more full-time AI programmers to take more than a year to go from a blank page to a shippable competent opponent.
> 2 votes

# Answer
Lets look at Starcraft 1 AI, which is well known and understood as a source of inspiration.

For point 1 I can't help you much since I don't know enough about your game. Basically you should start your game with no computer opponents and get your developers to play the game. You can then make points about what strategies that they employ - and that you want those built into the AI.

Point 2 is the most interesting. In Starcraft, the AI has sets of build orders to execute based on what the player is doing, but also based on the difficulty. At easier levels, the AI scales back on what it builds, and doesn't retreat from losing battles. The higher the difficulty, the more aggressive the build order and the more it tries to preserve its own units from losing battles. At the "insane" difficulty level, the AI actively cheats, gaining more resources than it should.

Point 3 is just an opinion. The AI should behave like humans. It should know what units it has revealed through scouting and build units to counter.

So moral of the story, the easier the difficulty, the less the AI should "try", and the less it should read player inputs. It should mine resources and use them fairly. The AI should be bound to the rules of the human players, but the difficulty is making them "act" like one.
> 1 votes

# Answer
As a player it gets really annoying at times when the AI can see things it shouldn't be able to see. I still one game that was otherwise quite good but the AI was all-seeing and thus could do some very nasty things with artillery at times because of that.
> 1 votes

---
Tags: ai, html5, strategy
---


# Question
Title: Problems with Creating Snake's Clone on Java
I'm creating Snake's clone. My app have too classes: Snake.java and Board.java.

Right now I have three problems:

1) There are two constants - BOARDS\_WIDTH, BOARDS\_HEIGHT. They are meant to be dimensions for playground where snake moves and collects apples. It's dynamic and I can set them as I want. For example 640 x 480, 160 x 160 or whatever. Only thing I need to keep in my mind is that both numbers must divide with 16. Why? Because constant UNIT is set to 16 x 16 and, for example, when board's dimensions are set to 160 x 160, it means that there would be 10 x 10 units large playground (160 / 16 = 10). Problem: playground is always two pixels (not units) larger than it meant to be. Like if I have set dimensions to 160 x 160, actual dimensions will be 162 x 162! Here are screenshot...

If you measure this image... after pill (apple, if you like) there are two extra pixels.

2) Collisions. I think - it's because problem #1. You see, there are code lines...

```
if( x[0] < 0 || x[0] > BOARDS_WIDTH || y[0] < 0 || y[0] > BOARDS_HEIGHT ) {

    inGame = false;

}

```

They should prevent snake from going into walls. Actual result is that snake goes few units in the wall - then only the game stops... i want it to stop exactly when snake collide with the wall!

3) How to make snake start to move only when users clicks any of arrows? Right now it's like snake starts to move her body, but her head is stopped. After joints * DELAY snake's all joints are under her head! Ha, ha...

# Answer
1) You need to add setResizable() before pack() method,

2) You need to implement so to say "collision prediction" to reach desired effect,

3) You need to start timer only after any keyEvent is happened;
> 0 votes

# Answer
The reason that your getting an extra 2 pixels added on is that these pixels are added in to form the frame around your game. (Frame width is 1 pixel, add the frame on both sides and there's your extra 2)

I know this because I had a similar problem myself a while back.

**edit**

Just thought I'd add on to my answer, if you want a window with a width of say.. 160 you would just deduct 2 pixels from this value. Therefore a width specified at 158 pixels would give you your desired 160 width. If however you simply want the gameplay area to be 160 pixels wide then what you have at present is fine.
> 3 votes

---
Tags: java, collision-detection, events
---


title: book that I could make an indie game

text:
# Question
Title: book that I could make an indie game
What kind of book I read, that should do a full indie game?

# Answer
For game design I can recommend The Art of Game Design: A book of lenses.
> 1 votes

# Answer
Depends a little on what you are looking for a game.

You could do some Flash Games with little scripting but you have to learn the Flash scripting itself. If you can program C/C++/C#/Java you can find here some books which could be very interesting.

So, what is it what you can and what is it what you want to create?
> 0 votes

---
Tags: books
---


# Question
Title: Strategies for monster targeting AI in a turn-based combat system
I am making a Final Fantasy-style battle system.

I have a random generator that select the monsters move when it is their turn; different moves have different chances to be performed. I also have reactions and conditional actions for the monster to create simulated intelligence... but what I can't figure out is targeting.

I could just choose randomly between the five player characters, but I was looking for something that would make the game more challenging by adding some kind of strategy to the monsters' actions.

I code in C++.

Does anyone have an idea how to implement a system for the monster to choose who to attack besides completely random?

# Answer
My answer from this question would fit here.

To adapt for your problem: A monster would look to assign a score to each enemy. Pass the enemy to each of a collection of behaviour classes, which each return an integer score. Add all these scores together, and assign the final score to the enemy. Attack the enemy with the highest score.

This has the scope for different monsters having different behaviours, evaluating targets in different ways, and the personality extension I mentioned in the other answer could be modified at run time to alter target choice based on the monster's situation: maybe he becomes more aggressive as his health lowers?

From chaos' answer, you could keep a sticky target by remembering the score of the last target, and any new target would have to beat that score by some extra %.

Examples of the behaviours might be:

* defenseless target behaviour: returns high scores for targets that are particularly susceptible to this monster's attacks - eg a mage vulnerable to red magic in a battle with a fire demon.
* weak target behaviour: returns high scores for targets that are close to death
* decapitation behaviour: returns a high score for the player or leader of the group
* splash damage behaviour: if your game is a strategy-style rpg, that can make attacks across various team members, this behaviour could return high scores for targets that affect large numbers of bystanders, eg if a target is in the center of a tight group.

All of these behaviours are based on snapshots of the current game state, and require no long-term planning and little state on behalf of the monster.

More ideas: if your monster has multiple attacks, run this whole alg once for each attack, and pick the target/attack pair with the highest score. This was how I made enemy infantry select weapons on one big-budget FPS.
> 7 votes

# Answer
If you wanted them to act really smart, usually in RPGs the best thing for the monsters to do is all attack the PC with the highest ratio of offensive capability to hit points. You don't see this actually done a lot, though, since it tends not to be rewarding for the player. :)

One place I might recommend starting is to come up with some general categorization scheme for your PCs -- bucket them as melee, casters, healers, and stealth, or as offensive, defensive, support, or what-have-you -- and have each type of monster display a preference for the category of PC it will attack. Maybe some almost always go for that category, while some have a mild preference. This provides something useful the player can learn about the monster types and gives more interesting behavior than pure randomness.

You may also want to make monsters "sticky" in their target preference to some degree, i.e. make them tend to continue attacking whoever they last attacked.
> 5 votes

---
Tags: ai, rpg, turn-based
---


# Question
Title: Is it a good idea to develop non-trivial 2d game in python?
I am planning to develop 2D space RPG and i am facing the choice: what is the best language to write it in? My candidates are C++, Java and Python. Obviously, I want to write game in Python because of its expressiveness, speed of development and simplicity of adding scripting support. But I am worried:

* Won't Python be too slow? The game will be not trivial (like Tetris for example), it may be needed to calculate tasks for thousands of ships in universe (though their AI can be heavily simplified if those ships are not seen to the player). Of course I can write some critical parts in C, but it will instantly complicate building and deploying.
* Let's suppose that game became popular, and I became a superstar. Windows users rarely have Python at all (fortunately we have py2exe). Python on Mac OS X can be outdated and game may crash with obscure exception. Wouldn't it be hard to deploy game in Python?
* Because of lack of libraries for Python 3 I'll have to write game in Python 2. Wouldn't transition to Python 3 in couple of years be too painful and time consuming?

# Answer
> 8 votes
> Won't Python be too slow? The game will be not trivial (like Tetris for example), it may be needed to calculate tasks for thousands of ships in universe (though their AI can be heavily simplified if those ships are not seen to the player). Of course I can write some critical parts in C, but it will instantly complicate building and deploying.

It's hard to say, but most of the time the limiting factor for performance is one's ability/experience as a developer, not the language. Note that EVE uses Stackless Python (see here and here for downloads of a related presentation). I don't recall the exact details, but apparently most of their server cluster is running Python. I would thus imagine that it could handle your scalability requirements, although prototyping to be sure would be good.

> Windows users rarely have Python at all (fortunately we have py2exe). Python on Mac OS X can be outdated and game may crash with obscure exception. Wouldn't it be hard to deploy game in Python?

Most users rarely have the appropriate binary dependencies for games, regardless of what technology those games were written in (even C requires a runtime component to be distributed). Deploying via py2exe or equivalent, or simply deploying the appropriate dependency, is something of a fact of life. While it's never the easiest thing (most installer technologies are painful), it's doable and shouldn't be a reason to eschew the language -- as I said, you'll likely need to handle something similar regardless.

> Because of lack of libraries for Python 3 I'll have to write game in Python 2. Wouldn't transition to Python 3 in couple of years be too painful and time consuming?

This I don't know much about, never having really used Python 3. I don't expect Python 2.X will vanish any time soon, however, so I don't even suspect the lifetime of your game would be such that you'd *need* to transition over if you didn't want to, which makes this concern something of a non-issue.

As others have said, you're worrying too much about the language selection aspect of your project. Python is a powerful, useful tool for developing games and if you know it and like it you should develop with it. It doesn't matter how fast your game runs if it never gets finished because you worried too much about the language.

# Answer
> 14 votes
To your first point, you'll just need to build a prototype and see. Even if you told us all the details that wouldn't really change things.

As for the other two points, I kinda feel like you're putting the cart before the horse. From your question it seems like you are new to game development, in which case you really just need to pick a tool and go with it. Nitpicking over the pros and cons of mostly equally useful tools is a distraction from your real challenge: learning game development.

# Answer
> 0 votes
re #3, Python 2.x will see distributor support for at least another 5-10 years. If you use a fairly recent version (2.7, or possibly 2.6) the migration path is fairly easy if you write future-proofed code (new-style object, unicode everywhere, etc etc). The pain is mostly for things that were relying on old, broken behaviors.

---
Tags: python
---


title: Simple Terrain Rendering

text:
# Question
Title: Simple Terrain Rendering
For some reason I can not find a good example of terrain rendering, as in like "bare bones". Im reading Introduction to game Programming with DX10, and i've seen some other tutorials....but they all are complicated classes with ALOT of stuff thats unnecessary, and tbh just confuses a beginner like me. Like Raserteks tutorials are awesome, but it's SOO much code and classes, it's very difficult to understand the "3d" part when you have so many other classes.

Im just looking for the most BASIC terrain rendering (using a heightmap....or what have you).

It doesn't even have to have a camera or movement control, hell it can just be of one color. Im just trying to understand everything first. Does anyone know where I could find a sample of this? or heck if anyone would be willing to provide a simple sample of their own i'd be mega appreciative.

Dont get me wrong, the Book is great.....and I understand the functions, but the way the classes are put together...it makes it confusing of "what goes where".

edit: I've seen some Direct X 9 terrain demo's/samples....but isn't DX9 like WAYYY different from DX10 (if so thats why I wouldn't want to waste time on it). I could be wrong though.

# Answer
D3D9 is quite different from an API perspective than D3D10, but the underlying concepts are very similar. Any terrain rendering example in D3D9 (such as this one) will work fine in D3D10, you'll just have to translate the API calls which shouldn't be that difficult. Similarly, since the techniques for rendering terrain are in no way API-specific, you could even take a look at a tutorial geared for an OpenGL user, like this one.

Both of those articles illustrate very basic hieghtmap-based terrain using simple grids.
> 9 votes

---
Tags: terrain-rendering, directx10
---


title: Play game by coding your strategy

text:
# Question
Title: Play game by coding your strategy
I am building a simple strategy game, the goal of the game to teach programming basics to kids.

The concept of the game is simple, there will be a set of colony individuals - different type (resource gathering, fight, defend, scout ..etc).

I want to build a Campaign mode for this game, simple set of scenarios and missions as beta version.

As I said, the purpose is to teach programming basics, so player need to code there strategy to play the game, means that each colony individual's behavior will be programmed separately.

I am thinking of creating a basic syntax for code conditions, commands and actions (custom language), player will simply code individual's behavior by simply grouping these conditions, commands and actions in logical order. An example:

```
if FindEnemy
    if stamina > 0.6
       dobattle;
    else
       returnToNest;
    endif;
endif;

```

My question is that I am building the game using HTML5/CSS3/JS, and wondering I can implement it a client-side library to parse custom language and convert it to animation? or whether there is already built JS library or engine that can do similar requirement?

# Answer
If this is for kids, then another option is to use a GUI based alternative. Taking your example as reference:

```
if FindEnemy
    if stamina > 0.6
       dobattle;
    else
       returnToNest;
    endif;
endif

```

Rather than getting them to type out text, you can have blocks (very literally) like so:

Then you can work out what kind of mechanism you could have to insert an available block into the into the behaviour blocks. This essentially makes up a sort of script, where the users can drag over an IF block and enter a condition.

This method offers a number of advantages:

* Much easier to implement than text parsing as you don't need to worry about syntax errors (which is probably more likely to happen with first-time programmers).
* You can easily limit the scope of your work as the amount of functionality you give to the user is dependent on what blocks you make available.
* It's a much nicer experience for the user if they're starting out. Since they're scripting a game, they want to be able to see the results of their efforts as soon as possible, there's no need to memorise any APIs as all the available functionality is laid out in front of them and it's their choice.
* You can also help their debugging woes before they even compile and run by checking there aren't any illegal block combinations as soon as you can (for example, an ENDIF block when there's no opening IF)
* You more or less know what to expect from user input. For example a user typing in "IF BLAH YES THIS SOMETHING!! WOOP1!!1!" would probably result in invalid syntax, but let's say an IF block had a combo box in it to select all possible attributes that have conditions (like stamina) then you know the input they provide is legal.

I understand that this doesn't completely answer your question regarding text parsing, but I thought I'd suggest another method of doing so that might be a lot easier than a lot of syntax headaches for both the end user and yourself.

Hope that helps!
> 13 votes

---
Tags: html5
---


title: Curved movement between two points

text:
# Question
Title: Curved movement between two points
What is a good technique to enable an object to move between to points in a nice curved motion?

The end position could also be in motion, such as the trajectory of a homing missile.

# Answer
> 11 votes
Assuming you want this to be a frame-by-frame thing (where the target could even be moving), and not a precomputed trajectory, this is actually incredibly simple:

Every frame, compare the velocity-vector of the missile to the vector **(positiontarget \- positionmissile)**; that is, the vector pointing from the missile to the target. Every frame, if the two vectors do not have the same direction, then rotate the veloity-vector a little bit towards the other vector, so every frame the missle gets a little bit closer to looking at its target.

You can determine whether to rotate clockwise or counter-clockwise by looking at the sign of the cross-product between the two vectors.

---

**\[Edit\]** XNA-ish code (I don't have XNA to test this):

```
//Once a frame:

//Get vector spanning from missile to target
Vector2 vectorToTarget = target.Position - missile.Position;

//Convert to Vector3 to do cross-product
Vector3 vectorToTarget3 = new Vector3(vectorToTarget, 0);
Vector3 missileVelocity3 = new Vector3(missile.Velocity, 0);

//Rotate clockwise/counter-clockwise is determined by sign of cross-product
int crossProductSign = Vector3.Cross(missileVelocity3, vectorToTarget3).Z;

//Positive cross-product means rotate counter-clockwise, negative is clockwise
double rotationAngle = 0;
if(crossProductSign > 0)
    rotationAngle = -0.05;
else if(crossProductSign < 0)
    rotationAngle = 0.05;

//I'm not sure how to do rotation in XNA, but the internets tell me it's something like this:
missile.velocity = Vector2.Transform(missile.velocity, Matrix.CreateRotationZ(rotationAngle))

```

Note that, because `rotationAngle` has only three possible values, all possible values of `Matrix.CreateRotationZ(rotationAngle)` can be cached so you don't have to call it every frame.

# Answer
> 15 votes
There are two possible techniques:

**The first technique is to do a *frame-based* simulation. This is good if you are doing something like a homing missile in gameplay, that does not have to hit your target exactly.**

In this case you want to track the object's position and velocity. Each frame look at the direction to the target and the current movement direction, and adjust the velocity appropriately.

If you snap the velocity instantly, your missile will always hit the target. But if you adjust the velocity by a small amount each frame, your missile will curve towards the target - and if it curves slowly enough, the target could dodge it.

**The second technique is to use a *parametric* method. This is useful for animating things where you want to hit your target precisely and predictably.** In this case you usually take "time" as your parameter and put it into a function of some kind.

A particularly useful set of functions are the Equations of Motion you learned in highschool physics. By applying these to both axis you can get ballistic trajectories. With a little bit of maths, you can determine the initial parameters to hit a target - even a moving one, if it moves predictably.

XNA also provides a number of interpolation and curved motion functions. Take a look at the documentation for `Vector2` and for `MathHelper`. These provide some interpolation functions which you can use and even combine to do interesting things. For example, firing a missile: `Lerp` (linear interpolate) your missile's position from its start point to a target position, and also lerp that target position from some initial target to the target object's real (changing) position. This will give you a nice "locking on" effect.

(There are also some functions for producing curves, for example: `CatmulRom`, `Hermite`. These are probably harder to use successfully with a moving target, though.)

If you look into "easing" (in the context of animation), you can get some more interesting interpolation functions that can give you interesting effects like acceleration.

Now - you may say that this technique gives some odd results as your target moves around. However in practice, as long as your projectile is moving faster than your target, it usually looks fine. If it is a problem, you should probably be using a frame-based technique anyway.

# Answer
> 3 votes
You may want to look up sine waves or possibly Bezier Curves. I don't know whether the sine wave approach is normal, but I can't see why it would be that poor.

# Answer
> 1 votes
You can take a look at Steering Behaviors, as defined by Craig Reynolds: http://red3d.com/cwr/steer/

This is often used in AI to have NPCs move toward their target.

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


# Question
Title: What platform should I use for a master server?
We are making a small FPS, and want people to be able to play it online and fetch a list of all servers from a master server. We only have experience in C#, and we have already written a master server that tracks all the servers.

However we realize that we'd have to host it on a windows application server. These are expensive, and making our master server completely reliable and watertight may be a lot of work. Also it seems a waste to have a server out there running windows and our tiny application that only tracks a list of servers...

Should we make the effort to learn PHP and SQL and make our master server that way? Does anyone know of any master servers written in PHP to get us started?

# Answer
> 6 votes
I would write the server in the language/toolchain you know best, rather than learn a new one for that purpose, especially if you have any concerns about making the server "watertight." You're more likely to make mistakes with technology you are unfamiliar with. Unless the cost is prohibitively more to run a Windows server, I would stick with that platform.

However, you may also be able to find hosting providers that will run \*nix servers with mono available, so you can run your master server that way.

# Answer
> 3 votes
You might find this article to be of particular value.

Long story short, you can get an Amazon server set up running \*nix and Mono, and so have a cheap C# server to do your server stuff.

If you are just doing a master server list, this shouldn't be too hard--hell, even just a servers.txt that gets polled might do it for you.

---
Tags: c#, multiplayer, server, php
---


title: Java multiplayer cards game

text:
# Question
Title: Java multiplayer cards game
I need to develop a simple multiplayer card game. For example, a poker game; this is only for study. I am going to develop it in Java.

How I can I manage communication between the server and clients? Can I use sockets for this game?

Edit: Thanks, I know socket programming. I know the programming socket. I just wanted to know if it was the correct technique for a multiplayer game like online poker.

# Answer
> 1 votes
Yep, sockets would work just fine. There's a great tutorial using Java, that not only shows you how to use the sockets, but also teaches you about the underlying fundamentals. The tutorial can be found here:

http://www.gamasutra.com/view/feature/3218/java\_network\_game\_programming.php

Make sure you look at all 3 of the tutorial.

And the entire source code for the tutorial is found here:

http://www.gamasutra.com/features/19970812/netcon4.zip

---
Tags: java, networking, card-game
---


title: Loop writing value error

text:
# Question
Title: Loop writing value error
I'm currently re working an editor got from a tutorial, but I'm having a problem.

I'm making a call to an associative class for the form, which is supposed to get the original tile value and the set a new value, e.g

9(the original tile value) 9#5(the new tile value, based off the previous value)

The trouble I'm having instead of creating the new value it creates this instead 9#5#5#5#5#5#5#5

here is how I'm currently calling the functions

```
tileNumber = currentCollisionLayer.GetCellIndex(collideCellX, collideCellY);
string TileName = tileNumber + "#" + numForm.actualNumber.Text;
currentCollisionLayer.SetCellIndex(collideCellX, collideCellY, TileName);

```

when I call either of the other functions alone it works fine, its only when I try and use them in combination there is an issue

The class I calling these functions are below, any help with this would be greatly appreciated.

```
public class CollisionLayer
    {

        List<Texture2D> collisionTextures = new List<Texture2D>();
        string[,] map;

        public int Width
        {
            get { return map.GetLength(1); }
        }

        public int Height
        {
            get { return map.GetLength(0); }
        }

        public CollisionLayer(int width, int height)
        {
            map = new string[height, width];

            for (int x = 0; x < width; x++)
                for (int y = 0; y < height; y++)
                    map[y, x] = "0";
        }

        #if !XBOX
        public void Save(string filename)
        {
            XmlDocument doc = new XmlDocument();

            XmlElement rootElement = doc.CreateElement("CollisionLayer");
            doc.AppendChild(rootElement);

            XmlElement layoutElement = doc.CreateElement("Layout");

            string line = string.Empty;

            for (int y = 0; y < Height; y++)
            {
                string formatString = string.Empty;

                for (int x = 0; x < Width; x++)
                {
                    formatString += map[y, x].ToString() + " ";
                }
                if (y == 0)
                    line += System.Environment.NewLine + formatString + '\r' + '\n';
                else
                    line += formatString + '\r' + '\n';
            }

            layoutElement.InnerText = line;

            XmlAttribute widthAttribute = doc.CreateAttribute("Width");
            XmlAttribute heightAttribute = doc.CreateAttribute("Height");

            widthAttribute.Value = Width.ToString();
            heightAttribute.Value = Height.ToString();

            layoutElement.Attributes.Append(widthAttribute);
            layoutElement.Attributes.Append(heightAttribute);

            rootElement.AppendChild(layoutElement);

            doc.Save(filename);
        }

        #endif

        #if !XBOX

        public static CollisionLayer FromFile(string filename)
        {
            CollisionLayer tileLayer;
            List<List<int>> tempLayout = new List<List<int>>();

            XmlDocument input = new XmlDocument();

            input.Load(filename);

            int width = 0;
            int height = 0;

            tileLayer = new CollisionLayer(width, height);

            foreach (XmlNode node in input.DocumentElement.ChildNodes)
            {
                if (node.Name == "Layout")
                {
                    width = int.Parse(node.Attributes["Width"].Value);
                    height = int.Parse(node.Attributes["Height"].Value);

                    tileLayer = new CollisionLayer(width, height);

                    string layout = node.InnerText;

                    string[] lines = layout.Split('\r', '\n');

                    int row = 0;

                    foreach (string line in lines)
                    {
                        string realLine = line.Trim();

                        if (string.IsNullOrEmpty(line))
                            continue;

                        string[] cells = realLine.Split(' ');

                        for (int x = 0; x < width; x++)
                        {
                            string cellIndex = cells[x];
                            tileLayer.SetCellIndex(x, row, cellIndex);
                        }

                        row++;
                    }
                }
            }

            return tileLayer;
        }

        #endif

        public void SetCellIndex(int x, int y, string cellIndex)
        {
            map[y, x] = cellIndex;
        }

        public void SetCellIndex(Point point, string cellIndex)
        {
            map[point.Y, point.X] = cellIndex;
        }

        public string GetCellIndex(int x, int y)
        {
            return map[y, x];
        }

        public string GetCellIndex(Point point)
        {
            return map[point.Y, point.X];
        }

        //public void RemoveIndex(string existingIndex)
        //{
        //    for (int x = 0; x < Width; x++)
        //    {
        //        for (int y = 0; y < Height; y++)
        //        {
        //            if (map[y, x] == existingIndex)
        //                map[y, x] = "0";
        //            else if (map[y, x] > existingIndex)
        //                map[y, x]--;
        //        }
        //    }
        //}

        public void ReplaceIndex(string existingIndex, string newIndex)
        {
            for (int x = 0; x < Width; x++)
                for (int y = 0; y < Height; y++)
                    if (map[y, x] == existingIndex)
                        map[y, x] = newIndex;
        }
    }
}

```

# Answer
> 2 votes
I'd recommend either using the debugger (to set a breakpoint on the 'set' function) or add some debug output (in the 'set' function and a few other places), to see what's going on. To get '9#5#5#5#5#5#5#5' the three lines of code you have to modify the existing value (and add on '#' plus the new value) must be getting called 7 times.

The debugger should be the easiest method of finding out what's going on.

# Answer
> 1 votes
Since it looks like the only place you're adding a `#` to your string is in the lines you say you're using to call the functions in your class, I'd say the issue isn't in your class functions.

`string TileName = tileNumber + "#" + numForm.actualNumber.Text;`

The line above is getting called more than you want it to. The previous answer is excellent, use your debugger and place a break point on the line I mentioned above. I imagine you'll find that it's your problem. This site should give you basic debugging skills if you're not sure how to use the Visual Studio debugger.

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


# Question
Title: Line-Rectangle Collision Detection and Response
I've looked through Google and none of the solutions seem to pinpoint my idea. Ultimately, I want to create a level editor where I can draw lines and have them exported to a file for my engine to read. I'm having trouble getting path-rectangle to work. I'm using this in the context of a platformer, so I'm also interested in knowing which direction and distance the collision came from so I can resolve it. Which is the best algorithm for doing this? I'm only concerned about axis aligned rectangles.

EDIT: My character is represented as a rectangle and the level is represented by lines. The tools really do not matter as I'm looking for the mathematics behind it, not necessarily an implementation.

# Answer
> 3 votes
Well, a simple way to test the intersection of a line segment against a rectangle is to do a line segment test against each line segment that the rectangle is made of.

However for axis aligned boxes we can do things more efficiently.

Here is the easiest to understand code that I could find:

http://www.garagegames.com/community/blogs/view/309

There are slightly more efficient ways, but that should suit you fine.

There are dozens of implementations of this all over the internet. Search for "line AABB intersection".

However, you say that your box is an axis aligned box (AABB), so does this mean that your lines are also axis aligned?

In that case, all you really need to test is whether each of the Y values of the four points of the AABB are above or below the Y value defined by your line, and whether each of those point's X values are within the X values defined by the segment ends of the line.

As I said in the comment on your question, explain to us what you're trying to do, because as it stands your question doesn't make very much sense.

If you're trying to make a game where you have lines that are not axis aligned, but the player *is* axis aligned, i.e., you have a box player that has only one corner of the box touching the lines, then my advice is to not make that game.

If you want to make a game where the box is lined up with the line, then my answer needs to change because then you want to know about OBB vs line intersection instead.

If you want to make a game where the lines of the level are axis aligned, then you don't need to test the player box against the level lines, you only need to test the box points agains the level line segments.

---

For axis aligned level lines vs AABB player:

Each line segment of your level is made up of a Y value (the height of the line on the screen) and two X values (the left and right extents of the line). A line is a struct/class that stores X1, X2, Y.

Your AABB player is represented by two points, bottom left and top right (call them bottom\_left and top\_right).

C# code:

```
bool test_line_intersection(Line line, Vector2 bottom_left,
        Vector2 top_right, out float intersect_amount){
    intersect_amount = 0;

    if(top_right.X < line.X1){
        // player is not intersecting line.
        return false;
    }

    if(bottom_left.X > line.X2){
        // player is not intersecting line.
        return false;
    }

    if(bottom_left.Y < line.Y && top_right.Y > line.Y){
        // bottom of player is below line 0, and player is intersecting line
        intersect_amount = line.Y - bottom_left.Y;
        return true;
    }

    // player is not intersecting line.
    return false;
}

```

If this function returns true then there is an intersection. In that case, add intersect\_amount to the player position, and the player will no longer be intersecting with the line.

---
Tags: collision-detection
---


# Question
Title: JBox2D becomes very slow on mobile phones after 80-90 dynamic and static bodies
I have a simple game with 20-30 physics bodies (static, and dynamic)

If I add some additional Dynamic bodies and joints (over 80-90 item), then JBox2D will become very laggy, and a little slow.

Am I doing something wrong, or is this the limit of JBox2D? If I change to Box2D JNI via java native calls, will it be faster?

# Answer
Response for Android devices. Jbox2D is so bad... Since NDK is available, i use it with native Box2D. January 2010, there was a 3X factor without garbage collector lags. There is many NDK ports as in libGDX

note: With 2.3 devices, the new GC fixes lags...
> 1 votes

---
Tags: box2d
---


title: Fade from one Color to another

text:
# Question
Title: Fade from one Color to another
How would one go about gradually fading a sprite from one color to another?

# Answer
Use `Color.Lerp` to interpolate between two colours. See the MSDN documentation. Pass this as the color to `SpriteBatch.Draw`.

The arguments to `Color.Lerp` are the two colours you want to fade between, and a fade amount between 0 and 1.
> 7 votes

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


# Question
Title: Modelling the board in a Mastermind game
Hey, I'm trying to make a Mastermind game. I'm having trouble figuring how to design the game board for the guesses. The board must consist of four columns and eight rows. I'm having trouble figuring out how to go about printing the game board on screen. I know I could use a two dimensional array to store the letters and guesses, but I need to print the game board on the screen as well as the guesses inside the game board.

I hope this was clear enough, if not i can explain more, I just need help with this game board situation.

# Answer
Essentially a your board is a 32-element array (eight rows, four slots per row). You don't strictly speaking need to use a 2D array to represent this, as you can use a 1D array just fine with a bit of indexing math (it's useful to understand how to do so, because in some cases it can be a huge benefit; in this case it's likely to be a "six of one, half-dozen of the other" type of trade off though).

Each slot in the board can be empty, or a color. You could thus represent the value of a slot with the following enumeration:

```
enum SlotState {
  SS_EMPTY,
  SS_RED,
  SS_GREEN,
  SS_BLUE,
  // ...however many colors there are...
};

```

and represent the board itself with a simple class with the following minimal interface:

```
class Board {
  public:
    static const int COLUMNS = 4;
    static const int ROWS = 8;

    Board() {
      std::fill_n(slots, ROWS * COLUMNS, SS_EMPTY);
    }

    SlotState getSlot(int row, int column) const {
      return slots[row * COLUMNS + column];
    }

    void setSlot(int row, int column, SlotState state) {
      slots[row * COLUMNS + column] = state;
    }

  private:
    SlotState[ROWS * COLUMNS] slots;
};

```

Then, given any board, you can print it by simply iterating through the rows/columns of the board, asking the board for the value of the slot at that position, and rendering it. For example, to do so using the standard C++ console output object might look something like:

```
void printBoard(const Board& board) {
  for(int row = 0; row < Board::ROWS; ++row) {
    for(int column = 0; column < Board::COLUMNS; ++column) {
      switch( board.getSlot( row, column ) ) {
        case SS_RED:
          std::cout << 'R';
          break;

        case SS_GREEN:
          std::cout << 'G';
          break;

        // ..et cetera...

        default:
          std::cout << ' ';
      }
    }

    std::cout << "\n";
  }
}

```

You could just as easily be telling your graphics API to enqueue sprites or colored triangles/quads at that point, though, instead of printing characters.

The reason I suggest this approach is that, as you can see, the board itself ends up only knowing about the board's logical state... the size of the board and the value of every slot in the board. It also provides a relatively minimal (but functional) interface to manipulating the board. It has a single responsibility -- to represent the board. There's nothing in there about rules for what colors must go where (although a real-world class should perform some bounds checking that I have eschewed here for brevity). And there's nothing in there for rendering the board -- that is accomplished entirely by an external, non-member function and can be done entirely via the public interface of the board object.

This keeps the class lightweight and reusable and helps to increase it's maintainability as well -- it's a good habit to get in to trying to approach designs like this (and also to, in general, keep logical interfaces and rendering interfaces distinct).
> 3 votes

# Answer
You may want to be more specific. Do you not know how to draw anything to the screen?

If so, there are a lot of ways to do it. Based on the tag, I assume you're using C++. You could write text in a console window, you could use GDI or GDI+ to draw graphics, or you could use DirectX or OpenGL.

I suggest taking a smaller step first. You can forget the game for a moment and just try to draw something to a screen, like a circle. Then, for instance, you can use loops to draw more circles and organize it so it does what you want for the game.

Hope this helps a bit.
> 0 votes

---
Tags: c++
---


title: Water/Ocean simulation and physics

text:
# Question
Title: Water/Ocean simulation and physics
I'm looking for some references about water simulation, and how to model it's interaction with bodies (like boats, ships, submarines).

I've found a lot of references on the visual aspects of water (waves, reflection, etc), but very little about how to deal with the way it should interact with bodies. My experience with game development is very limited, and I'm really stuck here.

Bascally I would like to be able to make the position of a ship variates according to the waves. How can I do this?

I'm using Panda3D, but hope to hear about techniques and implementations used in any available technology.

# Answer
> 81 votes
Basically you're looking at modeling 6 things for a ship: pitch, yaw, roll, heave, sway and surge.

Pitch, yaw and roll are rotations the ship can make as it twists and turns going up and down the slope of the waves. Heave, sway and surge are movements induced by the waves pushing the ship around and/or the ship sliding down the face of a wave.

**"Like a Car Driving on Hills..."**

Imagine a boat on the water like a car driving over hilly ground. If the car drives over rolling hills (like a ship going over waves) it is going to tilt and angle as it goes up and down the hills. This is the pitch, yaw and roll. If the hills (waves) are big, the car (ship) will drive up and down, pitching, yawing and rolling as it goes. If the hills (waves) are really small (smaller than the car/ship), then the car (ship) is just going to drive over them and not pitch, yaw or roll much.

A big ship can just plow through smaller waves, whereas a small ship will move up and down the waves. Taking our car example, imagine someone riding a bicycle (small ship) over a set of small hills (waves). They will roll up and down as they go. Then someone drives a big truck (ship) over them. The truck is bigger than the hills, so doesn't really pitch up and down as it goes over them.

Unlike the car though, a ship is part way into the water, so it's movements are going to be dampened somewhat. Imagine a car with really soft spongey tires. When it drives over tiny hills, the spongey tires just smooth it out. A ship's movements are also dampened, so little waves won't make it bounce up and down like a car on a rocky road. A submarine is sort of the ultimate dampened ship, as when submerged it is pretty much immune to the surface waves. But if it's on the surface it's going to be moved by the waves.

A ship will also slide on waves. A ship going down the face of a wave will surge forward for example. So to extend our car example, make it a car with big spongey wheels driving on a somewhat slippery surface. Unless the car is running the engine to compensate for the slip, it's going to slide down the side of a hill. Even if it is running the engine, there is going to be some slip.

The one place where the car and hill analogy has problems is the fact that the waves change shape over time. A stationary ship will bob up and down as the waves go up and down.

**Waves Moving the Ship**

If there is no wind blowing on the ship to move it along, and the waves are a perfect sine wave shape, then the ship basically won't move anywhere as it bobs in the waves. It slides one way as it goes up the face of a wave, then slides back the other way as it goes down the back face of a wave.

However if the waves are NOT symetrical (like the picture below), then the waves are going to move the ship. Because one side of the wave is steep, the ship is going to slide quickly down that face as well as be pushed by the face of the wave. The gentle back slope of the wave however won't have much motion.

This isn't the most perfect model of wave motion and shape affecting a ship's motion, but it will probably do for a rough simulation.

**Wind Effects**

Wind is also going to push your ship around in ways independent of the wave motion or ship motion. The direction and force of the wind can be different than the direction and force of the waves.

**Buoyancy**

Buoyancy is how well your ship floats. Very buoyant ships float up high in the water, and ones that aren't buoyant sink. Neutrally buoyant ships (submarines) can basically "hover" at any point underwater, neither sinking nor rising. If you want to simulate a ship sinking, make it become negatively buoyant and it will begin to sink.

Buoyancy also affects dampening of the ship's motion. A ship that is extremely buoyant will bob around on the water surface and be strongly affected by waves. A ship that is less buoyant will be partially submerged and not be affected as much. Think of the difference between a pingpong ball floating on the surface versus an apple, which floats but is partially underwater. The pingpong ball bobs up and down with every wave motion. The apple on the other hand doesn't respond to every wave detail.

**Capsizing**

If the pitch, yaw and/or roll exceed some value, your ship is going to tip over. When it tips over, it might fill with water, reducing the buoyancy, thus making it not float any more.

**Getting Sea Sick :o~**

A ship that is traveling parallel to the direction of wave motion is "in the trough", and will produce the most nauseating effects at least in my experience :) If you are traveling in the direction the waves are going, you can have a very smooth ride - like having the wind at your back. If you are traveling in the opposite direction as the waves, you will have a pretty harsh ride as you are hitting each wave "hill" as it comes at you. Makes for a pretty exciting ride though!

**Further Reading**

Here are three articles that cover the science behind this, which might give you some insights. Though heavy on the math and science, they could give you an idea of what the different factors are.

Article 1: Modeling of Ship Roll Dynamics and Its Coupling with Heave and Pitch

Article 2: Modelling and Simulation of Marine Surface Vessel Dynamics

Article 3: Modelling and Simulation of Marine Surface Vessel Dynamics

**The Author Doing Field Research**

Here's me about ~~15~~ ~~20~~ ~~21~~ 24 years ago when I worked on research ships :)

# Answer
> 5 votes
Do you have a water simulation?

My suggestions are

* fake it with springs. Each vertex on the water surface is coupled together into a spring mesh. Pull one down and they all start oscillating. You could constrain x,z motion and only allow y (or up/down motion)
* fake it by summing sinewaves of different amplitudes and frequencies. Some thing like this:

```
rez = 32;
for(i=-rez; i<rez; i++)
   for(j=-rez; j<rez; j++)
   {
      yofs = 0;
      yofs += 1.0 * sin( t + j*0.5 + i*0.125);
      yofs += 2.0 * sin( t + (rez-j)*0.125 + i*0.25 );
      yofs += 2.0 * sin( t + (j)*0.125 + (rez-i)*0.125 );
      yofs += 0.5 * sin( t + (rez+j)*0.125 + (rez+i)*0.125 );
      glVertex(i/rez, yofs, j/rez);
   }

```
* simulate the 2D wave equation, this can be very fast on the GPU. See this page for a java applet and some pseudo code. Also check this version, the same but even simpler. A processing sketch with code.

From the wave equation sim you can get the direction (dx,dz) of the wave is traveling in

```
dx = h[x-1][z] - h[x+1][z]
dz = h[x][z-1]- h[x][x+1]

```

where h a 2D array with the height of the wave at \[x\]\[z\]

You could add this to the boats position to make it travel with the wave... I've tried, but the movement becomes jerky, so I smoothed it out with a simple 3x3 box filter (smoothing the differences/velocities dx dz)

---
Tags: physics
---


# Question
Title: Controls for physics-enabled game object
I'm trying to put together 2D game on Flash ActionScript. Game objects positions are updated by physics library and I'm trying to control them applying forces and updating these forces every frame.

Right now I'm pondering how to control a helicopter. I'm using concept of throttle and target height. To make heli float on constant height, I'm applying force of

F0 = -m * gy

which negates gravity for it. To make it move up or down, target height is used - it is increased with up key and decreased with down key, then the heli should ascend or descend to it. The problem is **transitional** process - right now the heli misses target height and then oscillates around it.

In short: how to control body with forces to make it move from point A to point B and stop there? Here's how I'm controlling it now:

```
    public function update(time:int):void
    {
        lastUpdate = time;
        var deltaY:Number = targetHeight - body.graphic.y;
        throttleMark.y = targetHeight;
        //force for stable floating
        var antigrav:Number = -body.gmass * body.space.gravityy;
        //made-up damping factor
        //   (in fact, too small, but higher scale make heli move very slowly)
        var damping:Number = -body.vy * body.vy * body.vy * 0.5;
        var attraction:Number = deltaY * 1000.0;
        var totalForce:Number = antigrav + attraction + damping;
        body.applyRelativeForce(_strafe, totalForce, 0.0, 0.0);
    }

```

# Answer
> 5 votes
You could consider running a simple PID controller in your game. It's simple to implement in a function like the one you have already.

By tweaking the parameters (or computing them, there are many techniques) you should be able to get a pretty neat behaviour.

Be sure to run your physics loop with a fixed time step though, as this is necessary to achieve stable regulation when implemented with discrete/digital logic (as oppossed to analog circuits....)

However, some non-linear daming that Lunin suggests might be an option. That would allow the chopper to "soft-snap" to the target height. It depends on how "physics-y" you want your game to behave. :)

# Answer
> 2 votes
Consider increasing your dampening as you get closer to the target height or making a boolean switch for a fixed increase once you've reached the target and until another height is set. That would allow you to have faster movement without sacrificing your ability to stop or requiring much change in code.

---
Tags: physics, actionscript
---


# Question
Title: What's the best way of drawing a glowing 3d line using LWJGL?
Sort of like a strip-light effect; not actually a light source, but just a polygon with glowing edges.

Can this be done easily? Right now I'm contemplating drawing a line more than once with varying alpha/width values to achieve this, but I think that'll cause weird glowing points at the vertices, which is far from ideal.

# Answer
> 2 votes
The basic idea is to extrude the line into a polygon, but do it like you'd billboard a point sprite (but for a line segment).

---
Tags: opengl, java, lwjgl
---


title: Polling vs event driven input

text:
# Question
Title: Polling vs event driven input
I'm developing a game using polling for the input method. However, now that I'm delving deeper into the game menus and other UI components, I'm finding that I'd probably like to have event driven input. Perhaps even having both, using event driven for the UI and polling for the "world" input. I'm curious on what the best way to go is.

I'm defining polling as: each update loop I check what keys are press, where the mouse is, buttons pressed, then run through them and do actions based on the info collected.

I'm defining event driven as: interrupt based events, when an event happens and interrupt is triggered and a code block is run based on the event.

Do you think it's best to go all event driven, all polling, or is a combination of both acceptable? If you have pros and cons for either please list them. Thanks.

**EDIT**

The game is Java/OpenGL based, so will be released to Windows/Mac/Linux. The possibility of extending that to mobile devices is low. The game is RTS style, 3rd person 3D.

**EDIT 2**

I'm still not totally happy with the way I've implemented this, but what I'm moving toward is catching events in my UI and if they're not handled by any of my UI components, I pass the event on to the "World" for picking/selection. Something like:

```
@Override
private boolean handleEvent(Event event) {
    if(hud.handleEvent(event)) {
        return true;
    }
    return WORLD.handleEvent(event);
}

```

This way I don't get clicks leaking through the UI to select objects behind buttons and what not.

Currently my camera controls are still based on polling, and that seems to be working for now, but I may update that later on.

I appreciate all the answers, sorry I could only pick one!

# Answer
It depends on the requirements of your game and hardware. Most games are usually interested in changes to input state, i.e. user presses the fire key and their weapon starts firing, user releases the fire key and their weapon stops firing, user presses the move key and starts moving, releases the move key and stops moving, etc., so an event-driven input system makes the most sense in those cases since the information is already in a suitable format. Plus on the Windows platform, you already receive events for changes to keyboard and mouse state, so it's often a 1:1 conversion from low-level input events to high-level game events. With polling, you'll often find yourself having to generate such events manually by comparing state between the current and last frame. Basically, "which buttons are pressed now?" tends to be far less useful information than "which buttons have been pressed/released this frame?", and given an initial keyboard/mouse state when you initialize your input subsystem, the former can be inferred from the latter anyway for those cases when you need it.

That being said, on certain platforms you're stuck with polling input at a low-level and there's no way around doing the edge checking yourself. However, I've always achieved the best results using events for all high-level logic since that's naturally how those systems tend to operate.
> 19 votes

# Answer
I see no reason that you cannot do both, and get the best of both worlds.

Input Events are generated by polling (at some level the driver polls the hardware to see what state its in), and since your main loop polls all input devices, you can easily implement your own. Something simple like below is what I've used in the past.

```
mouseInput = GetMouse();
kbInput = GetKeyboard();

// refactor this out to its own method if it makes sense
if menuState == Showing
    if mouseInput.LeftButton == State.Pressed
        LeftButton(mouseInput.X, mouseInput.Y)

// rest of game input code processing

void LeftButton(int x, int y)
{
    // left button event handler
}

```

I know that you defined events to be interrupts and what I've put here is not "truely event based", but I don't see what the above doesn't give you that interrupts do give you -- most users will not notice the single frame lost, unless your game runs at very low frame rate.
> 9 votes

# Answer
There are two different issues here:

1. How do you read user input from the OS/hardware?
2. How do you process user input in your engine?

For reading, it clearly depends on your platform, and what kind of input you want to read. Note that it's easy to convert one thing to another in your input layer. (I.e. poll and emit events to the engine, or listen to events and emit state to the engine.)

For processing, there are a few different options:

* For player movement control (and similar schemes), polling might be simpler as you need to recompute speed each frame. It's very likely that your inner loop will be polling based:

i.e. something like `speed += 1 if button.down else -1; clamp(speed, 0, 42);`
* For discrete events (fire missile, pause game, teleport to other side of planet), event processing is preferrable, otherwise your code will be littered with `maybeLaunchMissile(key_state);` calls, and that's just ... bad, m'kay. ;)

Hope it helps.
> 7 votes

---
Tags: java, input, events, polling
---


title: Perspective in early pseudo-3d games

text:
# Question
Title: Perspective in early pseudo-3d games
Please take a look at the screenshot below, from the old classic Space Harrier. My question regards the curved perspective on the chequerboard 'ground'. It's got a strangely curved geometry (I remember seeing this in a few old games/demos). I reminds me somewhat of a moire effect, and I think some of it (in the background) is just that - but I don't think its the full story. Compare with the screen shot from the Sega version, which shows moire effects in the distance, but not the same curvature.

So...

* **Why the curvature?**
* **Did they do this on purpose, or is it a side effect of some technique?**
* **How is it achieved?**

# Answer
This has to do with Mip Mapping textures. This texture has not been mip mapped. See the before and after mip mapping on this image:

http://warsztat.gd/files/articles/texatlas/mip-map2.png

So it's a side effect of the game trying to draw textures far away at an angle. Mip mapping fixes this, so the way to achieve it is to not use mip mapping.
> 6 votes

# Answer
I think it's more correct to say that the effect you're seeing is called Aliasing. Specifically a Moiré pattern.

Basically for speed there was a naive method of picking which pixel from a texture to draw at a given pixel on screen given the camera you're rendering from, and the curvature you see is a side effect of the grid pattern.

So no, it wasn't intentional.

Mipmapping helps fix this issue as well as improves speed of rendering (as picking adjacent pixels from a lower res texture is faster due to cache coherency than picking far apart pixels on a larger texture). But, as you can see from mipmap examples, it doesn't make the texture look "right". For that you need anisotropic filtering.
> 6 votes

---
Tags: 3d, geometry
---


title: Tile map using in game development

text:
# Question
Title: Tile map using in game development
I am a new Android game developer and I have only a limited knowledge about game development and all. I'd like to create a game just like Farmville and I heard that tile map is the method used to code this game but I dont have support from others so I request you all to help me if you can. Please tell me how I could create such a game using eclipse and android SDK and let me know if there is any game engine that can be a support to my game and how to use it too. I looked at cocos2d android but its very complicated for a starter point of view.

# Answer
> 2 votes
Tile maps are quite simple. View them as a 2D array of properties:

* Sprite to display
* World position (you can simply use your X,Y position in your 2D array and multiply it by your sprite width and height)
* Blocks movement or not (never played Farmville, so not sure if this is necessary)
* Pathfinding cost to traverse if you want to support NPCs
* Actors (either characters, items, etc...) standing on the tile

A basic approach to render them is calculate what fits the view of the camera, if it's a top down view this is trivial, if you're going for a 3/4 view, you will have some maths to compute which tiles to render. If you're not going for top down, render from back to front including actors standing on the tiles, so that they gradually fill the screen and overlap objects that are further away.

As a "starter", I would start simple, learn how to render sprites on the target hardware and move from there.

# Answer
> 1 votes
This question is very broad. It would be better if you asked something like "are there any support libraries for tile based games using cocos2d android".

With that question in mind, it *seems* that cocos2d supports the TMX map format. The Tiled Map Editor can export to that format. There seems to be a tutorial on how to get started here (I just did google search). I realize that it specifically is referring to the iPhone version of cocos2d but I imagine it wouldn't be too hard to adapt over.

---
Tags: tiles
---


# Question
Title: Does changing a Rasterizer State affect every object (model) on the screen?
Quick easy question. When setting a Rasterizer State (like for example wireframe).....does that affect every object (model) on the screen?

For example, let's pretend I have 2 cubes. I use:

```
devcon->RSSetState(pRSWireframe);

```

Will that affect all the objects on the screen?

# Answer
It will only affect objects rendered after the state is changed.
> 5 votes

---
Tags: directx11
---


# Question
Title: Having a slight problem moving my camera based on time passed using GLUT/OpenGL
Before anyone asks, this is for a university project and **I have to use GLUT**. I'm not tagging this as homework because this is not a requirement, nor will I have extra points for this.

With GLUT, for people unaware, you have:

* `glutIdleFunc(func)`: registers the render function and this means that when GLUT is not doing anything else, it will call this function. In other words, it will keep rendering as fast as possible.
* `glutTimerFunc(msecs, func, val)`: registers a function that will be called in `msecs` and the registering the same function recursively would allow for a fixed time based movement.

Now, I'm trying to avoid these functions for this purpose and most discussions/articles I found about GLUT, use them for time based movement. So I have come here once again... But if I'm not using any of those functions, how are the frames rendered? I just call `glutPostRedisplay` and a single frame will be rendered.

I have managed to implement time based movement in GLUT in a simple manner. May not be the best implementation, but it's not overly complex and works. Well, there's only a slight problem, that's why I'm here.

My camera movement is based on Newton's Second Law of Motion, where I calculate the displacement movement like this:

```
Vector3D displacement = (CurrentVelocity * elapsedTime) +
    (Acceleration * 0.5f * elapsedTime * elapsedTime);

```

The `elapsedTime` comes from my timer implementation and I think that's where the problem lies. The problem is that `displacement` should be positive or negative depending on the movement direction but if `CurrentVelocity` is a really low value (ie: -0.1f), the `displacement` will be positive when it should be negative. The rest of the code will accelerate or deacelerate the camera, so the problem only happens when accelerating because that's when `CurrentVelocity` will be small and what happens is that the camera moves slightly to the right (positive) and then to the left (negative) when it gains enough momentum to give a negative `displacement` value.

Now, when there's no movement in the scene, nothing is being rendered at all. When I press on of the movement keys, I do this:

```
CameraDirection.z = CAMERA_WALK_BACKWARD;
SceneTimer.PostRedisplayWindow();

```

That also comes from my timer class, I do that instead of calling `glutPostRedisplay` and the reason for that is this:

```
void Timer::PostRedisplayWindow(void) {
    currentTime = glutGet(GLUT_ELAPSED_TIME);
    glutPostRedisplay();
}

```

I need to get the `currentTime` (which will become the `previousTime` when I need to calculate the elapsed time) and then I call `glutPostRedisplay`. A single frame will be rendered, which means the `renderScene` will be called:

```
void renderScene(void) {
    (...)

    glLoadIdentity();

    elapsedTime = SceneTimer.GetElapsedTimeInSeconds();

    SceneCamera.Move(CameraDirection, elapsedTime);
    SceneCamera.LookAt();

    drawCompleteScene();

    glutSwapBuffers();

    checkAnimationRedisplay();
}

```

As you can see, the elapsed time is calculated and the camera is moved on that. Everything in the scene is drawn, swap buffers and then I have this extra function which will check if something needs to be animated, in this case, the camera needs:

```
void checkAnimationRedisplay(void) {
    if(SceneCamera.IsCameraMoving()) {
        glutPostRedisplay();
        return;
    }
}

```

It will keep calling `glutPostRedisplay` until the camera has stopped moving. Meaning, `renderScene` will be called every time, the elapsed time is calculated and the camera is moved based on time, everything's working; besides, of course, the little glitch already mentioned, little but the one that made me create this long question (sorry about that).

All that's missing is the most important function of this question, the one that calculates the elapsed time, simple as this:

float Timer::GetElapsedTimeInSeconds(void) { static int previousTime = 0; static int elapsedTime = 0;

```
previousTime = currentTime;
currentTime = glutGet(GLUT_ELAPSED_TIME);
elapsedTime = currentTime - previousTime;

return elapsedTime / 1000.0f;

```

}

There's probably something wrong with my timer code right? I mean, moving forward or right (positive values), there's no problems. The movement is smooth and time based. For instance, if I set a movement speed of 5m/s, it will actually take 5 seconds to move 25meters (I'm assuming 1m = 1.0f).

So, what I'm doing wrong with the timer so that the negative values start moving to the right for a split-second and only then to the left as it should?

**EDIT:**

A little more code as requested, this is how the `CurrentVelocity` is how calculated and how the displacement is applied:

```
void Camera::Move(Vector3D direction, float elapsedTime) {
    // Move only if the velocity vector is not of zero length (guards against
    // floating point rounding erros
    if(CurrentVelocity.SquaredMagnitude() != 0.0f) {
        Vector3D displacement = (CurrentVelocity * elapsedTime) +
            (Acceleration * 0.5f * elapsedTime * elapsedTime);

        Vector3D ForwardVector = Reference;

        if(cameraType != CAMERA_TYPE_SPECTATOR) {
            ForwardVector = Vector3D::CrossProduct(WORLD_SKY_VECTOR, RightVector);
            ForwardVector.Normalize();
        }

        Position = Position + (RightVector * displacement.x);
        Position = Position + (WORLD_SKY_VECTOR * displacement.y);
        Position = Position + (ForwardVector * displacement.z);
    }

    UpdateCameraVelocity(direction, elapsedTime);
}

void Camera::UpdateCameraVelocity(const Vector3D direction, float elapsedTime) {
    // Accelerate camera if the direction is -1 or 1 or decelerate if it's 0
    if(direction.x != 0.0f) {
        // Accelerate the camera
        CurrentVelocity.x += direction.x * Acceleration.x * elapsedTime;

        // Don't let it go beyond the max velocity
        if(CurrentVelocity.x > MaxVelocity.x) {
            CurrentVelocity.x = MaxVelocity.x;
        } else if(CurrentVelocity.x < -MaxVelocity.x) {
            CurrentVelocity.x = -MaxVelocity.x;
        }
    } else {
        // Decelerate the camera in the correct direction
        if(CurrentVelocity.x > 0.0f) {
            CurrentVelocity.x -= Acceleration.x * elapsedTime;

            // Don't let it start move in the opposite direction
            if(CurrentVelocity.x < 0.0f) {
                CurrentVelocity.x = 0.0f;
            }
        } else {
            CurrentVelocity.x += Acceleration.x * elapsedTime;

            // Don't let it start move in the opposite direction
            if(CurrentVelocity.x > 0.0f) {
                CurrentVelocity.x = 0.0f;
            }
        }
    }

    // All code below was removed, it's similar for all other axis...
}

bool Camera::IsCameraMoving(void) {
    return CurrentVelocity.SquaredMagnitude() != 0.0f;
}

```

# Answer
> 2 votes
Does the problem occur whenever you change the direction or only when changing from positive values to negative values? If it is always, it is most likely the last acceleration stored from last movement which is still slightly bigger than zero. How do you determine that the movement is over in IsCameraMoving() ?

Can you show the entire calculation of CurrentVelociy and Acceleration and how you apply the displacement?

Also double check that you reset all components of CameraDirection properly.

Edit:

Solution: The `displacement` calculation in `Camera::Move()` was wrong. `Acceleration` must also be multiplied with `direction` here as also done in `Camera::UpdateCameraVelocity`, otherwise it points into the wrong direction.

`Vector3D displacement = (CurrentVelocity * elapsedTime) + (direction * Acceleration * 0.5f * elapsedTime * elapsedTime);`

# Answer
> 0 votes
Wouldn't it be better (just cpu performance) this formula:

```
Vector3D displacement = ((CurrentVelocity + (direction * Acceleration * 0.5f * elapsedTime)) * elapsedTime);

```

Instead of given one

```
Vector3D displacement = (CurrentVelocity * elapsedTime) + (direction * Acceleration * 0.5f * elapsedTime * elapsedTime);

```

as it has 1 less operation?

---
Tags: opengl, animation, glut
---


title: OpenGL optimization tips

text:
# Question
Title: OpenGL optimization tips
What tips or tricks do you have when it comes to making the OpenGL more efficient?

# Answer
Use VBO rather than glStart()/glEnd(). This saves cycles in transferring the data to the GPU's memory.
> 16 votes

# Answer
The standard tip of profile, profile, profile applies just as well here, although the tools are slightly different.

gDEBugger is great at helping you see exactly what's going on under the hood. It's expensive, though.
> 8 votes

# Answer
These are from Apple's documentation references on OpenGL but every little bit helps right? ;)

OpenGL Performance Optimization : The Basics
Optimizing OpenGL Data Throughput on OS X

(This last one is a sample application)
Vertex Optimization

There are also a very large number of videos available on the subject (Also from Apple) that talk about OpenGL extensions. Some of them are OS X specific, but a few others are more generalized and could most likely be applied to Windows and Linux.

You can find the videos here. You do require iTunes and an Apple account to view them however (but they are free! :D)
> 8 votes

# Answer
Well, it really, really depends on what you're planning to do, but here are the basics:

* Your CPU is very precious while your GPU is a hungry beast. Offset as much as you can to the GPU. Nowadays you can do this with excellent libraries like OpenCL, CUDA and Thrust.
* Do your lighting in a shader. Not only will this help retain your sanity, but it allows you to very cool things like toon shaders and deferred lighting.
* Particles suck. Even when using OpenGL point sprites.
> 8 votes

# Answer
Minimize your state changes. On a lot of platforms, each state change potentially flushes the pipeline. It's much better to batch similar items together and change state once.
> 6 votes

# Answer
```
glEnable(GL_CULL_FACES);

```

Simple one liner that applies back face culling. This is excellent for trimming down polygon count. Also look into Frustum/Occlusion culling for reducing poly counts.

Another thing to look into is SIMD for your vectors and quaternions (mostly used in camera rotations). If you don't want to mess with ASM then check out libSIMD which is a great library for handling SIMD in C.
> 4 votes

# Answer
Don't use glGet\* when you can access local variables, e.g.:

* Don't query textures size from OpenGL, store them on loading in variables
* Don't query line widths / points sizes from OpenGL when you can store the changes in your application

These calls are really slow

Move unused stuff outside of glBegin - glEnd clause (be it glColor or glNormal or anything else) if it does not changes inside. OpenGL is a state machine, it uses the last value.
> 4 votes

# Answer
Minimize OpenGL commands is the key. So you must batch all drawing commands. For 2d games, it is a good idea to use Altas Texture and draw all sprites sharing the same texture in one opengl command.
> 3 votes

# Answer
Batch, batch, batch!! (Ab)use the GPU to render as much as possible in each draw call. Games are mostly limited by the amount of state changes, not so much by the amount of triangles.
> 3 votes

---
Tags: opengl, optimization
---