# Question
Title: How to export 3D models that consist of several parts (eg. turret on a tank)?
What are the standard alternatives for the mechanics of attaching turrets and such to 3D models for use in-game? I don't mean the logic, but rather the graphics aspects.

My naive approach is to extend the MD2-like format that I'm using (blender-exported using a script) to include a new set of properties for a mesh that:

* is anchored in another 'parent' mesh. The anchor is a point and normal in the parent mesh and a point and normal in the child mesh; these will always be colinear, giving the child rotation but not translation relative to the parent point.
* has a normal that is aligned with a 'target'. Classically this target is the enemy that is being engaged, but it might be some other vector e.g. 'the wind' (for sails and flags (and smoke, which is a particle system but the same principle applies)) or 'upwards' (e.g. so bodies of riders bend properly when riding a horse up an incline etc).
* that the anchor and target alignments have maximum and minimum and a speed coeff.
* there is game logic for multiple turrets and on a model and deciding which engages which enemy. 'primary' and 'secondary' or 'target0' ... 'targetN' or some such annotation will be there.

So to illustrate, a classic tank would be made from three meshes; a main body mesh, a turret mesh that is anchored to the top of the main body so it can spin only horizontally and a barrel mesh that is anchored to the front of the turret and can only move vertically within some bounds.

And there might be a forth flag mesh on top of the turret that is aligned with 'wind' where wind is a function the engine solves that merges environment's wind angle with angle the vehicle is travelling in an velocity, or something fancy.

This gives each mesh one degree of freedom relative to its parent. Things with multiple degrees of freedom can be modelled by zero-vertex connecting meshes perhaps? This is where I think the approach I outlined begins to feel inelegant, yet perhaps its still a workable system? This is why I want to know how it is done in professional games ;)

Are there better approaches? Are there formats that already include this information? Is this routine?

# Answer
> 3 votes
Yap. Bones formats. MD2 is a vertex animation format, not bones based format. And in Blender, depends on the version you're working with, but can probably make use of:

* Directx \*.x (I think in both 2.49 and 2.56 beta)
* \*.md5 . Doom III, like md2, from Id Software, but much better than md2. Md2 has vertex position accuracy problems, normals/lighting problems, UVs have its issues too, etc. Still, all blenders do export it, and can be useful for the flag animation. But you can asign some bones to the flag, some weight painting, and have same effect.Even easier.
* Collada. But it is still not ended, in certain newest builds at graphicall.org I have checked to be working, at least in basic stuff which you need.
* You need to use Blender 'constraints' in your bone animations, to have the behaviours you mention, and then export with those "baked". Then code would do the rest.(and don't quote me on this, but I think md5 did export constraints also. And that you can use a md5 version with blender 2.41. I think , set as an addon, md5 can work well with 2.56, but have not tried yet.)

A good knowledge of Blender rigging (bones, weights, constraints) system and formats is quite needed for this, but seems pretty doable.

A lot of people just used to use Milkshape, ideal for these kind of things, and there were very good loaders for game programmers, for ms3d format.

IMHO you can achieve the same by loading for example an md5, there are good loaders out there, and am told is an easy to handle format for programmers. Collada anyway might be the best in long run: Is the definite Blender's bet, and in general, everybody, engines, etc, are trusting on it. But it's a very complex format, so making a loader might be hard, unless you can grab sth already made or whatever. I don't know, that's the programmer side of things.

# Answer
> 2 votes
I'm not entirely sure if I fully understood your question(s). But I'd definitely use a mesh format that supports bones and animations. Especially the bones are important if you wish to move separate mesh-parts individually.

The flag you're speaking of could be pre-animated (wave movement) and aligned in the direction of the wind by using bones. The speed of the animation could be controlled by the strength of the wind.

I can't give you any format recommendations though, since you didn't mention the engine/framework you're using. OGRE for example uses its own mesh format that supports bones and animations. Unity can load several popular native formats directly... and there's always Collada, an XML based 3D format which you could write a parser for (or use an existing one).

---
Tags: 3d-meshes, models
---


title: OpenGL or OpenGL ES

text:
# Question
Title: OpenGL or OpenGL ES
What should I learn? OpenGL 4.1 or OpenGL ES 2.0?

I will be developing desktop applications using Qt but I may start developing mobile applications in a few months, too. I don't know anything about 3D, 3D math, etc and I'd rather spend 100 bucks in a good book than 1 week digging websites and going through trial and error.

One problem I see with OpenGL 4.1 is as far as I know there is no book yet (the most recent ones are for OpenGL 3.3 or 4.0), while there are books on OpenGL ES 2.0.

On the other hand, from my naive point of view, OpenGL 4.1 seems like OpenGL ES 2.0 + additions, so it looks like it would be easier/better to first learn OpenGL ES 2.0, then go for the shader language, etc

Please, don't tell me to use NeHe (it's generally agreed it's full of bad/old practices), the Durian tutorial, etc.

Thanks

# Answer
I suggest going the route with OpenGL ES 2.0, because as you have already said it is pretty much a subset of modern OpenGL. You should also be aware that even today some mobile devices only support OpenGL ES 1.0, which is radically different to OpenGL ES 2.0 and more like OpenGL 2.x (fixed function).
> 6 votes

# Answer
From a general point of view, either. The practices you learn in one will benefit you in the other.

It's more of a question of what you have access to, and what your interests are.

As for books, any book related to OpenGL later than 2.0 will help you get into the bleeding edge, since OpenGL works through extensions.

Also see What is the difference between OpenGL ES and OpenGL?
> 5 votes

---
Tags: opengl, graphics, graphics-programming, opengl-es, qt
---


title: 2D Skeletal Animation Transformations

text:
# Question
Title: 2D Skeletal Animation Transformations
I have been trying to build a 2D skeletal animation system for a while, and I believe that I'm fairly close to finishing. Currently, I have the following data structures:

```
struct Bone {
    Bone *parent;
    int child_count;
    Bone **children;
    double x, y;
};

struct Vertex {
    double x, y;
    int bone_count;
    Bone **bones;
    double *weights;
};

struct Mesh {
    int vertex_count;
    Vertex **vertices;
    Vertex **tex_coords;
}

```

`Bone->x` and `Bone->y` are the coordinates of the end point of the Bone. The starting point is given by `(bone->parent->x, bone->parent->y)` or `(0, 0)`. Each entity in the game has a `Mesh`, and `Mesh->vertices` is used as the bounding area for the entity. `Mesh->tex_coords` are texture coordinates. In the entity's update function, the position of the `Bone` is used to change the coordinates of the `Vertices` that are bound to it. Currently what I have is:

```
void Mesh_update(Mesh *mesh) {
    int i, j;
    double sx, sy;

    for (i = 0; i < vertex_count; i++) {
        if (mesh->vertices[i]->bone_count == 0) {
            continue;
        }

        sx, sy = 0;
        for (j = 0; j < mesh->vertices[i]->bone_count; j++) {
            sx += (/* ??? */) * mesh->vertices[i]->weights[j];
            sy += (/* ??? */) * mesh->vertices[i]->weights[j];
        }

        mesh->vertices[i]->x = sx;
        mesh->vertices[i]->y = sy;
    }
}

```

I think I have everything I need, I just don't know how to apply the transformations to the final mesh coordinates. What tranformations do I need here? Or is my approach just completely wrong?

# Answer
> 2 votes
I believe you would be looking to using transformation matrices here, though i think you need to elaborate upon your update function in order to accomodate for this. Ask yourself what transformations you need - translation, rotation?

```
        sx, sy = 0;
    for (j = 0; j < mesh->vertices[i]->bone_count; j++) {
        sx += (/* ??? */) * mesh->vertices[i]->weights[j];
        sy += (/* ??? */) * mesh->vertices[i]->weights[j];

```

I find sometimes putting something down in plain english helps. The above for e.g.:

For each bone, perform a (transformation) multiplied by the weights of the bone.

I would put more into

* Are we rotating or translating this bone?
* Does the parent constrain this
movement?

Matrices are handy for this because they can work off of a structure like this in that you can work out the constraint from the parent bone's information and apply it to the child bone.

* Perform transformation based on previous questions

This may be a completely wrong way about things, but certainly food for thought.

---
Tags: 2d, skeletal-animation, matrix
---


# Question
Title: How to determine which cells in a grid intersect with a given triangle?
I'm currently writing a 2D AI simulation, but I'm not completely certain how to check whether the position of an agent is within the field of view of another.

Currently, my world partitioning is simple cell-space partitioning (a grid). I want to use a triangle to represent the field of view, but how can I calculate the cells that intersect with the triangle?

Similar to this picture:

The red areas are the cells I want to calculate, by checking whether the triangle intersects those cells.

Thanks in advance.

EDIT:

Just to add to the confusion (or perhaps even make it easier). Each cell has a min and max vector where the min is the bottom left corner and the max is the top right corner.

# Answer
Calculate the three corners of your fov triangle, rotate them to be facing the correct way and such, and then do one of:

1) do a point-in-triangle test for all the potential targets

2) calculate the bounding box of the this triangle, and do a point-in-triangle test for all potential targets in cells in this bounding box - this will be very straightforward code to debug

A similar approach is to use a quadtree rather than a grid and do the intersections on that. If the O(1) tile access is speeding you up, then just testing all the cells in the bounds of the fov triangle for in-triangle ought to be so fast as to be instant. As you're looking at other options, I presume its not and that the O(1) is actually taking a massive cache miss cost as you thrash your cache. You could of course perhaps look at prefetch instructions to annotate your bounding box walk with...

3) 'rasterise' this triangle and check the cells that it 'paints' - likely the most efficient code, but perhaps only marginally as I'd speculate its all dominated by cache miss times and depends on how complex your cells are and how occupied they are.

An alternative approach is to render the FOV to an off-screen bitmap and then read the pixel value for each of your objects; you can't 'unmix paint' but with a limited number of objects and by carefully choosing your paint you can deduce who saw who. This approach is similar to how many games work out what the user clicked on - they draw the scene off-screen using solid colours for the hit-areas. GPUs are very fast at triangle fill...
> 6 votes

# Answer
The canonical solution in software renderers (which must do this exact algorithm every time they rasterize a triangle) is, I believe, to scan the triangle one row of pixels at a time. The left and right edges of each row and calculated by walking down the sides of the triangle using Bresenham, and then you fill in the row between them.

I'm glossing over *lots* of details but that's the basic idea. If you hunt around for "software render" and "triangle rasterization", you'll probably find some more details. This is a well-solved problem. Your graphics card is doing this millions of times a frame.

If you want a more roguelike-specific solution, here's how I implemented FOV in mine. It seems to work pretty quickly. It's essentially a simple shadow caster, working on octant at a time, scanning outwards from the player.
> 3 votes

# Answer
I'm using a variation of the scanline algorithm to solve the exact same problem. I started by sorting the three triangle points by their height. I then basically check whether two edges are on the left or on the right side. For the side with two edges, you have to mark they row where you change which edge delimits your rows. For the side with one edge, you can just always use that.

So then for each row, I know which two edges delimit the it, and I can compute upper and lower bounds in x-direction. It sounds quite complicated, but it condenses down to just a few lines of code. Make sure you handle the special-case where one edge is completely horizontal!
> 2 votes

# Answer
How about maintaining a range of columns for each row that are in the triangle? What you can do is set the min and max column for each row where each point is, and where each triangle line crosses a horizontal row separator line.

```
public class Point
{
    public float X;
    public float Y;
    public Point(float x, float y) { this.X = x; this.Y = y; }
}

public class Line
{
    float ROW_SIZE = 100f;
    float COL_SIZE = 100f;

    public Point P1, P2; // P1 has the lowest Y
    public float Slope, Intercept; // set in constructor
    public bool IsVertical;

    public Line(Point p1, Point p2)
    {
        if (p1.Y > p2.Y) { P1 = p2; P2 = p1; } // p1 has lowest Y
        else { P1 = p1; P2 = p2; }
        IsVertical = (p1.X == p2.X);
        if (!IsVertical) { Slope = (p2.Y - p1.Y) / (p2.X - p1.X); Intercept = p1.Y - Slope * p1.X; }
    }

    public void ExpandRanges(int[] minCol, int[] maxCol)
    {
        // start out at row, col where P1 is, which has lowest Y
        int row = (int)(P1.Y / ROW_SIZE);
        int col = (int)(P1.X / COL_SIZE);
        int lastRow = (int)(P2.Y / ROW_SIZE);
        int lastCol = (int)(P2.X / COL_SIZE);

        // expand row to include P1
        minCol[row] = Math.Min(col, minCol[row]); maxCol[row] = Math.Max(col, maxCol[row]);

        // now we find where our line intercepts each horizontal line up to P2
        float currY = P1.Y;
        float currX = P1.X;
        while (row < lastRow)
        {
            row = row + 1;
            float rowY = row * ROW_SIZE;
            float diffY = rowY - currY;
            float diffX = IsVertical ? 0f : diffY / Slope;
            currY = currY + diffY;
            currX = currX + diffX;
            col = (int)(currX / COL_SIZE);

            // expand rows above and below dividing line to include point
            minCol[row - 1] = Math.Min(col, minCol[row - 1]);
            maxCol[row - 1] = Math.Max(col, maxCol[row - 1]);
            minCol[row] = Math.Min(col, minCol[row]);
            maxCol[row] = Math.Max(col, maxCol[row]);
        }

        // expand last row to include P2
        minCol[lastRow] = Math.Min(lastCol, minCol[lastRow]);
        maxCol[lastRow] = Math.Max(lastCol, maxCol[lastRow]);
    }

    public static void Test()
    {
        Point p1 = new Point(160, 250);
        Point p2 = new Point(340, 250);
        Point p3 = new Point(250, 40);
        Line l1 = new Line(p1, p2);
        Line l2 = new Line(p2, p3);
        Line l3 = new Line(p3, p1);

        Line[] lines = { l1, l2, l3 };

        int rowCount = 4;
        int[] minCol = new int[rowCount];
        int[] maxCol = new int[rowCount];
        for (int i = 0; i < rowCount; i++)
        {
            minCol[i] = int.MaxValue;
            maxCol[i] = int.MinValue;
        }

        for (int i = 0; i < lines.Length; i++)
            lines[i].ExpandRanges(minCol, maxCol);

        for (int i = 0; i < rowCount; i++)
            Console.WriteLine("Row {0}:  {1} - {2}", i, minCol[i], maxCol[i]);
    }
}

```

Output:

```
Row 0:  2 - 2
Row 1:  1 - 3
Row 2:  1 - 3
Row 3:  2147483647 - -2147483648

```
> 2 votes

# Answer
There's some algorithm work done in the roguelike community that deals with FOV/LOS/lighting in a tile-based world.

Perhaps you can find something on this page that can be used to help solve your problem: http://roguebasin.roguelikedevelopment.org/index.php?title=Field\_of\_Vision

Specifically "Permissive FOV" might be the most applicable to your situation.
> 1 votes

---
Tags: collision-detection, intersection
---


# Question
Title: Recommended hardware for developing ios games?
I know you have to have mac os x to use xcode and thus to develop/compile apps for the iphone. And I'm not exactly wanting to go the hackintosh way, so I'm looking at buying a used mac.

What specs are recommended. If I buy a cheap mac mini that has only 1gb of ram would that be enough? (I'm not talking about using that to create the graphics/audio, I'll use my normal windows/ubuntu pc for that). I'm just talking about being able to use xcode and write applications.

I'm trying to spend the least amount I can without running into problems developing the app.

# Answer
I use two machines regularly while doing iOS development -- a late 2009 quad core i5 iMac and an 11" MacBook Air. Both machines have their pluses and minuses, but both are more than capable enough for the job. Basically it comes down to buying what you can afford and what you feel comfortable with. Any Mac sold by Apple today has more than enough power for iOS development.

If you go with a used Mac, I would try to stick with the 64-bit capable Macs rather than a 32-bit only like the original MacBook, MacBook Pros, iMacs and Mac minis. The only reason I recommend this is that Apple typically drops support for some machines every time a new major OS X release is done. And the 32-bit Macs are looking like the most likely candidates for being dropped with Lion. The other side of this is that Apple also has been keeping iOS developers on the latest OS X release -- the latest SDKs are now requiring 10.6.6, for example.

Don't skimp out on RAM -- 1GB of RAM is not enough to keep MacOS X, Xcode, Interface Builder and the simulator happily in RAM all the time. You will not be very happy with just 1GB of RAM. 4GB of RAM is fairly cheap these days -- even on some of the older machines where Apple says it can only take 2GB you can actually toss in 4GB and get about 3.5GB of memory. The Core 2 Duo MacBooks are like this, probably some of the Mac minis as well.

On the iOS device side, you'll obviously need at least one device to develop and test with. The cheapest option is the 8GB iPod touch. But if you are intending to make a real game to release, you'll want to have other devices as well. At the very least, you should have one of each device for each generation you want to support -- so if you are only targeting the current generation, that would be an iPod touch and an iPhone 4. If you want to target the prior generation, you should have those as well. You can get away with not having the newer hardware if all you have is an older device, but I wouldn't recommend only having the newer hardware while also targeting the older devices. There are huge differences in how OpenGL and the CPU performs on some of the devices and you really don't want to find out about those differences while reading the reviews for your app. And then there is the iPad as well to consider as well...
> 3 votes

# Answer
The big concern is that is has to be able to run Snow Leopard, the latest version of Mac OSX, in order to run the latest version of xcode. As long as it can run that, you can do your development on it.

I would not expect great speed, though.
> 3 votes

# Answer
If you already have a good PC, you could indeed turn it into a Hackintosh (dual-boot OS X or whatever) to run Xcode and do the programming, and then transfer your code to a low-powered Mac Mini when it's all ready. It is of course against Apple's terms to actually publish an app from a hackintosh system (whether they actually detect it is another matter; I don't know the answer to that), but **code is code. It's just text.** Who's to say what you wrote it on?

You could write an iOS app on a clay tablet, and as long as you transcribe it into OS X before the final compile and publish, you'd be fine. :)

<sub>(IANAL, just speaking from common sense.)</sub>
> 2 votes

# Answer
I have not tried this but, you can run os x in a virtual machine.

Also get a old iphone or ipod touch to try your app out. If it runs well on old hardware it runs great on new hardware.
> 0 votes

---
Tags: iphone, hardware, development-speed, ios
---


# Question
Title: How can I make a collection of mini-games in XNA where the user can download packs of minigames and the main .exe can run them without being altered?
I'm currently making a PC game in XNA. It's actually a collection of mini-games (there's 3 mini-games at the moment) however I plan to make and add more, in downloadable 'packs'.

My question is, what's the best way to achieve this?

Currently my thoughts are:

* Create a 'game' interface
* Build games to this interface but create them as .dlls
* Have the main .exe file scan a directory and load in the .dlls at runtime.

I've not messed around with the idea much, but I know there are applications at-least that use this plug-in approach (Notepad++ seems to), but I'm not sure of any games that do (although I'm sure they must exist). However it seems that this is a problem that has been solved previously, so I'm wondering if there's any form of established best-practice.

# Answer
On windows, you can you can just open an assembly (dll) and import types and execute methods. See the Assembly Class documentation.

On the Xbox 360 you do not have access to System.Reflection. Here you should rely on the XBLA store API. I'm not sure how much of this functionality is available to XBLIG applications.
> 5 votes

# Answer
Since you're building a game for Windows, you can access the full framework as @Ranieri stated. Your architecture sounds solid; however, you might want to check into MEF, the Managed Extensibility Framework. It might make that workflow you outline more streamlined. I haven't used it myself, but I've read good things about it.
> 1 votes

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


# Question
Title: How are you handling scores that can worsen (e.g. Elo rating) in Game Center?
Currently, Game Center leaderboard scores can only change one-way (e.g. increase). This makes it impossible (I think) to deal with Elo ratings and the like. How are you getting around this in your leaderboards?

I have filed a bug report / feature request with Apple already FWIW.

Are you using a third-party leaderboard service? Rolling your own?

# Answer
> 5 votes
Off the top of my head, if negative scores are not allowed: track positive and negative scores separately.

For instance, when writing the leaderboard:

```
// Pseudocode
points_for_win = 3;
points_for_loss = 2;

if (didWin)
    leaderboard.positive_score += points_for_win;
else
    leaderboard.negative_score += points_for_loss;

```

When retrieving the leaderboard, you can then compute the user's actual score by:

```
actual_score = leaderboard.positive_score - leaderboard.negative_score;

```

---
Tags: iphone, cocos2d-iphone, game-center, leaderboards
---


# Question
Title: Flash, Java, Unity plugin install penetration?
Is there data on how many users have Flash, Java, or Unity plugins installed?

# Answer
> 4 votes
This website extrapolates from a panel of some sort:

http://www.riastats.com/

Bottom line as of posting this:

* Flash: 97%
* Silverlight: 70%
* Java: 75%

# Answer
> 3 votes
Others have mentioned Flash, Java and Silverlight. Sadly there are no official numbers for Unity I'm aware of. In a rather old blog post they talk about ~1% pre-installed user base. This article over at Gamasutra also assumes 1% penetration. Although the conversion seems to be rather high (people willing to install the plugin).

User base might also increase with gaming platforms like Kongregate supporting Unity Web-Games.

# Answer
> 1 votes
According to the Adobe Flash website, Flash Player Version Penetration, it's about 99-98% in most markets.

Java is also pretty ubiquitous. Unity is less frequently found, however the installer is inline and quite small in most cases.

---
Tags: flash, java, unity, browser-based-games
---


title: Mouse aim in an FPS

text:
# Question
Title: Mouse aim in an FPS
I would like to make a First Person Shooter and move the camera with the mouse. The problem is that when the cursor reaches the limits of the screen, the camera won't turn anymore. How can I keep the mouse centered and detect its movements anyway?

# Answer
> 38 votes
The general approach to handling this in classic Win32 programming is to capture the mouse delta each frame, and then reset the mouse position to the center of the screen. You also want to make the mouse cursor invisible, obviously, as otherwise things look ugly.

You can do the same thing in XNA, you just work with a slightly different interface. So you might do something like:

1. At startup, set the mouse's position to the center of your screen with Mouse.SetPosition.
2. Also at startup, make the mouse invisible.
3. Every input frame, grab the current mouse state.
4. Since you know the mouse was at the center, you can use the current X and Y values from the MouseState object you recovered in step #3 to compute the delta movement in both dimensions. You can feed these deltas to the rest of your game logic, such as (in your case) the camera code.
5. Reset the mouse to the center of the screen before moving on to the next frame.

EDIT: Also, here is a tutorial I dug up via a Google search for "XNA relative mouse input" (which is what you're asking about). It's a bit old, I think, so some of the methods may have had their names changed, but the concepts should still apply.

EDIT 2: Meant to say "handling this *in* Win32" and not "handling this *is* Win32," updated accordingly.

---
Tags: xna, camera, first-person-shooter, aiming, mouse
---


# Question
Title: snapping an angle to the closest cardinal direction
I'm developing a 2D sprite-based game, and I'm finding that I'm having trouble with making the sprites rotate correctly. In a nutshell, I've got spritesheets for each of 5 directions (the other 3 come from just flipping the sprite horizontally), and I need to clamp the velocity/rotation of the sprite to one of those directions. My sprite class has a pre-computed list of radians corresponding to the cardinal directions like this:

```
protected readonly List<float> CardinalDirections = new List<float>
                           {
                               MathHelper.PiOver4,
                               MathHelper.PiOver2,
                               MathHelper.PiOver2 + MathHelper.PiOver4,
                               MathHelper.Pi,
                               -MathHelper.PiOver4,
                               -MathHelper.PiOver2,
                               -MathHelper.PiOver2 + -MathHelper.PiOver4,
                               -MathHelper.Pi,
                           };

```

Here's the positional update code:

```
if (velocity == Vector2.Zero)
            return;

        var rot = ((float)Math.Atan2(velocity.Y, velocity.X));
        TurretRotation = SnapPositionToGrid(rot);

        var snappedX = (float)Math.Cos(TurretRotation);
        var snappedY = (float)Math.Sin(TurretRotation);
        var rotVector = new Vector2(snappedX, snappedY);

        velocity *= rotVector;
        //...snip

private float SnapPositionToGrid(float rotationToSnap)
    {
        if (rotationToSnap == 0)
            return 0.0f;

        var targetRotation = CardinalDirections.First(x =>
                (x - rotationToSnap >= -0.01 && x - rotationToSnap <= 0.01));
        return (float)Math.Round(targetRotation, 3);

    }

```

What am I doing wrong here? I know that the SnapPositionToGrid method is far from what it needs to be - the .First(..) call is on purpose so that it throws on no match, but I have no idea how I would go about accomplishing this, and unfortunately, Google hasn't helped too much either. Am I thinking about this the wrong way, or is the answer staring at me in the face?

EDIT: Thanks Gregory for the answer. Only thing I really had to modify from the answer was to re-construct the velocity vector to the new snapped rotation (I'm sure there are further optimizations that I can do, but for now it's enough that it works!):

```
        var snappedX = (float)Math.Round(Math.Cos(TurretRotation), 3) *
                           velocity.Length();
        var snappedY = (float)Math.Round(Math.Sin(TurretRotation), 3) *
                           velocity.Length();
        var rotVector = new Vector2(snappedX, snappedY);

```

FOLLOW-UP EDIT: The initial answer worked very well as a naive implementation, but suffered from inaccuracies of up to 45 degrees when dealing with negative angles; -3.14 snapped to -2.356 for instance. To correct that, I added a check to account for those situations. Below is a complete implementation of a SnapToGrid method. Some optimizations have been made, like pre-computing the various divisors of Pi to avoid the division. Further optimization could possibly be achieved by looking for short-circuit scenarios, i.e. `if rotationToSnap ~=0,` but if anyone has further optimizations, I'd be curious to see them!

```
public static float SnapPositionToGrid(float rotationToSnap)
{
    if (rotationToSnap == 0)
        return 0.0f;

    var modRot = rotationToSnap  % MathHelper.PiOver4;

    float finalRot;

    if (modRot < RoundedPiOver8)
    {
        if (modRot < -RoundedPiOver8)
            finalRot = rotationToSnap + -MathHelper.PiOver4 - modRot;
        else
            finalRot = rotationToSnap - modRot;
    }
    else
        finalRot = rotationToSnap + MathHelper.PiOver4 - modRot;

    return (float)Math.Round(finalRot, 3);
}

```

# Answer
> 8 votes
I'd do this mathematically, assuming I understand your question. You want your rotation to be an integer multiple of PiOver4, right? So divide by your direction increment, round to the nearest integer, and multiply by the increment again. An unoptimized version would be:

```
return PiOver4 * (float) Math.Round(rotationToSnap / PiOver4);

```

I'm not too familiar with optimization in XNA; if modulos and comparisons are cheaper than multiplications and divisions (as I suspect), it'll be faster to do something like:

```
var modRot = rotationToSnap % PiOver4;
if(modRot < PiOver8) return rotationToSnap - modRot;
else return rotationToSnap + PiOver4 - modRot;

```

I haven't tested that code or anything, but it or a similar approach should work.

# Answer
> 0 votes
Gregory's answer can be amended to handle negative rotation by just wrapping and unwrapping by a full rotation:

```
return PiOver4 * (float) (Math.Round(TwoPi + rotationToSnap / PiOver4) - TwoPi);

```

---
Tags: xna, 2d, c#, mathematics, sprites
---


title: Sounds to describe the weather?

text:
# Question
Title: Sounds to describe the weather?
I'm trying to think of sounds that will help convey the time of day and weather condition. I'm not even sure of all the weather conditions I would consider, and some are obvious. Like if it's raining, the sound of rain. But then I'm thinking, what about for a calm day? If it's morning time, I could do birds chirping or something. Night time could be an owl or something. What are some good combinations of sounds/weather/time to have a good effect?

# Answer
> 6 votes
The sound of rain, provided it is not too loud, is a good idea, as a rain visual without a rain sound is disconcerting. Occasional playing of the sound of thunder can really help, but you would probably need to support some kind of lightning effect for that to work.

Is your game set in the country or the city? This drastically alters the sound of a 'calm' day and a usual night. Considering what you mentioned, I'm going to assume country. The sound of an occasional wind gust or a wolf howl for such a situation is not out of the question. Whatever enhances the overall feeling of being *in* the environment. That is quite possibly the biggest problem with music and sound effects - they are at their best when you don't even notice them for what they are; their presence is just part of the scene and they don't stand out.

Whatever your choice, make sure to sufficiently space the sound effect between plays and provide a pretty decent number of sounds that are played. Hearing the same hooting owl every three seconds at night could get *really* annoying.

# Answer
> 6 votes
How about using **background music** instead of sound effects?

Animal Crossing is a real-time game (meaning the game keeps track of the time), and it had a different background tune for each hour of the day; the tune in the middle of the day is upbeat, "friendly" sounding, and the night one is very quiet and slow with some extra percussion sounds thrown in. I don't recall any bird chirping sounds, though there is the sound of water running when you walk near a stream and the sound of your own footsteps when you walk around (specific to the material being walked on), and there definitely was the pitter-patter of rain when it was raining.

---
Tags: game-design, sound, special-effects, sound-effects
---


# Question
Title: What are typical job interview questions related to game development?
I've already looked at some examples from StackOverflow, but I'd like to know if any of you could show concrete examples of job interview questions... Are they different with a job related to game development?

# Answer
> 6 votes
The context of the questions might change, but not really; if you are looking to program, you will still be asked questions that apply to Computer Science in general, including, but not limited to:

* Mathematics
* Programming Syntax
* Programming Methodology
* Debugging

At least, I was. My programming methodology question was phrased in terms of game related terms, such as `ships` and `bullets`, but it was really a design question and a math question.

# Answer
> 17 votes
Am I a bad person because I think of these?

* What do you do for fun? *(Translation: Do you have a social life that will interfere with putting in 60 hour weeks normally, 100+ hour weeks in crunch?)*
* How do you balance your personal life with work? *(Translation: Have you had experience with a normal job that you put in a day at and then go home from when you're done, or can we format your brain with the insane expectations that make us money?)*
* Where do you see yourself in five years? *(Translation: Do we have a reasonable shot at keeping you in the same code monkey role for several product cycles?)*

**Disclaimer**: Please note that this answer contains a high quotient of bitterness and cynicism, and that its contents reflect a worst-case scenario that the gaming industry is unfortunately notorious for. There are many ethical and benignly-motivated people performing hiring and management in the industry, and being asked any of these questions *does not* automatically mean that the "translations" apply.

# Answer
> 6 votes
From my experience being interviewed:

* Expect some technical questions relating to your specialty (i.e. if you're trying for a graphics programmer position, expect some questions about what graphics libraries you've worked with and some of the more prominent graphics algorithms)
* Some companies give you programming tests, of the "write code to do X" variety. This might happen at your interview in real-time, or they might ask you to do this ahead of time and send it in with your application. Expect to struggle red-faced through the embarrassment of having to correctly identify the bugs in your own code.
* You may have some questions about other fields, such as audio, visual art, production and game design, or questions about your ability to play nicely with people in those fields. You don't need to be expert in non-programming fields, but you do need to be able to communicate effectively with non-programmers. (My favorite question: "Describe \[polymorphism / A\* / quaternions / whatever\] to me in terms my technophobic grandmother would understand.")
* Since game dev is so team-oriented, expect lots of non-programming questions that are trying to find team fit: questions about how you handle stressful situations, disagreements with superiors, eleventh-hour requests from publishers, impossible-to-implement specs from designers, and just generally if you're the kind of person that other people would like to spend more time with than they spend with their families.

Every company's interview process is different, of course, but I think you'll find more similarities than differences between game industry programming, and greater software industry programming, in terms of what the interview is like. The biggest difference is that in the game industry, the person interviewing you probably won't be wearing a suit :)

# Answer
> 4 votes
Of course, there are the standard interview questions (programming, personal, etc.). But then there are also the games-related questions, for example:

* What kinds of games do you like/play?
* What is your favorite game?
* Are you okay with working on genre X?

Furthermore, they might ask you about specific technologies/APIs/SDKs and what your specialization is (graphics? physics? audio?).

# Answer
> 4 votes
For the question like this there is great website: glassdoor.com. It is specialized mostly on inteviews and also offesr some other things about companies. Membership is free (or was a half of year ago) if you after some time you spend there fill yours interview in your company. Propably you will find lots of people attending on similar position at similar company.

And for me as a computer graphics engineer

* Describe graphic pipeline on gpu (not just programmable part, but how it really work)
* How would you do ... something related to the game engines (mine was shadows for omni-directional light.)
* shadow mapping, environment mapping, shading models, ambient occlusion ...

# Answer
> 4 votes
You didn't specify a discipline, but for programming almost every game company test I've seen has included:

* A question about virtual destructors in C++. What they do, when are they needed, etc.
* A question about dot products and cross products, what they do, how they're used, possibly how they're derived.

# Answer
> 3 votes
There is no other answer that is also not a good answer.

Programming Tests: Generally want to see what you are capable with and what your turn around times are.. Just remember that a Wrong answer is never a good one so do not rush these in order to make it look like you can turn them around quick. Just do a google search for programming tests. Also, take a look at the Sucker Punch programming test.. that one is Infamous and has been around forever (hundreds of forum posts generated from trying to get a good solution to it).

Over the phone: These will generally be light tech questions and mostly personal questions. Why do you want to make video games, why do you want to make Their video games.. etc so on and so forth.

In Person: Usually the final stage.. Making video games is VERY stressful.. you need to show you can be accommodating, interact with the person you are interviewing with and I can almost guarantee you will be shown around to a few other key members of the team. Also, some hands on tech questions can be brought up here... I have however been very successful in avoiding receiving them... Might be something to do with telling Them what their code/script is doing with out them asking me to write something ;)

Please note though, as mentioned at the start.. No other answer here is a bad answer, the questions will be wide and many.. Mostly game or game object oriented, but programming is programming.. video games just have to do it 60 times a second :)

Good Luck!

EDIT: Cached link to an old Sucker Punch Job Listing w/ Programming Test referenced at the bottom.

---
Tags: game-industry, jobs
---


# Question
Title: How can I get a velocity vector for an object moving in a circle?
I am simply trying to make an object move in a circle around a point. Let's say I have an object with a position vector going from that point to the object, and also the angle of the object with the x axis.

What is the equation I can use to obtain a velocity vector for that object so that it continues to move in a circle? What other information do I need?

# Answer
The velocity vector should be tangent to the circle, that is, perpendicular to the vector from the center to the current position. IIRC, the vector perpendicular to (u, v) is (-v, u).

Note that the perpendicular vector changes constantly as the object moves, so you need a new velocity vector after each update.
> 5 votes

# Answer
There is no single vector in Cartesian coordinates that will keep an object moving in a circle, as a single vector can only represent a straight line in the given system. However, you can express this motion in polar coordinates, where a straight line can actually represent circular motion in the equivalent Cartesian coordinate system.

For example, the polar vector (r=0,θ=5) rotates you 5 units around the origin (where a unit is typically a degree or a radian).

The rotation is done around the origin of the coordinate system, so you need to factor that in when converting between the 2 coordinate systems, typically as a translation done in Cartesian space I would expect.
> 3 votes

# Answer
I would use a vector that I call angularVelocity where the direction the vector is pointing represents the axis of rotation (orbital axis, in your case) and the magnitude represents the angular change per second. I can feed that vector to a matrix that is set up to perform an axis, angle rotation. All that is left is to offset this mechanism by the point that you want to orbit around. In pseudo code, it would look like this to orbit the moon around the earth assuming the sun was the gameworld origin:

```
angularVelocity = /*arbitrary*/ new Vector(0, 1, 0) * 3.14; //orbits 2 rev/sec

Matrix rotation = CreateARotationMatrix(angularVelocity);

moonPosition = ((moonPosition - earthPosition) * rotation) + earthPosition; //assuming your code library has a way to transform a vector by a matrix there.

public Matrix CreateARotationMatrix(Vector av)
{
   float angle = av.Length();
   Vector axis = av.Normalize;
   axisAngle4d.X = av.X;
   axisAngle4d.Y = av.Y;
   axisAngle4d.Z = av.Z;
   axisAngle4d.W = angle * elapsedTimeSinceLastFrame;

   //plug above into code found here to finish matrix: [http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm][1]

}

```

The speed that the object orbits (the mood in our case here) can be related directly to whatever linear velocity you want by factoring in the orbital radius.

Note: You only have to build that matrix once, not every frame, unless the axis or the angular rate changes.
> 1 votes

---
Tags: mathematics, algorithm
---


# Question
Title: Whats a good setup/toolchain for a project?
I was thinking, what is needed for a good setup and what are good (free) tools to use? Some of what i came up with are

* Bug tracking
* Some good (distributed:P) source control (which means no svn fellas)
* automated nightly builds or a continuous integration (or anything that automates builds and possibly sends emails when there are build errors)
* wiki to document decisions, road map or milestones.
* Something to backup assets (art, sound, etc)

What else? and do you have suggestions for any of the above? i pretty much clueless of all of these except for source control

# Answer
I can't say enough positive things about FogBugz. It's the best bug/task tracking system I've used. As of FogBugz 8 it even has a decent Wiki based of CKEditor. It supports plugins so you can extend it to do a bunch of stuff (like a Kanban board), or customize its workflow, or do more extensive timesheet reporting, or whatever. You can do self hosted or pay them to host.

Now the base solution isn't free, but you can do a "students and startups" hosted solution which is good for 2 users.

They have a separate product, Kiln, which is basically Mercurial but tied in Fogbugz (optionally) and has a pretty slick code review pipeline. I talked to one of the guys that worked on it and they said it had pretty decent tools for dealing with the "big file" problem with DVCS solutions (namely that every client has every version of every file, and that not scaling for, say, giant zbrush files), like filtering "big files" by extension, and that sort of thing.
> 3 votes

# Answer
Bitbucket uses Mercurial as its dvcs and has features similar to Github, but it also has a great free plan where you can store unlimited private projects with up to 5 collaborators.

http://bitbucket.org
> 2 votes

# Answer
Github, git, Hudson (note: this is not a hosted service), Github, Github :-)
> 1 votes

# Answer
I like Google Code a lot -- if you are willing to make your project open-source, it's pretty awesome. It provides you with hosting for code (SVN or Mercurial), files for releases, a simple-but-effective wiki, and a straight-forward bug tracker. The downsides are that access control for the wiki is limited, and edits to the wiki cause commits to your repository.

I've heard good things about github, and from what I've seen of it while grabbing people's code from it, I like it. But I have never used it for more than that, because I don't have a compelling need (or desire) to use distributed version control.

In the realm of less-general tools, Perforce is a powerful version control system that is used by just about every professional game development studio I have worked at or know of. They have free limited-user licenses. You need to host and administer the server yourself, though, which is something I have very limited experience doing so I can't comment much to that.

I have used Trac for bug tracking before (and still do for my own projects that I host on my private SVN). It's also simple -- I am a fan of simple bug tracking and such, instead of systems like Bugzilla, which I think are too much trouble to configure. I don't use Trac's built-in wiki, really, preferring DokuWiki instead. There is also the ever-popular MediaWiki, if that's your thing.

Backup-wise, I mostly use Backblaze, which is awesome but violates your "free" constraint. If I couldn't use Backblaze I'd just back everything up via a cron job or something to an external hard drive and mirror that to my web server, probably.
> 1 votes

---
Tags: tools
---


# Question
Title: WinAPI window taking 50% of CPU when idle
I'm currently working on a game that creates a window using WindowsAPI. However, at the moment the process is taking up 50% of my CPU. All I am doing is creating the window and looping using the code found below:

```
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    MSG message = {0};
    WNDCLASSEX wcl = {0};

    wcl.cbSize = sizeof(wcl);
    wcl.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wcl.lpfnWndProc = WindowProc;
    wcl.cbClsExtra = 0;
    wcl.cbWndExtra = 0;
    wcl.hInstance = hInstance = hInstance;
    wcl.hIcon = LoadIcon(0, IDI_APPLICATION);
    wcl.hCursor = LoadCursor(0, IDC_ARROW);
    wcl.hbrBackground = 0;
    wcl.lpszMenuName = 0;
    wcl.lpszClassName = "GL2WindowClass";
    wcl.hIconSm = 0;

    if (!RegisterClassEx(&wcl))
        return 0;

    hWnd = CreateAppWindow(wcl, "Application");

    if (hWnd)
    {
        if (Init())
        {
            ShowWindow(hWnd, nShowCmd);
            UpdateWindow(hWnd);

            while (true)
            {
                while (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
                {
                    if (message.message == WM_QUIT)
                        break;

                    TranslateMessage(&message);
                    DispatchMessage(&message);
                }

                if (message.message == WM_QUIT)
                    break;

               if (hasFocus)
            {
                elapsedTime = GetElapsedTimeInSeconds();
                lastEarth += elapsedTime;
                lastUpdate += elapsedTime;
                lastFrame += elapsedTime;
                lastParticle += elapsedTime;

                if(lastUpdate >= (1.0f / 100.0f))
                {
                    Update(lastUpdate);
                    lastUpdate = 0;
                }
                if(lastFrame >= (1.0f / 60.0f))
                {
                    UpdateFrameRate(lastFrame);
                    lastFrame = 0;
                    Render();
                    SwapBuffers(hDC);
                }
                if(lastEarth >= (1.0f / 10.0f))
                {
                    UpdateEarthAnimation();
                    lastEarth = 0;
                }
                if(lastParticle >= (1.0f / 30.0f))
                {
                    particleManager->rightBooster->Update();
                    particleManager->rightBoosterSmoke->Update();
                    particleManager->leftBooster->Update();
                    particleManager->leftBoosterSmoke->Update();

                    particleManager->breakUp->Update();
                    lastParticle = 0;
                }
            }
            else
            {
                WaitMessage();
            }
            }
        }

        Cleanup();
        UnregisterClass(wcl.lpszClassName, hInstance);
    }

    return static_cast<int>(message.wParam);
}

```

So even when I am not drawing anything when the window has focus it still takes up 50%. I don't understand how this is taking up so much system resources.

Am I doing something wrong?

Any help would be much appreciated, thank you!

# Answer
> 5 votes
You have two cores or two processors, right?

When focused, your program executes the loop continuously. It uses all of the available CPU resources given to it by the OS because you have said "I must use all of the available CPU resources given to me by the OS" -- you don't have any statements -- such as a call to Sleep() or using GetMessage() instead of PeekMessage() -- that will block your thread and tell the OS you wouldn't mind being switched out now.

Note that I'm not suggesting Sleep() or GetMessage() are proper solutions, per se, only that using them would cause your apparent CPU usage to drop. It isn't necessarily a problem that your program asks for as big/frequent of a timeslice as you can get from the OS. Games typically do this, for example. As long as you play nice when you're not the foreground app by reducing processing or drawing, et cetera, which it looks like you are doing, you should be fine.

# Answer
> 0 votes
If you don't respond to paint messages, windows will keep spamming your window with paint messages, which probably takes a bit of cpu time. This is my guess. I'm not entirely certain, though.

---
Tags: opengl, windows, game-loop
---


# Question
Title: What can I do to increase the female:male ratio of gamers in an online, casual gaming, community?
Can I make a significant difference by changing the types of games that are available? Are there any generic features that I can add to games, which will help make them more attractive to casual female gamers?

# Answer
I am not a woman gamer, but one thing you should definitely try is removing things which would tend to drive them away. Are there games that use a lot of cleavage or exploitative visuals? Does your advertising or the game copy use gendered language ("are you man enough")? Do your games tend to feature male main characters, with women as props or victims? Are your community features (forums and chat rooms) policed for sexist, antisocial, and homophobic content? All these are things that I often hear discussed as reasons why women are driven away from communities.

Things that you shouldn't do in an attempt to attract women: add lots of pink or games about shopping and fashion. While these games may appeal to some girls and women, they can often come across as pandering or disingenuous. Also, avoid having a ghetto category like "games for girls."
> 14 votes

# Answer
I spend a lot of time playing games and **personally** I don't find myself off-put by male orientated games that use huge breasted victimized ladies and what not, in fact I have no problems with most of the issues Gregory Weir raised. Although I do think the points about community attitude and no pink/games4girls are valuable.

I think as a whole woman are looking for different features, Customization is a huge favourite for example. It's a stereotype because it's true. I like to make my character or gameplay personal to me, that's a huge factor in keeping me interested and coming back for more. It doesn't need to mean i want more pretty coloured wizard hats, i just want to be involved with the role i'm playing in a game. I want to be able to define myself so that i feel that my presence there is worth something.

Another thing is that i like to feel emotionally involved. This is mostly through writing, for example if there is an npc or an instructional character I prefer some thought to have gone into their script so they don't just feel like another game mechanic. Or if a game has a "world" i want to feel that i have some place in it. Alternatively this aspect can be covered by a good community for some people.

It's true i might just be encouraging distinction between men and woman here when the industry is trying to find the happy medium, but i think i'm just being realistic. You can't ignore the fact that what ladies look for is very different, it a tough balance to strike, we don't want to be playing a whole different game from the blokes, we want to be able to play the same game our own way. And we wan't more substance to the game because hack and slash (/other generic gameplay) just can't satisfy us alone like it can with a lot of young men.

**EDIT**

A couple of years down the line, noticed this was up voted and I'm not sure my anecdotal response holds much merit. Some of the points are still valuable if you hadn't already considered them, but you should really take any comment on what girls prefer in games with the knowledge that single opinions might not hold up. Even the loudest consensus might not represent the majority of your potential female users. Empirical studies are probably the best way to research this problem if necessary.
> 15 votes

# Answer
I'm a female gamer. I can't really tell you what you could do to attract me to a game, but I guess you're free to ask me any questions about my gaming habits.

I can tell you why I like particular games or maybe you can kind of gather from the games I play, what attracts me to them.

When it comes to computer games I play, or have played:

* Guild Wars (a loong time ago)
* World of Warcraft (Mipey's right about the vanity pets.)
* Left 4 Dead
* Command & Conquer (pre-EA, again a long time ago.)
* Plants vs Zombies
* The Sims
* Sim City (I liked 3000 the most)
* Diablo 2
* Portal
* TF2
* Fortress Forever
* Zelda (pretty much all of them, but Ocarina's my favorite)

One thing I find really appealing is having a nice balance of male/female playable characters. In a LOT of games, seriously a TON if there is a female character, there's only one. So I mean, guys can pick from a number of avatars and female players get one character to choose from. That's one thing I liked about WoW, even number of male/female characters, however one thing I don't like about WoW is the, "Oh, you're a girl and you play WoW? You must be ugly!" mentality.
> 9 votes

# Answer
More than on language and visuals, it depends on the very nature of your game. Does it encourage aggressive gameplay (think any FPS)? Then you'll attract more males than females. Does it appeal to the caring personality, such as gardening and management games (think Sims)? Then you'll attract more females.

Males tend to be more competitive, females tend to be more collaborative. If you include both gameplay aspects, you'll see more balanced ratio between men and women. An example is World of Warcraft, which is highly competitive environment (think DPS, PvP), however it also has much of leeway for collaboration (think tank, healer, guilds).

You can also consider adding player-owned housing, gardens etc. that feature growth in return for care (find items). Vanity items also are a good way to appeal to the "other" side, such as non-combat pets, collectibles etc.
> 4 votes

# Answer
> Can I make a significant difference by changing the types of games that are available?

Absolutely. Type and setting/story. I'm pretty sure most players of Murder, She Wrote are female. I know for a fact that my 60+ year old mother-in-law, who was quite anti-gaming before, played it through at least twice :)
> 2 votes

---
Tags: community-management
---


title: Where is the time spent?

text:
# Question
Title: Where is the time spent?
Game development is a large process. In your experience, how are the total hours for releasing a game divided over the following major areas. I believe this is useful because few people (none?) are really good at all the areas, so this helps me balance the cost of items I'm not so good at when estimating the complexity of creating a game.

* Modeling and raw asset creation (textures, audio)
* Level design
* Gameplay design
* Programming
* Testing
* Marketing

# Answer
> 8 votes
It depends vastly on the kind of game and the tools you're working with. If you're making a first-person shooter in raw C++, you're going to spend a ton of time on programming. If you're making a 2d MMORPG in an existing game framework for 2d MMORPGs, it's going to be pretty much all asset creation of one kind or another. If you're making a puzzle game in an existing framework, you'll be spending nearly all of it on level design.

There's just no good answer without knowing, at the very least, the genre, scope, and tools involved.

# Answer
> 4 votes
This question really doesn't have an answer, but it's an interesting discussion anyway.

Modeling and raw asset creation (textures, audio)

* this could take literally years, if you're a single person trying to make a make professional quality 3D models for a whole game. On the other hand, many indie games use retro pixel art, 3D primitives or hand drawn graphics, and then you could have all your art done in a matter of days! It's normally more cost effective to purchase royalty free audio from a site like http://www.soundrangers.com than professionally record yourself, although something like Garage Band or Sony Acid is great for music. You can also buy packs of off-the-shelf 3D models for under $100 dollars, but this will make your game a lot more generic and less unique. There are many good sites with free textures though.

Level design

* this depends on how big your game is an how much of the fun comes from puzzles and challenges incorporated into the level design. If you can create a system that is lego-like and doesn't require special programming for each level, you can hand level-design over to other, less technical (ie cheaper!) team members. Some really fun games, like Spelunky, use algorithms to auto-generate levels, and that would certainly save you some time.

Gameplay design

* Gameplay can actually come to together in a matter of hours by just playing around and hacking code. It can even happen by accident sometimes when you find an unexpected behaviour that is more fun than you were actually going for. That said, you want to put a lot of thought it to things like - how does the character interact with terrain, walls, ledges, water etc. It's better to design the game through your code than do too much on paper

Programming

* For indie games it's normally better to use a pre-existing engine to handle the solved problems like collision detection etc

Testing

* Testing playability is really important. For indie games you should be able to get friends and fans to do this for free. At the design agency I worked at we'd get the receptionist, project managers and interns to do testing.

Marketing

* Keeping a blog, twitter account etc is a good idea, but don't let it stop you finishing your game. Buying ads costs money but shouldn't take up any time.

# Answer
> 2 votes
There is a lot of variation based on the genre and scale of the project. On the indie/flash/iPhone side the amount of time spent on programming tends to be a larger percentage of the whole. With big console projects the majority of the time is spent on content development.

# Answer
> 1 votes
Feel free to flame but in my experience:

```
* Modeling and raw asset creation - 30%
* Level design - 10%
* Gameplay design - 10%
* Programming - 45%
* Testing - 10%
* Marketing - 5%

```

This varies largely on the complexity of the project however.

# Answer
> 0 votes
Wow what a question. It really depends so much on the type of game. If you're talking about a very simple iPhone game then artists and audio bods will be twiddling their thumbs before programming in complete. But if you're talking about a big 3D game then art content is by far the biggest part. For a AAA console game there may be a large team of developers in-house, but the art team will be at least twice that number and these days will probably include a huge amount of outsourced content.

If you need a lot of art content try an outsource company like http://creativesintheattic.com there are many others but I've used them and it's been worth it. Unlike some outsource companies they were willing to work on a fairly small number of assets (my budget was low) but they also provide for AAA games so the quality is top notch.

---
Tags: time-management, project-management
---


title: Changing render target within an effect

text:
# Question
Title: Changing render target within an effect
I've got an effect which is a fairly simple two-pass deal- but it involves rendering to a texture in the first pass. Is it possible to change the render target from within an effect? I would definitely appreciate the reduction in code duplication from C++ by being able to do both passes within HLSL.

# Answer
> 1 votes
I am pretty sure you can't do this -- you have to change the render target between passes from the CPU side of things. The list of effect states that can be manipulated by effect files does not include anything regarding the render target.

---
Tags: c++, directx9
---


title: Is a computer science degree worth it?

text:
# Question
Title: Is a computer science degree worth it?
I'm in my last year of high school, and I've been looking at colleges. I'm taking a C++ class at a local community college and I don't feel that it's worth it. I could have learned everything in that class in a week.

This had me thinking, would a CS degree even be worth it? How much can it teach me if I can learn everything on my own? Even if I do need to learn more advanced subjects, many colleges put their material online AND I can buy a book. Will companies hire me if I don't have a CS degree? If I have a portfolio will I stand a chance? What kind of things are needed in the portfolio?

I want to live doing what I love - programming. So I will do it. I'm just not sure that a CS degree will do anything to me. In addition, if there is a benefit to getting a CS degree, what places are the best?

# Answer
As a burned-out, bitter, and cynical programmer with \>10 years in the industry, this would be my advice:

Don't plan on games as a long-term career.

Plan to do it for a few years, get it out of your system. But plan for a more sensible career longer-term, and don't leave it too late to make that change

You might manage 5-10 years in the industry, then you'll realise that there's not much long term future in being made redundant every 1-2 years, and crunching like crazy to buy the higher-ups supercars whilst barely seeing any pay rises, let alone bonuses.

Also, the industry changes at quite a pace. When I was at high school age, it was all about the Amiga, 16-bit consoles, and 2D games. By the time I came out of university, it was all about 3D and Playstations. These days, the 'big games' industry is in a worse state than ever, can't see it lasting many more years as things are. But we have a resurgence in bedroom coding/indie development, and new opportunities in mobile devices and web-based platforms.

Change can be exciting, but generally change means layoffs. Layoffs force salaries down. Changing job means relocating... Most people can't keep doing it for all that long...
> 4 votes

# Answer
I'm going to point you to my answer on the game dev degree vs. computer science degree question: Game Development Degree vs Computer Science Degree

A CS degree is more than just learning how to program. And working with a team making games is a lot more than just programming.
> 7 votes

# Answer
I'll answer it in a game-development context since your title seems to indicate that's where you're going with the question. Would a CS degree be useful for game development programming? Yes. I don't know how much you can teach yourself but if you could teach yourself that well, you'd already know and wouldn't be asking here.

I'm working on a masters degree in computing and video game development (where I work directly with professionals who work in game development) and the experience I got with the traditional CS undergrad classes has been invaluable.

I have a friend who has gotten a number of programming jobs without a college degree but he's the type of person who creates compilers and interpreters for computer languages he creates for fun. Unless you're that hardcore, you'll almost certainly need a degree.
> 2 votes

# Answer
Edsger Dijkstra allegedly said "computer science is no more about computers than astronomy is about telescopes." Often people replace "computers" with "programming," for much the same idea.

An education in computer science will expose you to a wide variety of topics that have nothing to do with programming itself (although programming is often used as a vehicle for communicating and solving those problems) -- topics that have to do with modeling and manipulating information in interesting ways that tend to be very relevant in modern game development (even if it won't seem apparent while you're slogging through the classwork). For example I have leveraged the knowledge I acquired about graph theory in several instances to build automatic layout and diagramming tools, "visual programming" type editors, and unique-coloring algorithms to allow designers to have a holistic view of the the content they produced for a game, et cetera.

You don't *need* a computer science degree to be a game programmer. You could have another degree (or, if you're quite good, no degree at all, but that could be risky in today's job market at least) -- math or physics, for example. You could even get one of those "game school" degrees (but I would not recommend it). It is important that you study what you are interested in, because college will only give you benefits proportional to the effort that you put into it, and you're not likely to do that if you're not invested in your coursework in some fashion.

Certainly studying on your own, outside of school, is important, too -- because most colleges won't be teaching you how their coursework can be applied directly to game development. Plus, building games and little tech demos on your own will help you have a portfolio of interesting work to talk about in your future job interviews. Some interviewers, myself included, are greatly encouraged by a candidate who takes the time to pursue knowledge on his or her own.

As for where you should go... that depends on you as well. You should go to a school that interests you, where you think you'd fit in, where you like the environment, et cetera. You should visit schools if possible. You don't need to go to Brown, MIT or Carnegie Mellon or whatever in order to get a good, solid CS education. In fact, I'm personally a bit skeptical that there is any significant benefit at all to doing so (many such schools are actually more well known for their *graduate* programs, and their undergraduate material may be no better off than anywhere else).
> 2 votes

---
Tags: education, jobs
---


title: Hardcoding C++ shader interop code

text:
# Question
Title: Hardcoding C++ shader interop code
When writing code that interacts with multiple shaders, is it best practice to hard code the use of each effect? I wrote a couple of hard-coded loops and then noticed that I accidentally ended the pass of the wrong shader, and this has me concerned that instead, I should be writing some sort of Shader class that generically executes a shader. Is this the right way to go?

# Answer
> 4 votes
Yes, it would be more scalable in the long run to write a system could wrap and handle what your shaders need for you.

There are several ways to do this, such as having a "Shader" class like you mentioned that inspects the underlying D3D Effect object for semantic annotations that let your wrapper class determine things like which kinds of vertex or texture input are required, begins and ends all the appropriate classes, et cetera.

---
Tags: c++, directx9
---


# Question
Title: Bitmap font rendering, UV generation and vertex placement
I am generating a bitmap, however, I am not sure on how to render the UV's and placement. I had a thread like this once before, but it was too loosely worded as to what I was looking to do.

What I am doing right now is creating a large 1024x1024 image with characters evenly placed every 64 pixels. Here is an example of what I mean. I then save the bitmap X/Y information to a file (which is all multiples of 64).

However, I am not sure how to properly use this information and bitmap to render. This falls into two different categories, UV generation and kerning. Now I believe I know how to do both of these, however, when I attempt to couple them together I will get horrendous results.

Now for the algorithm. I am doing my letter placement with both GetABCWidth and GetKerningPairs. I am using GetABCWidth for the width of the characters, then I am getting the kerning information for adjust the characters.

Does anyone have any suggestions on how I can implement my own bitmap font renderer? I am trying to do this without using external libraries such as angel bitmap tool or freetype. I also want to stick to the way the bitmap font sheet is generated so I can do extra effects in the future.

Rendering Algorithm

```
for(U32 c = 0, vertexID = 0, i = 0; c < numberOfCharacters; ++c, vertexID += 4, i += 6)
{

    ObtainCharInformation(fontName, m_Text[c]);

    letterWidth = (charInfo.A + charInfo.B + charInfo.C) * scale;

    if(c != 0)
    {

        DWORD BytesReq = GetGlyphOutlineW(dc, m_Text[c], GGO_GRAY8_BITMAP, &gm, 0, 0, &mat);
        U8 * glyphImg= new U8[BytesReq];
        DWORD r = GetGlyphOutlineW(dc, m_Text[c], GGO_GRAY8_BITMAP, &gm, BytesReq, glyphImg, &mat);

        for (int k=0; k<nKerningPairs; k++)
        {
            if ((kerningpairs[k].wFirst == previousCharIndex) && (kerningpairs[k].wSecond == m_Text[c])) {
                letterBottomLeftX += (kerningpairs[k].iKernAmount * scale);
                break;
            }
        }

        letterBottomLeftX -= (gm.gmCellIncX * scale);
    }

    SetVertex(letterBottomLeftX, 0.0f, zFight, vertexID);
    SetVertex(letterBottomLeftX, letterHeight, zFight, vertexID + 1);
    SetVertex(letterBottomLeftX + letterWidth, letterHeight, zFight, vertexID + 2);
    SetVertex(letterBottomLeftX + letterWidth, 0.0f, zFight, vertexID + 3);
    zFight -= 0.001f;

    float BottomLeftX = (F32)(charInfo.bitmapXOrigin) / (float)m_BitmapWidth;
    float BottomLeftY = (F32)(charInfo.bitmapYOrigin + charInfo.charBitmapHeight) / (float)m_BitmapWidth;

    float TopLeftX = BottomLeftX;
    float TopLeftY = (F32)(charInfo.bitmapYOrigin) / (float)m_BitmapWidth;

    float TopRightX = (F32)(charInfo.bitmapXOrigin + charInfo.B - charInfo.C) / (float)m_BitmapWidth;
    float TopRightY = TopLeftY;

    float BottomRightX = TopRightX;
    float BottomRightY = BottomLeftY;

    SetTextureCoordinate(TopLeftX, TopLeftY, vertexID + 1);
    SetTextureCoordinate(BottomLeftX, BottomLeftY, vertexID + 0);
    SetTextureCoordinate(BottomRightX, BottomRightY, vertexID + 3);
    SetTextureCoordinate(TopRightX, TopRightY, vertexID + 2);

    /// index setting

    letterBottomLeftX += letterWidth;

    previousCharIndex = m_Text[c];

}

```

# Answer
> 0 votes
Like bluescrn and Jari have suggested, I'd say go with bmfont if you can.

But if you want an example that just draws text, here's a snippet I was toying with some months back. Part are surely borrowed from somewhere (the PNG codec writer), but I have no idea where.

Good luck!

```
#include <Windows.h>
#include <Wingdi.h>
#include <gdiplus.h>
#include <Gdiplusgraphics.h>
using namespace Gdiplus;

extern int MyGenTexture[512*512];
int MyGenTexture[512*512];

int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
   UINT  num = 0;          // number of image encoders
   UINT  size = 0;         // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo = NULL;

   GetImageEncodersSize(&num, &size);
   if(size == 0)
      return -1;  // Failure

   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
   if(pImageCodecInfo == NULL)
      return -1;  // Failure

   GetImageEncoders(num, size, pImageCodecInfo);

   for(UINT j = 0; j < num; ++j)
   {
      if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
      {
         *pClsid = pImageCodecInfo[j].Clsid;
         free(pImageCodecInfo);
         return j;  // Success
      }
   }

   free(pImageCodecInfo);
   return -1;  // Failure
}

extern void MakeTexture();
void MakeTexture() {
    HDC myDC = CreateCompatibleDC(NULL);
    //HBITMAP GenTexture = CreateCompatibleBitmap( Context, 512, 512 );

    BITMAPINFOHEADER myInfoHeader = {
        sizeof(BITMAPINFOHEADER),
        512,
        -512, // Negative, to make it top down //
        1,
        32,
        BI_RGB,
        0, // Size of compressed data //
        4096, // Pixels per meter //
        4096,
        0,
        0
        };

/*  HBITMAP myTexture = CreateDIBitmap(
        myDC,
        &myInfoHeader,
        NULL,
        NULL,
        NULL,
        DIB_RGB_COLORS
        );
*/

    BITMAPINFO myInfo = {
        myInfoHeader,
        0
        };

    int* Data;

    HBITMAP myTexture = CreateDIBSection(
        myDC,
        &myInfo,
        DIB_RGB_COLORS,
        (void**)&Data,
        NULL,
        NULL
        );

    SelectObject( myDC, myTexture );

    GdiplusStartupInput gdiplusStartupInput;
    ULONG_PTR           gdiplusToken;
    // Initialize GDI+.
    GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

    {
        Graphics g( myDC, myTexture );
        SolidBrush brush( Color(255,255,255,255) );
        FontFamily fontFamily( L"Times New Roman" );
        Font font( &fontFamily, 48, FontStyleRegular, UnitPixel );

        for( int idx = 0; idx < 512*512; idx++ ) {
            Data[idx] = 0x00FFFFFF;
        }

        //g.Clear( Color(0,255,255,255) );
        g.DrawString(L"Using \"Technology\", i.e.",-1,&font,PointF(0,20),&brush);
        g.DrawString(L"GDI+, I have created a",-1,&font,PointF(0,70),&brush);
        g.DrawString(L"texture from system",-1,&font,PointF(0,120),&brush);
        g.DrawString(L"installed fonts! That",-1,&font,PointF(0,170),&brush);
        g.DrawString(L"means international",-1,&font,PointF(0,220),&brush);
        g.DrawString(L"characters!",-1,&font,PointF(0,270),&brush);
        g.DrawString(L"",-1,&font,PointF(0,320),&brush);
        g.DrawString(L"      スマイルズ ",-1,&font,PointF(0,370),&brush);
        g.Flush();

        for( int idx = 0; idx < 512*512; idx++ ) {
            MyGenTexture[idx] = Data[idx];
        }

        // Write File //
        Bitmap OutBitmap(myTexture,NULL);

        CLSID encoderClsid;
        GetEncoderClsid(L"image/png", &encoderClsid);
        Status stat = OutBitmap.Save(L"Awesome.png", &encoderClsid, NULL);
    }

    GdiplusShutdown(gdiplusToken);

    DeleteObject( myTexture );
    //DeleteObject(GenTexture);
    DeleteDC(myDC);
}

```

# Answer
> -1 votes
You could always give this a try: http://www.angelcode.com/products/bmfont/

It generates nicely-packed textures of bitmap characters, and an .xml file of all the UV/spacing data. Results are generally very good.

---
Tags: c++, graphics, c#, algorithm, rendering
---


# Question
Title: 2D object-aligned bounding-box intersection test
I have two object-aligned bounding boxes (i.e. not axis aligned, they rotate with the object). I'd like to know if two object-aligned boxes overlap. (*Edit: note - I'm using an axis-aligned bounding box test to quickly discard distant objects, so it doesn't matter if the quad routine is a little slower.*)

My boxes are stored as four x,y points. I've searched around for answers, but I can't make sense of the variable names and algorithms in examples to apply them to my particular case.

Can someone help show me how this would be done, in a clear and simple way? Thanks. (The particular language isn't important, C-style pseudo code is OK.)

# Answer
If you know where to look it is easy. You are looking for oobb. Go here: http://www.realtimerendering.com/intersections.html.
There you find link to this site http://www.geometrictools.com/LibMathematics/Intersection/Intersection.html
and there find correct code. (ctrl+f "Intersection of boxes (2D)")

It uses SAT and contains source codes and article.
> 5 votes

# Answer
The easier way is probably to test each vertex of box B against each side of box A (compute the signed distance). This way you can classify each vertex as "in front" or "behind" the segment.

If all of B's vertexes classify as "in front" of one of A's segments, B and A don't overlap; otherwise, they do.

This is somewhat involved, so you may get some performance gain by doing a circle-circle check first, using the bounding circles of the squares (trivial to compute)
> 2 votes

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


# Question
Title: Sprite sheets with buffer objects and shaders
What is the "best" way to handle sprite sheets with shaders and buffers? In immediate mode it is easy to modify a sprite's texcoords when it is drawn, but I don't know how to do this with modern opengl. Should I store all the texcoords in a buffer and change the pointer for every sprite, or is there a better way?

# Answer
You can always make looong buffer "vertex;texcoord" repeat. And just use indices how you said. It is propably most easy and kinda similar to what you know.

If you want to save some memory. There is pretty neat solution and it is to have one sprite in buffer with unite texcoords and create UVs transformation matrix and send it to your shader and multiply texcoords with it (in vertex shader).

You dont have to create matrices by yourself if you are not fine with that. You can just use regular GL functions and than read matrix with `glGetFloatv`function. Like this:

```
glGetFloatv (GL_MODELVIEW_MATRIX ,&g_TexCoordMat);

```

I created image to describe it better. glTranslate ang glScale can be looked as that they are just moving with the UV space basis.

If you don't know how to send matrix to shader i can share some code with you.

**Edit:** Added picture
(source for spritesheet i used: funorb.com)
> 12 votes

---
Tags: opengl, shaders, spritesheet
---


title: Why is there a lack of games for Linux?

text:
# Question
Title: Why is there a lack of games for Linux?
What is wrong with the Linux/\*nix family for games? What makes the development of games for this platform too slow compared to Windows or even OS X?

# Answer
For game clients, it mostly has to do with culture, leading to difficult monetization strategies.

Servers for multiplayer games, on the other hand, have gotten a lot of traction for linux/nix, it is a very attractive platform for developing server technology.

There is hope that eventual release of Steam for Linux will help change that culture when it comes to clients, and provide developers and publishers a more monetarily viable platform for distributing games.
> 18 votes

# Answer
> What is wrong with the Linux/\*nix family for games?

'Wrong' is a strong word, but I'll list a few things that hold games developers back from working on Linux.

Culture - Linux people tend more to believe software should be free - this isn't conducive to making a profit off selling your software. This may change in the future with online games being 'software as a service' in a sense.

Market share - The market share of Linux on the desktop has always been quite small. Now that the market share has finally crept up from 'negligible' to 'pitifully low' you could make a small argument for targetting that platform - if the previous point wasn't at all true, that is. This has also come a bit too late - the non-console game market is really quite small these days when you exclude MMOs.

Developer support - Microsoft have poured a lot of time and money into DirectX, and more recently into XNA. With one download, you had all the APIs and documentation you needed to make games. Linux has no central body to do this, nor even one single product that could be used instead. SDL doesn't do 3D graphics, OpenGL doesn't do anything but graphics, neither have had a very credible upgrade strategy in recent years, and there are a billion other libraries (many of which can be found on a list I maintain here) you can throw into the mix without any clear leaders. It's just a lot more hassle. On top of that a lot of leading middleware doesn't work on Linux, so instead of tried and tested code with paid support you have to consider using abandoned open source that's never been used in a shipped game.

OS support - Linux can do everything Windows does, but it certainly makes it hard sometimes. Sound support in particular is awful. Video support is awkward due to the legalities around codecs. Distribution of your binaries can be fiddly when you consider the different packaging types you need to support. All these things can be overcome if you know what you're doing, but most Windows developers won't know what they're doing with Linux so they aren't able to smoothly port their product to Linux.
> 32 votes

# Answer
Linux accounts for roughly 1% of total end users accessing the internet (OS Marketshare). It's usage increases significantly when talking about servers, but it's just not a big consumer OS.
> 12 votes

# Answer
There's nothing wrong with the Linux/\*nix family of OSes for game development except for perceived audience. Most devs feel that the effort to create games for Linux won't translate into copies sold of their games, especially in the AAA communities.

Even several companies that just ported even AAA games to linux (didn't even pay the upfront cost of developing the game) have not been able to generate enough sales on that platform to stay afloat.

That said, Linux can be a boon to many indie devs, because there are some Linux zealots will buy a game simply because it comes out on Linux.
> 8 votes

# Answer
Linux gaming is a largely untapped market, in my opinion, especially for indies. If you look at the numbers as reported by Hemisphere Games for Osmos and the numbers reported by Wolfire Games for the Humble Indie Bundle (especially the total revenue for each platform), you can see that Linux users can be pretty eager to support those who support Linux.
> 5 votes

# Answer
One thing i noticed that hasn't been touched on here yet, is the overall hodgepodge of drivers, kernels, and libraries you have to work with on linux. It's gotten better lately (with a few distros making up what i can only guess is the majority of the linux boxes out there), but it still is a mess. For a great example of what i mean, see this post-mortem of the linux Osmos port, specifically the "Didn't Love" section. In short, that article complains about:

* Supporting multiple distrosDEs/WMs/drivers/etc.
* Audio \[my comment: and let's face it, the audio support on linux is pretty atrocious at times\]
* Lack of documentation and consensus (little official documentation, and if you ask in a forum you get as many answers as posts, not to mention outdated thread containing wrong answers)
* Packaging the game
* No OS-level GUI layer for simple dialogs
> 3 votes

# Answer
What do you mean with too slow? I don't think that gamedev for linux is any slower than for other operating systems. If you meant to ask why there are no commercial games developed for linux I'd guess it's mostly because the market is too small. There was a company that started to port commercial windows games to linux but they closed down because they hadn't any success selling those games iirc. Futhermore if you want to develop a game for linux you still need to provide it for windows as well if you want to make enough money, however developing it in such a cross-platform manner is even more costly and the linux market is probably not worth it. So I'd say it's just not cost-effective.
> 2 votes

# Answer
One reason that I think Linux doesn't get as much attention is simply that most people who run Linux can also choose to run Windows via a dual-boot setup to run games. This also effects Mac users as well to some extent, but due to the less technical make up of the userbase (not saying this as a slight to Mac users -- it's more that Linux users tend to be the kind of people who don't mind doing all sorts of arcane technical tasks to get something working), there are less people willing to install Windows on their machine.

Closely related is that anyone who is interested in PC games is probably going to buy a PC with Windows on it. Since they have a Windows machine already, they aren't going to be demanding native Linux or Mac versions.
> 2 votes

# Answer
I also think there's simply power in numbers. There's many more windows users than linux users and thus more output on windows. Also, entry level is a lot lower with visual tools versus command line tools (although that has changed over time). Also a lot of kids got their parent's old PC to tinker with, which statictically was more likely to be a windows PC than a Linux box.
> 2 votes

# Answer
The common game user is not a linux user. So the market is not there and not wise to spend money trying to focus on that market.

I know that id Software try to release a linux client of their games, just because they are awesome and love the platform.
> 1 votes

# Answer
Let's not forget that most commercial game engines is tied to and/or have a toolset squarely rooted on win32/consoles. This is also the reason why so many games still uses BSP for instance. Because they've made a huge investment, they are not going to take a huge risk for a smaller market. Might change in the future, but right now you have to invest a lot of effort to become cross platform.

Since Steam just appeared on the Mac, which is really excellent news, I suspect it will only be a matter of time before it appears on Linux. A Mac is running a unix-like OS, so there shouldn't be too much trouble porting the games over.

At least we can hope. :)
> 1 votes

# Answer
Another major issue you must take into account when developing for linux is how to install your game. There is no standard install mechanism that works without issues across distributions. There are package management systems which make your life easier though not all distros use the same formats. The two most common packaging formats would probably be .deb (used by debian based distros) and .rpm (used by redhat based distros). You can waste a lot of time getting the packaging of your application right for multiple distributions, though if you choose not to supply your game in a distros chosen packaging format you run the risk of alienating their user base.
> 1 votes

# Answer
I wonder if the market is as small as people say. I mean I know several people who use Linux as their day to day OS that keep a partition free for a windows install to play their games. (I do the same) The one and only reason we have windows installed is because of the software developers. If they shift their positions and support Linux then I'm certain the adoption rate would go up. But nothing will change unless somebody takes the leap first (come on valve).
> 0 votes

# Answer
Personally, I solved a lot of Linux's issues by using Wine, but I still had problems finding a standardized installation solution that'd work for everyone.
> -1 votes

---
Tags: windows, linux, platform, operating-system
---


# Question
Title: Implementing camera for 2d side scroller game?
I'm implementing a 2D side scroller for iOS (using C/C++ with OpenGL) (beat'em up style like double dragon/final fight ).

My scenes are composed of one cyclical background image ( the end of the image connects perfectly with the beginning ). This is to produce a cyclical scroll effect.

I was wondering how could I implement a camera that follows my player movement ?

( Resources / Links are greatly appreciated with explanations :) )

# Answer
> 2 votes
Presumably you have a coordinate system for your level, so that you always know where any individual entity in the level is (or, more likely, where those entities are spawned so that you know when they should become active and start engaging the player). You've also got your player entity in there, and that's the one you want your camera to track. The camera itself needs a position in the level, too -- I will assume here that the position of the camera in the world corresponds to the center of the screen, but you could just as easily choose another point of reference.

The simple solution is to always have the player centered in the screen, so the camera's position is always set to the player's position every frame. This tends to be somewhat unpleasant for player's, however. A better solution is to allow the player to move around within the center region of the screen and only scroll when the player character gets near the edge of the screen -- since you know the camera's position and the width of the screen, you can use that to compute two borders. When the player's X coordinate falls outside of the range of one of those borders, adjust the camera's X coordinate appropriately.

To scroll your background, you can do what notabene suggested and simply adjust the UV coordinates of the quad rendering the background (ideally this would be done by setting a shader parameter and doing the offset in the shader, instead of mapping and unmapping the quad's vertex buffer every frame, but you could do either). The important part there is that the addressing mode be set to wrap.

# Answer
> 3 votes
The most easy thing to handle which came to my mind is just to draw fullscreen quad with your background texture. And move UVs in x (so move only U). And set UV border method to repeat.

**edit:** Texture coords are between 0-1. But that doesn't mean that you cannot specify any other values. UV border method says how will gpu handle value beyond 1 and under 0. You can set it to clamp, mirror, repeat. In opengl you can do it this way:

`glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);`

nice article is here: http://www.flipcode.com/archives/Advanced\_OpenGL\_Texture\_Mapping.shtml

---
Tags: c++, opengl, iphone, camera, side-scroller
---


title: Is there an algorithm for a pool game?

text:
# Question
Title: Is there an algorithm for a pool game?
I am looking for algorithm to calculate direction and speed of balls in a pool game. I am sure there has to be some type of open source code for this since pool games are some of the oldest computer games I can remember.

I mean, when one ball hits another, I need a algorithm to calculate direction of both of them. It will depend of exact angle of where they hit each other and on speed.

I want to practice Java coding, so I am looking for java code or package that has this type of code.

# Answer
Whilst basic sphere-sphere collision detection/response is quite simple, doing it accurately enough for a good pool simulation would be more tricky, as you'd have to deal with spin.

Are you aware of the existence of physics engines? Some popular examples are these (and they can do a lot more than just pool ball collisions). Probably a good choice for making a pool game, but not so much for learning Java...

In 2D

Box2D: http://www.box2d.org

Chipmunk: http://code.google.com/p/chipmunk-physics/

In 3D

Bullet: http://bulletphysics.org/

ODE: http://www.ode.org

If you were making a big-budget commercial game:

Havok: http://www.havok.com
> 9 votes

# Answer
You may be interested in the article "Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres" if you choose to go the "roll your own" route. It's not Java-specific, but does discuss some of the algorithms involved for a simple simulation.
> 6 votes

# Answer
For a simple pool game where spin is not modeled the algorithm is quite simple.

1. To check if a collision happens, check if the distance between the balls is smaller than the sum of their radius.
2. Calculate the normal of the impact
3. Calculate the impact force based on the speed difference, normal, impact coefficient and masses
4. Apply the impact force to both balls

In pseudo code this becomes:

```
vector difference = ball2.position - ball1.position
float distance = sqrt(difference)
if (distance < ball1.radius + ball2.radius) {
    vector normal = difference / distance
    //vector velocityDelta = ball2.velocity - ball1.velocity
    vector velocityDelta = ball1.velocity - ball2.velocity

    float dot = dotProduct(velocityDelta, normal)

    if (dot > 0) {
        float coefficient = 0.5
        float impulseStrength = (1 + coefficient) * dot * (1 / ball1.mass + 1 / ball2.mass)
        vector impulse = impulseStrength * normal
        ball1.velocity -= impulse / ball1.mass
        ball2.velocity += impulse / ball2.mass
    }
}

```

You can omit the mass from the algorithm if all balls have same mass and also assume constant radius for all balls for a pool game, but the code will be more useful for you without those simplifications.

The code is based on this tutorial, but I remember that the impulse multiplication was incorrect there.
> 2 votes

---
Tags: java, physics, billiards
---


title: HLSL: Pack 4 values into 32 bit float

text:
# Question
Title: HLSL: Pack 4 values into 32 bit float
I can't find any useful information on packing 4 values into a 32 bit float in HLSL.

Ideally, what I want to be able to do in HLSL is:

```
float4 values = ... // Some values where each component is between 0 and 1.
float packedValues = pack32R(values);
float4 values2 = unpack32R(packedValues);

```

I realize that there will be precision limitations, and performance tradeoffs between different precisions in different methods. I'm just wondering what ideas are out there.

# Answer
> 4 votes
32bit floats have 24 bits of significant precision, so the best precision you're going to get is 6 bits per component.

I haven't tested this, but basically all you need is:

```
// C side, params in 0..63 ints
#define PACKI(a,b,c,d) ((a) << 18) | ((b) << 12) | ((c) << 6) | (d)
// C side, params in 0..1 floats
#define PACKF(a,b,c,d) \
 ((int)floor((a)*63) << 18) | \
 ((int)floor((b)*63) <<  12) | \
 ((int)floor((c)*63) <<   6) | \
 ((int)floor((d)*63))

// GLSL side
vec4 unpack(float i)
{
   return mod(vec4(i / 262144.0, i / 4096.0, i / 64.0, i), 64.0);
}

```

---
Tags: hlsl, shadermodel3
---