# Question
Title: Models from 3ds max lose their transformations when input into XNA
I am making models in 3ds max. However when I export them to .fbx format and then input them into XNA, they lose their scaling. It is most likely something to do with not using the transforms from the model correctly.

Is the following code correct using XNA 3.0?

```
Matrix[] transforms = new Matrix[playerModel.Bones.Count];
playerModel.CopyAbsoluteBoneTransformsTo(transforms);

// Draw the model.
foreach (ModelMesh mesh in playerModel.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.World =
            transforms[mesh.ParentBone.Index] *
            Matrix.CreateScale(Vector3.One*20) *
            Matrix.CreateTranslation(position);

        effect.View = view;
        effect.Projection = projection;
    }
    mesh.Draw();
}

```

It also seems to work if I export it in .obj format, which is probably vertex only format, then import it back into 3ds max and then export it to .fbx for XNA.

Here's an image reference in case you don't understand what I am saying. The left is in XNA and the right in 3ds max.

# Answer
The best solution i found was to reset the xform, In 3ds max

1. In the utilities panel goto "Reset Xform"
2. Then with the model selected click "Reset Selected"

from what i understand reset xform places the mdels transformations in a separate modifier called "xform"

However i still dont understand why xna was unable to just get the transformations from the model
> 0 votes

# Answer
When exporting, the model data is exported and the transformation data is also exported, they are not baked into each other.

I've seen many folks forget to take into account the transformation data when loading their models into Xna.

If you are properly using a transform array populated by the `CopyAbsoluteBoneTransformsTo` method then you are using the transformation data (including scale), but not going about it properly would result in a problem you are describing.

If you think this may be a clue, then post your code and we can see if you are coding it properly.
> 0 votes

---
Tags: xna, 3dsmax
---


# Question
Title: How do I get bullets to move in the direction of the mouse's position?
> **Possible Duplicate:**
> Shoot a bullet towards cursor - top down 2d

I'm creating a 2D top down shooter, and I want to get the bullets to go in the direction of the mouse. Not sure of the logic that goes into it.

# Answer
You could use trigonometry like here: 2D Magnet-like repelling behavior

But the very simplest approach is:

```
//init:
CONSTANT_FACTOR = .001;

//every frame:
dx = mouse.x - bullet.x;
dy = mouse.y - bullet.y;

bullet.vx = dx * CONSTANT_FACTOR;
bullet.vy = dy * CONSTANT_FACTOR;

bullet.x += bullet.vx;
bullet.y += bullet.vy;

```
> 0 votes

---
Tags: xna, rotation
---


# Question
Title: Predicting enemy position in order to have an object lead its target
In my 2D game I have AI turrets that should assist the player by automatically firing towards enemies. I would like to make them fire intelligently and lead their target instead of just targeting an enemy's current position. So, given the (always constant) velocity and position vector of both the enemy and the turret's projectile, how can I find a vector that represents the actual position the turret must target in order for the projectile to intersect (and hit) the enemy?

Any links to articles that describe the math, algorithms, etc. would be appreciated!

# Answer
This question on GameDev, and this question on StackOverflow should provide you with the answer you're looking for. :)
> 5 votes

# Answer
~~I'm not gonna give you an answer I'm sure is useful or even correct, but here it goes:~~
After playing with mathematica a little more (check the end of the answer for notebook /published notebook) files, this solution appears to be correct, even thought it might not be the best one in terms of efficiency.

I wrote this in mathematica which corresponds to your problem. Basically it solves the equations / inequalities in order to the OA variable which is what we need to find out. The output is gonna give us the possible solutions that OA can have and the conditions that need to verify for each solution to be valid:

```
Reduce[{BPx, BPy} + t*{BVx, BVy} == {OPx, OPy} + t*OV*{Cos[OA], Sin[OA]} && t != 0 && OV != 0, {OA}]

```
* {BPx,BPy} is blue's current position
* {BVx,BVy} is blue's velocity vector
* {OPx,OPy} is orange's bullet position
* OV is the norm of orange's bullet velocity vector (total speed)
* OA is orange's bullet angle (angle of velocity vector)
* t is the time needed for the bullet to hit blue

I tried putting t\>0 && OV\>0 in the conditions but mathematica would take forever so I just used t!= 0 && OV != 0. So the solutions I'm gonna give here just work when blue is not in the exact same position as orange and when the orange's bullet really moves (instead of staying still)

The output is gigantic: http://freetexthost.com/xzhhpr5e2w

However if we extract the OA == _ parts, we get this:

http://freetexthost.com/iyrhqoymfo

Those are the values OA can have (each one requiring different conditions to be valid).

With some further analysis taking out the solutions that require OV to be negative which we don't want, I got this:

http://freetexthost.com/iy4wxepeb6

So these are the possible solutions to the problem, each one requiring different conditions to be valid. In order for a certain angle OA to be a valid solution, the following conditions must meet:

```
Reduce[{BPx, BPy} + t*{BVx, BVy} == {OPx, OPy} + t*OV*{Cos[OA], Sin[OA]} && t != 0 && OV != 0, {t}]

```

Output:

```
(BVy - OV Sin[OA] != 0 && BPx == (BPy BVx + BVy OPx - BVx OPy - BPy OV Cos[OA] + OPy OV Cos[OA] - OPx OV Sin[OA])/(BVy - OV Sin[OA]) && t == (-BPy + OPy)/(BVy - OV Sin[OA]) &&  BPy OV - OPy OV != 0) ||
(BVy == OV Sin[OA] && BPy == OPy && BVx - OV Cos[OA] != 0 && t == (-BPx + OPx)/(BVx - OV Cos[OA]) && BPx OV - OPx OV != 0) ||
(BVy == OV Sin[OA] && BVx == OV Cos[OA] && BPy == OPy && BPx == OPx && OV t != 0)

```

So consider only the solutions where that verifies (you don't need to verify the t==\_ parts. They are the ones that give you the time needed for the bullet to hit the vehicle if the other conditions are valid. Notice that if t results in a negative value, you cannot consider a given OA as a valid solution, even if it verifies the other conditions (this is because we used t!= 0 instead of t\>0 in reduce)).

It also might be a good idea to ask in https://math.stackexchange.com/ about this.

**Edit**

I've grown some interest for this question, so I've created a commented notebook with a graphical demonstration of everything I explained . Download it here:

http://www.2shared.com/file/pXhYyhN1/towerBullets.html
Or here: http://www.2shared.com/file/W01g4sST/towerBullets.html

(this is the published version, and you only need the mathematica player -which is free- to see it. If you don't have mathematica this is the way to go)

Screenshot:
> 3 votes

---
Tags: algorithm, ai, aiming
---


# Question
Title: How do I know if I've gone too far with processing things in a game?
A common programming quote I see every day is:

> Premature optimization is the root of all evil!

I admit I'm one of those guys that like to do premature optimization in a pretty obssessive manner but that's probably because I'm not aware how powerful modern processors are. I can think of lots of sollutions for a problem, but all of them are tough on the memory side, and I keep thinking "This will hurt me more in the future when I'll have to re-do it because it's bad performance-wise."

How do you know when the code you are thinking of is going too far and is not a case of premature optimization? How much can your game handle at a time before performance becomes a problem?

# Answer
Simple, when it runs slowly. (Or consumes a lot of memory.)

Premature Optimization is optimizing things without reason, e.g. before you run into any problems because of the performance. For example when you optimize your path-finding algorithm just because it can be faster, not because you noticed that your path-finding takes up a too large part of your CPU time.

That's just bad because optimization is a trade off, when you code you should code for maximum readability and maintainability, not for tiny performance benefits. Highly optimized code is usually hard to understand and thus hard to maintain.

Make a goal what kind of hardware you want to support and test your game on that hardware. Does it run at full speed? Then it's okay, keep on coding. If not profile it, check what parts are making it slow and optimize those parts.
> 7 votes

# Answer
Think of optimization on your designing stage, when you consider if the general algorithm (it's outline) is fast enough for your game, or maybe it may be too slow for a smooth FPS. If you're not sure, do a quick, dirty test (if possible).

Then, forget about optimizing on first stage of programming. Optimizing here is not necessarily bad, but may decrease readability of the code or prove to be useless if at the end of this stage your prototype will show the design is wrong.

After making a working prototype, try to isolate parts of code like functions or classes and test them with unit tests.

Only then optimize final, tested (and working) functions/classes, and then test them again using same unit tests.

You will need a common sense to decide which function is CPU heavy (you can also measure it, but usually it should be obvious). Spend most time optimizing code that takes most time to execute (counting it's repetition).
> 2 votes

# Answer
When choosing whether or not to spend time on optimizing something, the most important factor is how often this code is executed:

* Occasionally, maybe once every few minutes: Why bother?
* Once per frame: Might be worth it.
* Once per frame and game object: Should be optimized
* For every pixel painted: Stop cutting corners - you must make that faster!

Special consideration should be taken for code which is executed in situations which are especially important for the user experience. Mainly loading times and saving times.
> 2 votes

---
Tags: performance
---


# Question
Title: How do I apply a force using the object direction and speed?
I have a 3D object moving and I need to be able to apply forces to it such as gravity. In 2D, I would simply store its movement in dx and dy, but since this is in 3D, I am using a `Vector3D direction` and a `float speed`. How can I determine how much to rotate the direction and change the speed when by using something like `applyForce(Vector3D force)`?

# Answer
> 1 votes
There's a problem with the information you have. Speed (or velocity), is *not* a force! You need to have an acceleration value and a mass value if you want to apply a force.

Remember that `F = MA`. Or mass times acceleration. If this is the force of gravity, you use the mass of the object times gravity (roughly 9.8 m/s). If it's some kind of rocket or walking force you need to decide an appropriate force to use.

You may find that you just want to use the mass of the object in all cases, that's fine, and it simplifies things. Then you can simply set your acceleration appropriately to get the kind of forces you want.

Whatever mass\*acceleration you use: Take your direction, normalize it, scale it by the acceleration. That will give you an acceleration in the direction of travel. Then multiply it by the mass. Finally apply it as a force to your object.

# Answer
> 0 votes
Just a simple idea for your reference. The force in 3D space is also a 3D vector, so that's all about 3D vector arithmetic, suppose you have a model with a velocity of V and mass of m, and you want to apply a force F on it, use the second law of Newton, then it is something as below

```
Vector3 a = F / m;
V' = V + at;

```

where a is the acceleration, that's also a 3D vector. V' is the new velocity when applying the force.

---
Tags: 3d, mathematics, physics
---


# Question
Title: Whats the potential for actionscript flash?
Is flash programming a tool for beginners? if i mastered flash programming,can i do full option, 2d games or 3d games , what are the limitation for flash if not can you advice me about other tools

# Answer
Potential of Flash is very high.

* FlasCC technology is yet another step bringing the performance closer to C++: http://gaming.adobe.com/technologies/flascc/
* There are a lot of tutorials about making games in Actionscript 3, targeted at beginners. This makes the language a good choice to learn programming with an approachable learning curve. So an answer to one of your question is: *yes, Flash is a tool for beginners* \- but not only for them.
* There is a dynamic, living market for flash games. It's not for ambitious projects, rather for games done in a month. You get money for sponsoring, about a thousand dollars for a simple game (but with nice graphics).
* Flash, by some sources, has up to 99% market penetration (at least for PCs and Macs). If you want to make a browser game, you should consider Flash seriously.
* Flash is cross-browser compatible. There are limited functionalities that don't work same everywhere, like native mouse cursors, but they usually are not a problem nor a surprise to the developer.
* Flash has GPU acceleration support now. It lets you create both fast (some will disagree) 3D and 2D games (using Starling).

However, as Philipp said in the comment, Adobe Flash is unsafe. I personally don't believe HTML 5 will become as cross-browser compatible as Flash anytime soon, but that's just my opinion. I just wrote about the potential of it, and in the context of Flash in future, I'll add one more thing:

* Flash is weakly supported on smartphone operating systems and probably will be supported even less in future (and surprisingly that's Adobe's, not Microsoft's or Apple's decision)
> 0 votes

---
Tags: actionscript-3
---


# Question
Title: Do I lose/gain performance for discarding pixels even if I don't use depth testing?
When I first searched for discard instruction, I've found experts saying using discard will result in performance drain. They said discarding pixels will break GPU's ability to use zBuffer properly because GPU have to first run Fragment shader for both objects to check if the one nearer to camera is discarded or not. For a 2D game I'm currently working on, I've disabled both depth-test and depth-write. I'm drawing all objects sorted by their depth and that's all, no need for GPU to do fancy things. now I'm wondering is it still bad if I discard pixels in my fragment shader?

# Answer
Graphics hardware can perform early depth-based culling of fragments before computing their color value (in other words, before running your fragment shader). Consequently, if you utilize any features that would affect that, such as `discard`, alpha-testing, or manipulating `gl_FragDepth` the hardware's ability to do that optimization will be compromised since the true depth of the fragment cannot be assumed and the full shader must be run.

Whether or not the use of any of those compromising features has a net observable performance impact depends on the situation, though. The early-z optimization can improve performance if you have very expensive fragment shaders, for example, but if the cost of your pipeline is in the vertex shader (or elsewhere) it won't benefit you as much, and consequently you may see little or no performance degradation by using `discard`.

Disabling the depth test entirely via the API should prevent the optimization from running as well, since it could result in incorrectly-rendered scenes. In your case, then, it shouldn't matter that you use `discard`.

Recent hardware can force the tests (including early stencil tests) using `layout(early_fragment_tests)` -- there is more information (and caveats) on this on the page I linked in the beginning of the answer.
> 20 votes

# Answer
As always for performance questions the most accurate answer is to try it out on your target hardware and measure what happens.

In your case it's probably not a bad thing to do. In fact there's a chance it will help performance by saving on memory bandwidth. It will also add shader instructions though, so it's not always a performance benefit.

Even when using the depth buffer the performance hit isn't always very significant, if you're careful with the order you draw things in.

There's a blog post at https://fgiesen.wordpress.com/2011/07/08/a-trip-through-the-graphics-pipeline-2011-part-7/ which describes in some detail how early depth testing might work in hardware, and what limitations there might be.
> 3 votes

---
Tags: opengl, shaders, fragment-shader
---


# Question
Title: How do I make my rain effect look more like rain and less like snowfall?
I am making a game in that game I want a rain effect. I am little bit far from this right now. I am creating the rain effect like below:

```
particleSystem.addParticleInitializer(new ColorInitializer(1, 1, 1));
particleSystem.addParticleInitializer(new AlphaInitializer(0));
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(2, 2, 20, 10));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 30.0f));

particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 150));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 1, 1f, 1, 1, 1, 3));
particleSystem.addParticleModifier(new ColorModifier(1, 1, 1f, 1, 1, 1, 1, 6));
particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 3));
particleSystem.addParticleModifier(new AlphaModifier(1, 0, 1, 125));
particleSystem.addParticleModifier(new ExpireModifier(50, 50));

scene.attachChild(particleSystem);

```

But it looks like snowfall! What changes can I do for it to look more like rain?

**EDIT** Here is a screenshot:

# Answer
> 13 votes
Fundamentally, it looks like snow because the particles are round and they don't convey motion in any way. Rain drops are typically seen as elongated droplets, even to the point at which they are lines rather than particles. Think of a scene where you are looking out of a window at a rainstorm: you're not seeing individual drops suspended in the air, you're seeing the streak of the path they follow.

You could try stretching the particles out along one axis, but I think you're not going to be able to get a rain-like effect with particles like these.

# Answer
> 4 votes
Also, aside from what MrCranky said, rain does not really have a color, it more just deforms the world around it, so to get accurate rain you really need to be using shaders. That said, you can fake it using long streaks (like what MrCranky said) that are all in line with eachother

# Answer
> 3 votes
Snow "Flutters like a Feather" and Rain "Falls with a Flop"

Simple solution may simply be to increase the gravity so rain drops falls faster and less "snow like"

Making snow versus rain has the following characteristics

* Snow is basically a solid round thing that doesn't deform
* Snow has air resistance / drag so it falls slowly and gracefully with a relatively low maximum velocity
* Snow is easily affected by air turbulence (example, a wind affector) and zigs and zags as it descends ... and event ascends for that realistic feel of a passing breeze

Rain is pretty much the opposite of the above Snow

* Rain deforms as it falls
    + easiest visual change is to stretch the rain drop sprite based on the speed of the raindrop
    + this gives the impression of motion and speed
* Rain is less affected by wind or air resistence
    + a strong wind affector can nudge the path of descent but only mildly (and really only worth accounting for this if more realism is the goal)

So ...

* As the others suggest, use a sprite sheet to animate the drops as they fall
    + sprite sheet of event two sub-sprites is useful ... example: "drop" and "splash"
* Stretch the texture to give motion
    + scaled relative to a min/max velocity range (eg, normalize 0..1 and scale "drop" accordingly when you paint the texture)
* stronger gravity
    + potentially "substantially" more than your environment's normal gravity to make rain have a good "look and feel"

# Answer
> 1 votes
You're only going to be able to get so far with just changing the graphics. I'd personally start with long blue rectangles and stylize it from there. Look at how Minecraft does raindrops.

What's really going to make it feel like rain is the sound you use. Find a free rain ambient track somewhere on the internet and loop it. As long as there are enough particles and they're moving fast enough downwards your mind will make the connection to rain.

---
Tags: android, box2d, andengine
---


title: TGA loader: reverse y-axis

text:
# Question
Title: TGA loader: reverse y-axis
I've written a TGA image loader in Java which is working perfectly for files created with GIMP as long as they are saved with the option `origin` set to `Top Left` (actually TGA files are meant to be stored upside down - `Bottom Left` in GIMP). My problem is that I want my image loader to be capable of reading all different kinds of TGA, so my question is: How do I flip the image upside down?

Note that I store all image data inside a one-dimensional byte array, because OpenGL (`glTexImage2D` to be specific) requires it that way.

# Answer
If you know the size of the image, then you can write a converter which takes the byte array and the dimensions and just returns a rearranged array. The basic idea is that you need to take each row of pixels and swap them with the row mirrored across the plane that you're flipping on. Pseudo-code would look something like this:

```
in: bArray, width, height
out: flipArray
currentChunkIndex = 0
flipArray = allocate byte array of size width*height
for each chunk of bArray from currentChunkIndex to (width*height - width) spanning width bytes:
    copy chunk opposite to plane of reflection into flipArray
    for a vertical flip:
    take chunk of bArray starting at index ((width*height) - ((currentChunkIndex+1)*width)) and spanning width bytes,
    and copy it into flipArray at index currentChunkIndex spanning width bytes
    currentChunkIndex += width

```

Happy coding!
> 0 votes

---
Tags: opengl, textures
---


title: State machine interpreters

text:
# Question
Title: State machine interpreters
I wrote my own state machine tool in C and at this point I'm faced with two choices for specifying state machines.

1. Crafting a little language and writing a interpreter.
2. Writing a compiler for that language.

I know the advantages/disadvantages of each. I'd like to know what choices game programmers have made for their games. If you've used a state machine in your game in any form, I'd be interested in knowing how you did it.

# Answer
> 2 votes
I've always done it with function pointers and ints or enums for states. Granted, the state machines themselves are written in native code. Why do you want to make a language to specify your state machines?

---
Tags: ai, c, fsm
---


title: Draw Cards and Eliminate Cards Problem

text:
# Question
Title: Draw Cards and Eliminate Cards Problem
I am having a problem in this question. I want a system inside a game wherein the player draws 2 cards randomly, and the enemy draws 2 cards randomly. Then, what the program does is to print out to the console the cards the player draw and the enemy's. The cards should not conflict and must not be the same. Then lastly, the program prints out the card that was not drawn by both the player and the enemy. Here's how I did it but it was lengthy and full of errors:

```
import java.util.Random;
public class Draw {

    public static Random random = new Random();
    public static String cards[] = {"Hall", "Kitchen", "Billiard", "Study", "Pool"};
    public static int playercounter;
    public static int enemycounter;
    public static String playercardA = null;
    public static String playercardB = null;
    public static String enemycardA = null;
    public static String enemycardB = null;
    public String lastcard = null;

    public static void playercardAdraw() {
        playercounter = random.nextInt(5);
        playercardA = cards[playercounter];
    }

    public static void playercardBdraw() {
        playercounter=random.nextInt(5);
        playercardB= cards[playercounter];
            if (playercardB==playercardA || playercardB == enemycardA || playercardB == enemycardB) {
                return;
            }
    }

    public static void enemycardAdraw () {
        enemycounter = random.nextInt(5);
        enemycardA=cards[enemycounter];
            if (enemycardA == playercardA || enemycardA == playercardB) {
                return;
            }

    }

    public static void enemycardBdraw () {
        enemycounter = random.nextInt(5);
        enemycardB=cards[enemycounter];
            if (enemycardB == playercardA || enemycardB == playercardB || enemycardB == enemycardA) {
                return;
            }
    }

    public static void main (String args []) {

        System.out.println("Starting to draw...");
        System.out.println("Player's Turn: ");
            playercardAdraw();
        System.out.println("Player's first card: " + playercardA);
            playercardBdraw();
        System.out.println("Player's second card: " + playercardB);
        System.out.println("Enemy's Turn: ");
            enemycardAdraw();
        System.out.println("Enemy's first card: " + enemycardA);
        enemycardBdraw();
        System.out.println("Enemy's Second card: " + enemycardB);
    }

}

```

# Answer
make a deck class like:

```
import java.util.*;
class Deck {
    Deck() {
        Collections.shuffle(c);
    }
    String draw() {
        String s=c.get(0);
        c.remove(s);
        return s;
    }
    final List<String> c=new ArrayList<String>(Arrays.asList(cards));
    static String cards[]={"Hall","Kitchen","Billiard","Study","Pool"};
}
public class Gd40356 {
    static void run() {
        Deck deck=new Deck();
        System.out.print("drawing: ");
        for(int i=0;i<deck.cards.length;i++)
            System.out.print(deck.draw()+' ');
        System.out.println();
    }
    public static void main(String[] args) {
        run();
        run();
    }
}

```
> 2 votes

---
Tags: java
---


# Question
Title: Color sprite tint with opacity in MonoGame/XNA
In MonoGame I am using SpriteBatch to draw sprites. I want to create a semi transparent overlay that would 'tint' the sprite with a given color. `SpriteBatch.Draw` accepts `Color` parameter that allows to specify the tint, however the alpha channel seems to make the whole sprite transparent (not the tint only).

To address the problem i am overlaying my sprites with another white, semitransparent sprite tinted to a given color. It works as expected, but I am not sure if that is the correct (and most optimal) approach.

Can you suggest better/faster technique?

# Answer
Don't use a color with alpha in the `SpriteBatch.Draw(...Color)`. Your sprite's transparent parts will stay that way, and their opaque parts will be tinted.
> 1 votes

# Answer
"Color.Green the tint is too strong, i would like it to be Color.Green with 30% opacity."

I think you mean **saturation**, not opacity. Here you go:

```
Color desaturatedGreen = Color.Lerp(Color.White, Color.Green, 0.3f);

```
> 1 votes

---
Tags: xna, monogame
---


# Question
Title: How can I achieve this lighting with OpenGL?
I'm currently trying to implement a type of "smooth" lighting. How can I achieve lighting which looks like this:

http://dl.dropbox.com/u/1668516/concept/warp3.png

Using OpenGl. I've attempted to use blending modes and have come very close to making it work but it came out like this: https://pbs.twimg.com/media/A1071viCEAAlFmJ.png

Edit: The technique usedis drawing the lighting image (a white gradient) then drawing all my images using the blending effect glBlendFunc(GL\_DIST\_COLOR,GL\_ZERO) however the images come out slightly transparent as shown previously I also have no control of how dark the black background is.

and I also wasn't able to change the alpha of the black background which I want to be able to do.

Could I get a few pointers in the right direction?

# Answer
> 1 votes
The problem with using glBlendFunc(GL\_DIST\_COLOR,GL\_ZERO) multiple times is that you'll only be able to take away light, not add more light to the scene - which will be a problem as soon as two or more light overlap. You can fix this problem by rendering all the lights additively to an offscreen buffer and then drawing the whole thing at once after finishing the rest of the scene.

To create and maintain an offscreen buffer, you can use an OpenGL Framebuffer Object as described here: http://www.opengl.org/wiki/Framebuffer\_Object. You can essentially draw on it the same way you can draw to the backbuffer / screen. For accumulating all the lights there, you can use a simple additive blending mode:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE)

```

which will also allow you to use the alpha channel of the light.

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


# Question
Title: Why distant objects are being drawn in front of close objects?
I am rendering two cubes in the space using **XNA 4.0** and the layering of objects only works from certain angles.

Here is what I see from the front angle (everything ok)

Here is what I see from behind

This is my draw method. Cubes are drawn by **serverManager** and **serverManager1**

```
        protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        switch (_gameStateFSM.State)
        {
            case GameFSMState.GameStateFSM.INTROSCREEN:
                spriteBatch.Begin();
                introscreen.Draw(spriteBatch);
                spriteBatch.End();
                break;
            case GameFSMState.GameStateFSM.GAME:
                spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

                // Text
                screenMessagesManager.Draw(spriteBatch, firstPersonCamera.cameraPosition, fpsHelper.framesPerSecond);

                // Camera
                firstPersonCamera.Draw();

                // Servers
                serverManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix);
                serverManager1.Draw(GraphicsDevice, firstPersonCamera.viewMatrix, firstPersonCamera.projMatrix);

                // Room
                //roomManager.Draw(GraphicsDevice, firstPersonCamera.viewMatrix);

                spriteBatch.End();

                break;
            case GameFSMState.GameStateFSM.EXITGAME:
                break;
            default:
                break;
        }

        base.Draw(gameTime);
        fpsHelper.IncrementFrameCounter();
    }

```

**serverManager** and **serverManager1** are instances of the same class **ServerManager** that draws a cube. The draw method for **ServerManager** is:

```
        public void Draw(GraphicsDevice graphicsDevice, Matrix viewMatrix, Matrix projectionMatrix)
    {
        cubeEffect.World = Matrix.CreateTranslation(modelPosition); // Set the World matrix which defines the position of the cube
        cubeEffect.View = viewMatrix; // Set the View matrix which defines the camera and what it's looking at
        cubeEffect.Projection = projectionMatrix;

        // Enable textures on the Cube Effect. this is necessary to texture the model
        cubeEffect.TextureEnabled = true;
        cubeEffect.Texture = cubeTexture;
        // Enable some pretty lights
        cubeEffect.EnableDefaultLighting();
        // apply the effect and render the cube
        foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            cubeToDraw.RenderToDevice(graphicsDevice);
        }

    }

```

Obviously there is something I am doing wrong. Any hint of where to look? (Maybe z-buffer or occlusion tests?)

# Answer
I found the answer in a related question

The problem was my depth buffer. As I was using a spritebuffer in my main draw

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

```

Some **GraphicsDevice** properties were incorrect. **BlendState** value was AlphaBlend and **DepthStencilState** was none.

In order to fix this only have to add two lines at the beginning of ServerManager draw method:

```
        graphicsDevice.BlendState = BlendState.Opaque;
        graphicsDevice.DepthStencilState = DepthStencilState.Default;

```

Useful link: http://blogs.msdn.com/b/shawnhar/archive/2010/06/18/spritebatch-and-renderstates-in-xna-game-studio-4-0.aspx
> 5 votes

---
Tags: xna-4.0, depth-buffer
---


title: Alternative ways to construct maps

text:
# Question
Title: Alternative ways to construct maps
I've searched around and it seems like most people are using tile-based map systems.
I suppose, this question is more theoretical than practical (I am not very concerned about memory or performance speed), but I want to know: what other ways can a map be created in a game?
A map being a graphic representation of terrain that can be navigated, has entrances and exits, and boundaries (no-go zones).

Besides using text files to store and arrays to load tile data, one idea I had, was to store a map entirely as a graphic file and use queries on the pixel colour to determine boundaries (i.e. you can only move in a certain direction if the way is bright enough in that direction).

What other creative map systems are out there?

# Answer
> 2 votes
Well, Theoretically speaking, I believe there are three main ways of creating a map: 1. Graphs (which include the tile system); 2. continuous (bouncing box) system and 3. mixture of both.

1. The graphs approach consists in telling each identity which are its possible movements. It implies that every identity as a position on a graph, and can only move to certain positions: e.g. in a square tile system, each identity can only move to up/down/left/right (and diagonals in some cases), which is basically to say that each tile has a set of links connecting it to other tiles. Forbidden places are set by not linking that node.
2. On the other hand, the continuous approach, basically the identity can move freely everywhere, subject to the constraints defined by the bouncing boxes of other identities. For instance, the map can be a set of vertices that define a smooth surface, and when the identity moves trough the surface, it is repositioned on top of it, according to the maps height and identity height.
3. Finally, probably the most used now-a-days is a mix: a graph system to define your tile system and on each tile, you use a continuous approach. Only the tile where the identity is is loaded (and possible close tiles).

# Answer
> 1 votes
Instead of using tilemaps you can use general objects transformations. Like: house01 x:151 y:150 angle:30. Also you can generate your map on the fly.

In storing map as bitmap you use 32bits per pixel for example, and in the simpliest tilemap only 8bits(ASCII char). And using bitmap for map generation it's just a way for storing data. Anyway your engine will interpret data as required, so your idea is right about save/load tilemap.

---
Tags: maps
---


# Question
Title: Unity3d: Box collider attached to animated FBX models through scripts at run-time have wrong dimension
I have several scripts attached to static and non static models of my scene. All models are instantiated at run-time (and must be instantiated at run-time because I'm procedural building the scene).

I'd like to add a `BoxCollider` or `SphereCollider` to my `FBX` models at runtime.

With non animated models it works simply requiring `BoxCollider` component from the script attached to my `GameObject`. `BoxCollider` is created of the right dimension. Something like:

```
[RequireComponent(typeof(BoxCollider))]
public class AScript: MonoBehavior
{

}

```

If I do the same thing with animated models, `BoxCollider` are created of the wrong dimension. For example if attach the script above to penelopeFBX model of the standard asset, `BoxCollider` is created smaller than the mesh itself.

How can I solve this?

# Answer
> 1 votes
Have you tried using Bounds to generate the box collider? You use something like this in runtime:

```
   Bounds mapBounds = new Bounds (transform.position, Vector3.one);
      foreach(Transform child in this.transform) {
        mapBounds.Encapsulate(child.gameObject.renderer.bounds);
   }

```

And then Add a BoxCollider and adjust according to those bounds.

---
Tags: unity, bounding-boxes, bounding-spheres
---


title: Vector transform equation explanation

text:
# Question
Title: Vector transform equation explanation
I'm trying to understand the maths of moving points in a 3d space by making a game written in `C#`.

I'm looking at this wolfire blog series which explains some basic 3d maths. I've read the first two parts but am stuck on the 3rd. I know it's all really rudimentary stuff but I find Googling for help with equations really hard.

The one I'm struggling with is:

`0*(0.66,0.75) + 2*(-0.75, 0.66) = (-1.5, 1.3)`

How can anything multiplied by 0 not be 0?

So my question is how does this look in code:

`x(a,b) + y(c,d)`

I know it's basic stuff but I just can't see it.

# Answer
> 0 votes
It *is* zero. 2\*0.75 == -1.5 and 2\*0.66 == (approximately) 1.3.

---
Tags: 3d, mathematics, linear-algebra
---


# Question
Title: Which should be faster: 10 flat shaded polygons or 2 with a transparent texture
I have particle system, and I want to the individual particles to take the shape of a star. Which should be faster: Drawing the 10 polygons using a flat shader, or 2 polygons (a square) with a partially transparent texture?

# Answer
> 3 votes
10 flat shaded polygons is pretty much guaranteed to be faster than the 2 transparent textures from a GPU pov. Especially true when you don't have unified shader architecture, as you'll almost always be bottlenecked by pixel shader throughput for particle systems. Unless you're doing anything fancy, your vertex shader in this case is likely fewer cycles than a single pixel, and that doesn't even account for the alpha blend.

# Answer
> 4 votes
Two polygons with a texture is faster.

Why?

Because it is the typical way to do things. If you're working in 2D then you can just use `SpriteBatch`. And for 3D, here is a sample that you could reuse (one of many you could find online). By reusing this existing method and perhaps code, you will save yourself a lot of time researching, designing, and implementing an alternative system.

You'll also be saving your artists time. Making a texture is much easier than making a model, even a simple one.

*... oh you meant runtime performance ...*

# Answer
> 0 votes
I'm just going to chime in with my POV on this.

As you mentioned in a comment, there is a 4-triangle star,

Now the question is whether to use this 12-vertex, 4-face star (I wouldn't use an index buffer because that would only be a savings of 2 vertices/prim the way I've constructed it here), or to use a square polygon with 2 triangles and use a texture on top.

I'd bet your horses that untextured polys will give you much better performance. But going with the textured quad is probably a better idea **for the reason of flexibility alone**: Using a texture *gives you additional flexibility* to change your mind about the shape of the object, with no runtime performance *change*, if you were to change the texture.

You could also use your same particle engine with different textures to achieve different effects. For example, the traditional "ball-shaped" particle will plug into your texture-based particle engine quite easily without requiring you to make many changes. So using a texture makes your particle engine easier to reuse in that way.

### Addendum: T-junctions

As Sam said, the triangle shown above infamous T-junctions. Look at the big triangle in the red-star. If you shade the leftmost vertex blue and the rightmost vertex green, what color could you shade the left/right vertices of the TOP triangle of the star? The gradient will look very wrong at the T-junctions, because you'd have to guess the interpolated color at the T-junctions, and that's not going to look good.

To eliminate T-junctions, you only need 8 triangles:

---
Tags: xna-4.0, performance, particles
---


# Question
Title: How does one develop a first person shooter with a one man team?
I have an idea for a first person shooter game and I have plenty of free time to work on it.

I know java and objective-c very well and I also know autodesk inventor (which is similar to 3ds max).

How would I go about starting to develop a small fps? What programming language should I use? What modeling/animation software should I use?

# Answer
"How to Program Independent Games" is a really good presentation from Jonathan Blow (creator of Braid) about how to take on the development of a game by yourself.

My best advice would be to make the smallest FPS you can (with any language/engine) and then expand on that.

Try Unity. That seems like the fastest way to make an FPS these days. Another way to do it would be to use an engine from another FPS such as, Half-Life, Quake or Unreal and basically make a total-conversion that in no way resembles the game the engine was made for. Counter-Strike was made this way. Heavily modding/totally converting a game is game development too.
> 21 votes

# Answer
Fundamentally creating a game with a one man team isn't really any different than creating a game with a huge team other than the fact that you don't have as many (or any, really) specialized people or parallelization of tasks. The decisions you would make here are the same decisions you would make if you were running a team who's goal was to get to ship as quickly as possible.

So you have to play to your strengths and *design* away from your faults. If you aren't very good at high poly art, you either need to pick a style that works with your skill set, or use existing art in the form of mods or buying art off stock websites. If you don't know anything about multiplayer networking, use middleware that solves most of the problems for you.

In particular, getting bogged down by non-critical-to-gameplay technology and features is going to suck away your time and not get you closer to your end goal. I'm personally a big fan of Unity due to it's super quick iteration time, easy art pipeline (just drop in pretty much any format and it'll work), and the ability play the game from within the editor. All of these will help you get up and running quicker than using something more "professional".

> What programming language should I use? What modeling/animation software should I use?

Use whatever you're comfortable with. If you're not comfortable with any of them, just pick one of the popular ones. The choice of tool here isn't going to make or break your progress by any significant factor compared to the design decisions you decide to go with.
> 10 votes

# Answer
go look at www.unity3d.com and it's tutorials. Also check out the "Tornado Twins" home page and their free Unity tutorials.
> 4 votes

# Answer
You question, as already mentioned, is quite broad and can easily be interpreted in multiple ways. One important requirement is ***why*** you want to create an FPS game. Your objective is important in narrowing down how to can achieve your goal. Are you just testing the water, perhaps to do bigger things, or is this just an interest and not necessarily some kind of career opportunity. Or are you just not sure?

The FPS game genre is quite old and as a result there are multiple ways in which you can create FPS type games depending on what you want to do. Here are just a few game engines that may be of interest to you:

* Unreal Development Kit (free for non-commercial use)
* Unity (gaining serious popularity, free version available)
* CryENGINE 3

For a much more comprehensive list look here.

At the other end of the spectrum are game engines designed for complete novices like these ones:

As for software and modelling tools you will need to try them out for yourself to get the 'feel' for them, but to make you job a little easier I have compiled a page which lists a number of them, I have only focused on listing free programs that can be used in game creation only though.
> 3 votes

# Answer
Did you consider making a mod for an existing game? That way you could safe a lot of time used on solving uninteresting problems like the graphic- and sound engine, user interface, netcode (when it's multiplayer) etc.. You can also reuse assets from the original game.

This allows you to concentrate fully on what matters most: Gameplay.

The drawback, of course, is that your game will be hard to monetize. Your target group are only those who bought the original game, and you can't really take money for your mod, because the publishers of the original usually don't support that. Your best bet is that the creators of the original buy you up, like Valve bought the Counter Strike team.

Regarding the programming language: The vast majority of first person shooters is programmed in C++. Most other programming languages aren't that good for the low level performance optimization which is required for fast 3d engines.
> 2 votes

---
Tags: first-person-shooter
---


# Question
Title: Getting individual sprites from png sprite sheets?
I'm using BYOB platform to get started in basic game development.

I was going to make a quick endless runner with a sprite downloaded from the net.

However, those sprites all come in sprite sheets, I guess for animation purposes. I only need one sprite, can I extract that from the sheet with Gimp or Inkscape?

# Answer
> 2 votes
Sprite Sheets, despite the name, are really only static images. That is to say, there's no hidden stacking or frames, so when you want to get just one sprite from a sprite sheet, the simplest way to do so is to crop the image to what you need.

Animation comes from changing which sprite is displayed over time, and oftentimes the way to do this is to assign one png (the sprite sheet) for the object's texture, and then limit which part of the texture is actually displayed, rather than have a separate PNG for each different frame.

---
Tags: sprites
---


# Question
Title: Is there any quick and easy way to make all bodies visible with Farseer physics engine for XNA?
I just want to be able to see all my bodies on the screen for debugging purposes and i cant think of an easy way, for example i have make some edge fixtures with curved arcs attached and i just want to see what they look like!

# Answer
> 3 votes
Farseer does ship a physics view, and thankfully it requires very little brain power to implement and use.

If you downloaded the "Farseer Physics Engine 3.3.1 Samples XNA" recommended package on their download page, you'd see a lot of examples included.

Navigate to (or click these convenient links to the codeplex page :P) `SamplesXNA/SamplesXNA/ScreenSystem/PhysicsGameScreen.cs` to see example usage of `FarseerPhysics.DebugViews.DebugViewXNA`.

It boils down to this:

```
FarseerPhysics.Dynamic.World myWorld;
// initialize myWorld...
var myDebugView = new FarseerPhysics.DebugViews.DebugViewXNA(myWorld);

```

And then you can set flags on it to determine what's visible:

```
myDebugView.RemoveFlags(DebugViewFlags.Shape);
myDebugView.RemoveFlags(DebugViewFlags.Joint);
myDebugView.DefaultShapeColor = Color.White;
myDebugView.SleepingShapeColor = Color.LightGray;

```

# Answer
> 1 votes
Farseer comes with a debugging environment. There's two ways of doing what you want to do. The first way is reproducing your situation in the test environment they ship. It will show everything of relevance. This is the technique I used for my game.

The other way is to integrate the debugging environment they made into your game, this is slightly more complex, and I haven't tried it yet, but if I understand correctly it should be possible, have a look around in the project and see what you can mix and match :)

Update: If it really is so simple as michael says then you should definitely do that, looks a lot better than what I did.

---
Tags: xna, farseer-physics-engine, body
---


# Question
Title: Is there any heuristic to polygonize a closed 2D raster shape with n triangles?
Let's say we have a 2D image black on white that shows a closed geometric shape.

Is there any (not naive brute force) algorithm that approximates that shape as closely as possible with n triangles? If you want a formal definition:

> Approximate the shape with a polygon that when rendered into a new 2D image will match the largest number of pixels possible with the original image.

# Answer
I think you'll need to do it in two or three steps:

For converting a raster image to polygons you can use pre-existing software like http://en.wikipedia.org/wiki/Potrace

Optimizing the result from that to get the best possible result with a specific number of polygons I believe is much harder. However efficiently optimizing an existing mesh down to a lower poly count isn't too difficult if you don't care about the result being optimal. For example http://research.microsoft.com/en-us/um/people/hoppe/proj/meshopt/ describes one algorithm to optimize a 3D mesh, based on a parameter saying how much to optimize it.

Once you have that optimized mesh you could apply a hill climbing algorithm to the vertex positions to try to further improve the fit.
> 3 votes

---
Tags: 2d, rendering, rasterization
---


# Question
Title: Is there a expected set of button mappings games commonly use?
I am making a game that will support a XBox 360 controller but I would like to try and keep the default button mappings to be what is expected from a user's past history from playing other games. Is there a set of guidelines from Microsoft on what should map to what (do you use `A` for fire or `left trigger`?), or has the gaming community picked up a common set of controls that is just not written anywhere, everyone just "knows" it (like WASD for movement).

The hardest thing for me is I have walking movement, vehicle movement, and airplane movement. I plan on allowing custom configuration of each, but I don't know what to set as the defaults.

# Answer
> 6 votes
There is no standard. About as close as you get to one is using the left stick to move and the right stick to look around or aim and using B for Cancel/No options (but no general standard for the Accept/Yes option!). Other than that it's all over the place.

A number of popular modern games have used all of the following for a primary fire button:

* A
* X
* Right trigger
* Hold left trigger and then hit one of the above

Note that right-trigger is very popular for shooters simply because it allows you to use both sticks (move and aim) while firing. Games that don't use the right-stick for anything in combat are more likely to use face buttons for attacking.

For secondary/melee, I've seen:

* A
* B
* X
* Y
* Left trigger
* Hold left trigger and then hit one of the above
* Tap right trigger

For opening a mini-map, I've seen:

* Y
* X
* B
* Menu
* Start
* D-pad (several different directions)

If in doubt, just go play a couple games in a similar genre to your game and see what they did. See if you like how it feels.

However you do it, do your in-game help properly! When a user is first expected to do something, tell them to do it and *show* them how. Don't just put some text that says "Press A to shoot." Pop up a picture of the A button (green circle, A in the middle) with "SHOOT!" next to it. If it makes sense in your HUD, keep the buttons displayed next to equipped items, so the user can instantly see what to press to use something he has picked up. If the usage is even remotely complicated or non-obvious, have some kind of tutorial (preferably in-game, not a popup/video!). Good tutorials are generally similar to ones where the user is stuck until he uses/masters the new move/item, with some kind of in-game reminder of "press \[button image\] to \[action\]" messages until he escapes the area.

Point being, you should be more concerned with ensuring your game can teach your player how to play it than hoping that you can rely on the player intuitively knowing how to play your game. Even if there was some standard-ish layout, you want to support new and casual players as well as hardcore gamers.

A wise man once told me that all games are basically just really long tutorials on how to play that one game. While I'm not sure that's true for every genre or type of game, it's a very good rule of thumb to keep in mind.

# Answer
> -3 votes
I used this, its a kind of standarized "Keyboard to Controller" map, but when you are diving deeper you may just google something like "xbox360 xontroler mapping", the picture search gives you the mapping of some games.

For your multiple game modes just make sure you keep the cmmon functions in the same place, so that you wont steer a car with the left stick and a plane with the right one.

---
Tags: movement, controllers, user-experience, xbox-controller
---


# Question
Title: Does the order of vertex buffer data when rendering indexed primitives matter?
I'm building a 3d object's triangles. If I can write them to the buffer in the order they are calculated it will simplify the CPU code. The vertices for the triangles will not be contiguous.

Is there any performance penalty for writing them out of order?

# Answer
There are (at least) two factors at play here. GPUs can utilize a post-transform vertex cache when indexed primitives are rendered. The size of this cache varies, and it's utilized during an individual draw call (not across multiple calls, as far as I'm aware, so it doesn't matter how frequently you change the buffer data in that context).

If you organize your data to take advantage of this cache (an example algorithm is here), you can see performance improvements. However, this organization has more to do with ordering your indices so that each index triple reuses as many recently-seen vertices as possible. It probably has little bearing on your specific scenario, unless your triangles, via your index buffer, are also randomly scattered about in the buffer... in which case you're probably blowing the cache often. It wasn't clear to me in your question whether or not this was the case, so I thought it worth mentioning.

What's more likely to be a problem is that GPUs also cache memory accesses to vertex data during a draw. The size of *that* cache is also fairly unreliably sized and it's conceivable that you could get a high miss frequency in that cache on the individual cores processing those indices into very poorly localized vertex data.

As to wether or not that's going to cause enough of a performance issue to be a red flag in your application, and particular (it sounds like) to re-engineer your algorithm to better organize the data at the expense of the readability of the algorithm... that's not something I can answer, you'll have to profile some scenarios and see.

I would personally err on the side of readable, maintainable code, though, as I *think* any cache missing you are going to cause is not going to be significant enough for users to notice.
> 12 votes

---
Tags: opengl
---


# Question
Title: Long running calculation on background thread
In my Cocos2D game for iOS I have a relatively long running calculation that happens at a fairly regular interval (every 1-2 seconds). I'd like to run the calculation on a background thread so the main thread can keep the animation smooth.

The calculation is done on a grid. Average grid size is about 100x100 where each cell stores an integer. Should I copy this grid when I pass it to the background thread? Or can I pass a reference and just make sure I don't write to the grid from the main thread before the background thread is done?

Copying seems a bit wasteful but passing a reference seems risky. So I thought I'd ask.

# Answer
If you can guarantee that no writing will be done to the grid during this process that will cause any deadlocks or race conditions or invalidate the calculation, then pass the reference. But I'm guessing you can't guarantee this, so copying the grid is usually worth it.
> 3 votes

---
Tags: objective-c
---


title: What's best to use OTF or TTF?

text:
# Question
Title: What's best to use OTF or TTF?
What's the most recommended format should I use for fonts, OTF or TTF or another?

In looking for:

* Performance/Efficiency with SDL\_ttf library
* Free/Open-ness \[1\]

\[1\] I'm planning to use GPL3 and Open Font License.

# Answer
> 4 votes
If you want to use SDL\_ttf, then you have no choice but using TTF fonts, see the doc:

> SDL\_ttf supports loading fonts from TrueType font files, normally ending in .ttf, though some .fon files are also valid for use.

Now if OTF is still an option you would consider (even if there's no SDL\_otf, which means you'll have to implement it), it's potentially a better choice than TTF, for the reasons exposed here. It's also an open standard so that's a +1 for free/open-ness.

Still, fonts in game engines are usually simple bitmaps, for performance reasons. So if you're actually writing a game and performance *is* an issue, use an offline bitmap font generator as you were suggested in comments.

---
Tags: open-source, fonts
---


title: How to decide face side of sprite

text:
# Question
Title: How to decide face side of sprite
I am just starting game-dev with slick2D and marte engine. When I move my sprite left and right, I am doing walk animation but when the key is released how can I decide in which side the sprite face to set?

Here's the relevant code:

```
    Input ip = gc.getInput();

    if (ip.isKeyDown(Input.KEY_RIGHT))
    {
        this.currentAnim = "Anim2";
        System.out.println("down");
        x += 0.1f * delta;
    }

    if (ip.isKeyDown(Input.KEY_LEFT))
    {
        this.currentAnim = "Anim4";
        System.out.println("down");
        x -= 0.1f * delta;
    }

```

# Answer
> 3 votes
You might be overthinking this because this is extremely simple. Try thinking about it conceptually before you start thinking in code.

Your question is: which side should the sprite face after walking

The answer you want is: it should face the side the sprite walked towards

To decide that each frame we need to store `lastDirectionWalkedTowards` but lets abbreviate that a bit and call it `facing`. Now since your sprites move along the X-axis we only have to know if its left or right. You can create an enum for this but even easier would be to store it as an int, with +1 meaning facing right and -1 meaning facing left. We can use 0 for neutral when we havent walked yet, and use some sane default.

The complete psuedo code:

```
int facing = 0; //class member

//in the update method

if (ip.isKeyDown(Input.KEY_RIGHT))
{
    facing = 1;

    this.currentAnim = "Anim2";
    System.out.println("down");
    x += 0.1f * delta;
}
else if (ip.isKeyDown(Input.KEY_LEFT))
{
    facing = -1;

    this.currentAnim = "Anim4";
    System.out.println("down");
    x -= 0.1f * delta;
}
else // if no directional key was pressed
{
    if(facing == -1) // if facing left
    {
        this.currentAnim = "LookLeft";
    }
    else // if facing right or neutral
    {
        this.currentAnim = "LookRight";
    }
}

```

---
Tags: java, slick
---


# Question
Title: How to detect the device type in UnrealScript?
How can I recognize if the player device is an *iPad* or an *iPhone*?

Now I can do it by checking the viewport size. But I think is just a tricky way, is there any other, more standard way?

# Answer
> 0 votes
To detect what platform you're runnning on from UnrealScript, you'd typically use:

```
if( class'WorldInfo'.static.IsConsoleBuild(CONSOLE_Something) )
{
    // do something platform-specific
}

```

Unfortunately, Unreal doesn't make a distinction between the different kinds of iOS devices (they're all `CONSOLE_IPhone`), so you're out of luck.

Also, when submitting an app to the Apple Store, you only have one build for all devices: you won't be able to do it manually by making two different builds.

This is probably for a very good reason (Apple trying to keep compatibility between device types and iterations?), so double check that you really want to make a distinction. And if it's really the case, yes, you'll have to use some heuristic of yours, such as the display resolution.

---
Tags: udk, unreal
---


# Question
Title: How to produce assets effectively on large Flash game projects?
I have been working on Flash games professionally for two years now and somehow, having our artists producing assets the right way is one of our biggest challenge.

More precisely, it is very hard to have them following **any kind of structure and/or standards**, nor taking into consideration performance. I would say also the most of our issues concerns UI and related animations.

Our current workflow is (on a Facebook hidden object game) :

1. Artists produce PSD and animate prototypes in Flash
2. Artists re-organize their FLA files to be a bit more "programmer friendly"
3. Programmers retouches assets until they have the right structure and export classes inside a SWC, from Flash
4. Programmers try to improve performances, sometimes degrading the quality of game graphics

Our main idea is to hire somebody dedicated to prepare assets for programmers but I am really looking forward to improving the pipeline.

I was wondering if you guys have tips of any kind to improve this workflow, whether it be team organization, training, tools or tips with Flash. Any explanation on your asset pipeline is well appreciated too.

**EDIT** :

Thanks for your replies. I do agree with you that tools and processes will never replace collaborative people. However, I feel like we got stuck into this "I am doing my own thing" mentality as the integration process caused a lot of friction. As part of our Scrum process, the team clearly acknowledge its own quirks and was looking at immediate solutions for the next project : better rules, better attitude, better understanding of each other.

My team have specialized artists (UI, character drawing, character animation), but no leading art director (we use existing licenses/brands), and programmers (both front and back end). That's why having a very versatile person in between (designer, integrator, technical artist or however you want to call it) is invaluable in my opinion - so, I am looking for innovative solutions.

Usually, the main specs/requirements for assets are :

* Naming (of classes, textfields or various visual objects that will be used by the code, taking in account that visual needs can cause deep nesting of objects)
* States (that we implemented with frame labels)
* Alignement (always build from 0,0 - use round values)

So, while adopting "good practices" can sure help, there always is this little part of feature-specific requirements that has to be decided. Basically I was looking for a an efficient way to communicate these specs (even to non-technical people) and avoid the back and forth to verify assets are as expected (this is where my idea of intermediate validation format comes from).

I understand there is no clear answer and I created this post to get people feedback and good ideas (it's working so far :)

# Answer
> 3 votes
Rules/processes are key, but just sticking a set of rules on the wall will not work.

* A good production team lead (having found out developers' need in terms of assets) should sit with artists to go through these processes, since a team lead's job is to *facilitate* work, whereas a developer's job is to *do* work. Developers should never, ever touch assets (just as designers should never touch code). Once they do, the balance starts to shift unfavourably towards artwork, as artists have more time on their hands, and developers, less.
* Rules don't enforce themselves. You need to establish authority and discipline for your rules to work. "Understanding" is not the same as "trying to understand", so "I don't understand" is a very limited excuse. I have seen artists on many of my contracts choose not to obey set rules because they do not see these rules as impacting them personally, so why bother? Until such time as there *is* an impact, compliance will fall by the wayside; most artists see their job as "being creative", not as "following rules". So you need to make it clear how important it is, by rewards and, if you're evil, also punishments. Get senior management support if necessary.
* On the start of a section of work, have an inclusive meeting where artists are expected to participate as part of the overall production team by getting involved with what output specifications are required and most importantly ask questions about *why*. Artists who are more involved should be rewarded in some way (buy them a six-pack as a monthly prize, for instance) aside from the social benefit of being well-liked by the programmers. Have these meetings *only for as long as it is necessary to bring artists up to speed with process*, i.e. avoid wasting production time on meetings.
* Once this knowledge has been imparted over a period of time, from developers and team leads to artists, it will largely become second nature to the artists.

# Answer
> 3 votes
To me it seems you have a communication issue, rather than something that can be fixed by using tools or adding a person to the team to correct the mistakes your team makes. It's best to prevent making mistakes by improving your communication.

## The designer

I'm going to assume (for now) you have a designer. (Not the same as an artist!)

The designer maintains a creative vision of the final product, and determines what assets are required to put that vision together. The artists then create the assets according to the specs (dimensions, file type, etc.) the designer provided, and the programmers implement the gameplay rules and include the artwork into the code.

Basically, both the artists and the programmers work for the designer. The designer acts as a go-between for the two disciplines, and needs to know both the technical and the artistic limitations, and keep the user experience in mind at all times.

## Collaborate design

Now, if you don't have a designer, it's a little more tricky. That means your entire team needs to act as a designer in a collaborate way. You should plan sessions to discuss what features are required, what art assets are required to implement those features, and how best to implement them.

The most important thing is that you write down everything you agreed upon; what has to be implemented before the feature is considered completed, and what technical requirements it has to conform to.

## Mixing both styles

You can have both a designer and design your game in a collaborate way. This allows for more creative input from both the programmers and the artists, and often results in ideas the designer did not think of. It also helps to communicate both the technical and artistic limitations to all three disciplines while having the designer maintain a clear product vision.

## Further reading

For further reading on collaborate project management, I suggest looking into Agile, Scrum and Valve's Cable methods:

# Answer
> 3 votes
The flash games I've been working on recently (isometric browser games where players get to build their Farm, Park, Zoo, Whatever) used a combination of animated SWFs, spritesheets, PNG's and procedural, bitmap-filled API rendering.

Only the animated SWFs were authored in Flash by artist, the rest of the game, as far as Flash is concerned was created in Flex Builder by programmers.

To get the assets into the project we set up an asset pipeline generating and compiling code that would make heavy use of the \[Embed\] tag but saved us the hassle of embedding assets manually. Here's some additional info if the idea interests you.

Performance issues related to assets are quick to resolve that way. You just tell the artist responsible for a problematic asset to redo it. We didn't care for how messy their FLA's were as long as the exported SWF would look good and be reasonable in size and performance.

# Answer
> 1 votes
I think I'd start with creating some kind of basic set of rules every designer has to follow. I'd do this with programmers and artists together so both can give you input and you try to find the best compromise between beautifull artwork and usable art. This set would contain all the "rules" for creating optimized art which doesn't look crappy and is programmer friendly, but also doesn't look extremely well but loads to slow due to huge file size etc.

If your artists can follow this, there is no need to refactor the animations etc later on. It can be very usefull to have a dedicated "art preparer" but it seems quite expensive. I'd try to create more understanding on both "teams" and better define the possibilities and impossibilities to both sides.

# Answer
> 1 votes
I will go by giving a possible answer to my own question. However, I won't mark it as the "right" one now since I have never tried it and some others answers are possible.

Some developers have developed a set of GUI extensions for Flash to allow designers to produce assets using custom rules or formats. More precisely, these provide:

* Snippets accessible through a comprehensive GUI to speed up repetitive tasks
* Metadata through naming of instances or layers
* Export routines assets in the desired format

Thanks to JSFL, it's possible to speed Flash asset creation, and it's even easier with xJSFL. Here's an example of that.

I was also thinking that one could add routines to "verify" the structure/naming of assets, by having some sort of descriptor file that would be the agreement between programmers and artists.

---
Tags: flash, assets, pipeline
---


# Question
Title: Drawing an arrow cursor on user dragging in XNA/MonoGame
I am writing a touch enabled game in MonoGame (XNA-like API) and would like to display a an arrow 'cursor' as user is making a drag gesture from point A to point B. I am not sure on how to correctly approach this problem. It seems that its best to just draw a sprite from A to B and scale it as required. This would however mean it gets stretched as user continues dragging gesture in one direction. Or maybe its better to dynamically render the arrow so it looks better?

# Answer
> 3 votes
You may split the arrow into a shaft and a head. Then you just enlarge the shaft and add the head later on. This will prevent your arrowhead from being stretched and if you pick a shaft image which will not show any signs of strechting (i.e. a rectangle) the whole process will be hidden.

---
Tags: xna, touch, monogame
---


title: High CPU usage on Pong clone

text:
# Question
Title: High CPU usage on Pong clone
I just made my first game, a clone of Pong, using OpenGL and C++. But its using ~50% of the CPU, which I guess is very high for a game like this. How can I improve that? Can you please look up my code and tell me what all things I am doing wrong? Any feedback is welcome.

http://pastebin.com/L5zE3axh

http://pastebin.com/rMJ6PG9k

Also it would be extremely helpful if you give some general points on how to develop games in OpenGL efficiently..

Thanks in advance!

**EDIT 1:**

I forced VSync on from CCC, and now the game just shows ~5% CPU usage, except when my own wait() method is called (my fault). I can solve that...but now another problem has come, the game feels very choppy and its not smooth after forcing on VSync. Maybe tearing because of single buffering?

Any ideas?

**EDIT 2:**

Was calling the display callback twice from my idle function, using display() and glutPostRedisplay()! Also, changed the mode to GLUT\_DOUBLE, now Fraps works on it..

One more thing! This game is working fine with VSync on (or forced) at 60fps.. but when I turn off VSync, it goes too fast. Do I have an option to turn on VSync? Or is any any other way?

# Answer
> 8 votes
You've implemented your own wait function that keeps the CPU running a small loop instead of letting it process other threads.

Call a sleep() method instead. It comes in various styles and flavors (depending on platform) or, if you want to keep your code portable, you could use Boost Thread e.g

```
 boost::this_thread::sleep( boost::posix_time::seconds(1) );

```

---
Tags: c++, opengl, collision-detection, efficiency
---


# Question
Title: Billboarding restricted to an axis (cylindrical)
I have succesfully created a GLSL shader for a billboarding effect. I want to tweak this to restrict the billboarding to an arbitrary axis, i.e. a billboarded quad only rotates itself about the y-axis. I use the y-axis as an example, but essentially I would like this to be an arbitrary axis. Can anyone show me how to modify my existing shader below, or if I need to start from scratch, point me towards some resources that could be helpful?

```
precision mediump float;

uniform mat4 u_modelViewProjectionMat;
uniform mat4 u_modelMat;
uniform mat4 u_viewTransposeMat;

uniform vec3 u_axis; // <------------ !!! the arbitrary axis to restrict rotation around

attribute vec3 a_position0;
attribute vec2 a_texCoord0;

varying vec2 v_texCoord0;

void main()
{
    vec3 pos = (a_position0.x * u_viewTransposeMat[0] + a_position0.y * u_viewTransposeMat[1]).xyz;
    vec4 position = vec4(pos, 1.0);

    v_texCoord0 = a_texCoord0;

    gl_Position = u_modelViewProjectionMat *  position;
}

```

**EDIT** \- The modified shader for cylindrical billboarding. Its very straight forward! Just swap out the up vector for the axis to restrict rotation about.

```
precision mediump float;

uniform mat4 u_modelViewProjectionMat;
uniform mat4 u_modelMat;
uniform mat4 u_viewTransposeMat;

uniform vec3 u_axis; // <------------ !!! the arbitrary axis to restrict rotation around

attribute vec3 a_position0;
attribute vec2 a_texCoord0;

varying vec2 v_texCoord0;

void main()
{
    vec3 pos = (a_position0.x * u_viewTransposeMat[0] + a_position0.y * vec4(normalize(u_axis), 0.0)).xyz;
    vec4 position = vec4(pos, 1.0);

    v_texCoord0 = a_texCoord0;

    gl_Position = u_modelViewProjectionMat *  position;
}

```

# Answer
While I ended up with a similar approach to yours, I can tell you about an implementation I went through on my way there. It's probably a bit simpler to understand, so it should be easier to modify.

Basically, I use the normal of the vertex to tell the vertices which way to shift in the view plane. More specifically, that can be done like this:

```
float xVal = Position.x - ((CameraRight.x * Normal.x) + (CameraUp.x * Normal.y));
float yVal = Position.y - ((CameraRight.y * Normal.x) + (CameraUp.y * Normal.y));
float zVal = Position.z - ((CameraRight.z * Normal.x) + (CameraUp.z * Normal.y));
vec4 vertexPos = vec4(xVal, yVal, zVal, 1.0);
gl_Position = ProjectionMatrix * ModelViewMatrix * vertexPos;

```

Where I'm setting the camera up and camera right as uniforms at the beginning of each frame. The normal positions are set like so:

```
//position x, y and z, then normal x, y, and z then float2 texture coords, then color
billboards.add(pos.x, pos.y, pos.z, bbhs, -bbhs, 0, texture[0], backColor);
billboards.add(pos.x, pos.y, pos.z, bbhs, bbhs, 0, texture[1], backColor);
billboards.add(pos.x, pos.y, pos.z, -bbhs, -bbhs, 0, texture[2], backColor);
billboards.add(pos.x, pos.y, pos.z, -bbhs, bbhs, 0, texture[3], backColor);

```

You could easily modify the axis being modified by changing the normal coordinates. Or if you only wanted the y axis, you always pass the camera up as (0,1,0).
> 2 votes

---
Tags: glsl, matrix, billboarding
---


title: Snake Game Help

text:
# Question
Title: Snake Game Help
I am making a snake game and learning XNA at the same time. I have 3 classes :

`Game.cs`, `Snake.cs` and `Apple.cs`

My problem is more of a conceptual problem, I want to know which class is really responsible for ...

* detecting collision of snake head on apple/itself/wall?
* which class should increase the snakes speed, size?

It seems to me that however much I try and put the snake stuff into snake.cs that game.cs has to know a lot about the snake, like :

-- I want to increase the score depending on size of snake, the score variable is inside `game.cs`, which means now I have to ask the snake its size on every hit of the apple... seems a bit unclean all this highly coupled code.

or

-- I DO NOT want to place the apple under the snake... now the apple suddenly has to know about all the snake parts, my head hurts when I think of that. Maybe there should be some sort of `AppleLayer.cs` class that should know about the snake...

Whats the best approach in such a simple scenario? Any tips welcome.

**Game.cs :**

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Design;

namespace Snakez
{
    public enum CurrentGameState
    {
        Playing,
        Paused,
        NotPlaying
    }

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager _graphics;
        private SpriteBatch _spriteBatch;
        private readonly Color _niceGreenColour = new Color(167, 255, 124);
        private KeyboardState _oldKeyboardState;
        private SpriteFont _scoreFont;
        private SoundEffect _biteSound, _crashSound;
        private Vector2 _scoreLocation = new Vector2(10, 10);

        private Apple _apple;
        private Snake _snake;
        private int _score = 0;
        private int _speed = 1;

        public Game1()
        {
            _graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            _spriteBatch = new SpriteBatch(GraphicsDevice);
            _scoreFont = Content.Load<SpriteFont>("Score");
            _apple = new Apple(800, 480, Content.Load<Texture2D>("Apple"));
            _snake = new Snake(Content.Load<Texture2D>("BodyBlock"));
            _biteSound = Content.Load<SoundEffect>("Bite");
            _crashSound = Content.Load<SoundEffect>("Crash");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            Content.Unload();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState newKeyboardState = Keyboard.GetState();
            if (newKeyboardState.IsKeyDown(Keys.Escape))
            {
                this.Exit(); // Allows the game to exit
            }
            else if (newKeyboardState.IsKeyDown(Keys.Up) && !_oldKeyboardState.IsKeyDown(Keys.Up))
            {
                _snake.SetDirection(Direction.Up);
            }
            else if (newKeyboardState.IsKeyDown(Keys.Down) && !_oldKeyboardState.IsKeyDown(Keys.Down))
            {
                _snake.SetDirection(Direction.Down);
            }
            else if (newKeyboardState.IsKeyDown(Keys.Left) && !_oldKeyboardState.IsKeyDown(Keys.Left))
            {
                _snake.SetDirection(Direction.Left);
            }
            else if (newKeyboardState.IsKeyDown(Keys.Right) && !_oldKeyboardState.IsKeyDown(Keys.Right))
            {
                _snake.SetDirection(Direction.Right);
            }
            _oldKeyboardState = newKeyboardState;
            _snake.Update();
            if (_snake.IsEating(_apple))
            {
                _biteSound.Play();
                _score += 10;
                _apple.Place();
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(_niceGreenColour);

            float frameRate = 1 / (float)gameTime.ElapsedGameTime.TotalSeconds;

            _spriteBatch.Begin();
            _spriteBatch.DrawString(_scoreFont, "Score : " + _score, _scoreLocation, Color.Red);
            _apple.Draw(_spriteBatch);
            _snake.Draw(_spriteBatch);
            _spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

**Snake.cs** :

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Snakez
{
    public enum Direction
    {
        Up,
        Down,
        Left,
        Right
    }

    public class Snake
    {
        private List<Rectangle> _parts;
        private readonly Texture2D _bodyBlock;
        private readonly int _startX = 160;
        private readonly int _startY = 120;
        private int _moveDelay = 100;
        private DateTime _lastUpdatedAt;
        private Direction _direction;
        private Rectangle _lastTail;

        public Snake(Texture2D bodyBlock)
        {
            _bodyBlock = bodyBlock;
            _parts = new List<Rectangle>();
            _parts.Add(new Rectangle(_startX, _startY, _bodyBlock.Width, _bodyBlock.Height));
            _parts.Add(new Rectangle(_startX + bodyBlock.Width, _startY, _bodyBlock.Width, _bodyBlock.Height));
            _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 2, _startY, _bodyBlock.Width, _bodyBlock.Height));
            _parts.Add(new Rectangle(_startX + (bodyBlock.Width) * 3, _startY, _bodyBlock.Width, _bodyBlock.Height));
            _direction = Direction.Right;
            _lastUpdatedAt = DateTime.Now;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            foreach (var p in _parts)
            {
                spriteBatch.Draw(_bodyBlock, new Vector2(p.X, p.Y), Color.White);
            }
        }

        public void Update()
        {
            if (DateTime.Now.Subtract(_lastUpdatedAt).TotalMilliseconds > _moveDelay)
            {
                //DateTime.Now.Ticks
                _lastTail = _parts.First();
                _parts.Remove(_lastTail);

                /* add new head in right direction */
                var lastHead = _parts.Last();
                var newHead = new Rectangle(0, 0, _bodyBlock.Width, _bodyBlock.Height);
                switch (_direction)
                {
                    case Direction.Up:
                        newHead.X = lastHead.X;
                        newHead.Y = lastHead.Y - _bodyBlock.Width;
                        break;
                    case Direction.Down:
                        newHead.X = lastHead.X;
                        newHead.Y = lastHead.Y + _bodyBlock.Width;
                        break;
                    case Direction.Left:
                        newHead.X = lastHead.X - _bodyBlock.Width;
                        newHead.Y = lastHead.Y;
                        break;
                    case Direction.Right:
                        newHead.X = lastHead.X + _bodyBlock.Width;
                        newHead.Y = lastHead.Y;
                        break;
                }
                _parts.Add(newHead);
                _lastUpdatedAt = DateTime.Now;
            }
        }

        public void SetDirection(Direction newDirection)
        {
            if (_direction == Direction.Up && newDirection == Direction.Down)
            {
                return;
            }
            else if (_direction == Direction.Down && newDirection == Direction.Up)
            {
                return;
            }
            else if (_direction == Direction.Left && newDirection == Direction.Right)
            {
                return;
            }
            else if (_direction == Direction.Right && newDirection == Direction.Left)
            {
                return;
            }
            _direction = newDirection;
        }

        public bool IsEating(Apple apple)
        {
            if (_parts.Last().Intersects(apple.Location))
            {
                GrowBiggerAndFaster();
                return true;
            }
            return false;
        }

        private void GrowBiggerAndFaster()
        {
            _parts.Insert(0, _lastTail);
            _moveDelay -= (_moveDelay / 100)*2;
        }
    }
}

```

**Apple.cs :**

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Snakez
{
    public class Apple
    {
        private readonly int _maxWidth, _maxHeight;
        private readonly Texture2D _texture;
        private readonly Random random = new Random();
        public Rectangle Location { get; private set; }

        public Apple(int screenWidth, int screenHeight, Texture2D texture)
        {
            _maxWidth = (screenWidth + 1) - texture.Width;
            _maxHeight = (screenHeight + 1) - texture.Height;
            _texture = texture;
            Place();
        }

        public void Place()
        {
            Location = GetRandomLocation(_maxWidth, _maxHeight);
        }

        private Rectangle GetRandomLocation(int maxWidth, int maxHeight)
        {
            // x and y -- multiple of 20
            int x = random.Next(1, maxWidth);
            var leftOver = x % 20;
            x = x - leftOver;

            int y = random.Next(1, maxHeight);
            leftOver = y % 20;
            y = y - leftOver;

            return new Rectangle(x, y, _texture.Width, _texture.Height);
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(_texture, Location, Color.White);
        }
    }
}

```

# Answer
> 2 votes
According to your game design you need one more class for Map. In the map class

1. You first define a grid which is the map grid whose walls have a texture.
2. Create a snake object inside the map class.
3. Inside the map you create an apple object at random position after every apple is eaten.
4. Now you have everything snake, walls and apple inside the map class.
5. All you have to do is detect movement and collisions in update method of map. As per your question where to detect collision, you detect collision inside map using intersects method of rectangle. If free space then valid move, if wall texture or snake texture then snake dead.

# Answer
> 1 votes
You can have a `CollisionManager` class to detect every collision, it makes some sense if you think about the real world, we don't actually detect collisions, we just feel then when they happen. You can make an `ICollidable` interface and your `CollisionManager` can call an `onCollision` method, this way the snake doesnt have to know about the walls or the apple, they just have to know what kind of object they collided with (apple, wall, etc) and can react accordingly.

Also, I see no problem with Game knowing about the Snake, it has to and the simplest way is to query the Snake for that. If you keep trying to make a perfect architecture, you will never make a game. Relax and use whatever works for your game.

**edit:**

Something like this (I don't know C#, but Ill try to make the code understandable):

```
interface ICollidable
{
    void onCollision(ICollidable other);
}

class Snake implements ICollidable
{
    void onCollision(ICollidable other)
    {
        if(other typeof Apple)
            grow();
        [...]
    }
}

class CollisionManager
{
    list<ICollidable> collidables;
    void addCollidable(ICollidable object){...}
    void update(float delta)
    {
        for(ICollidable c in collidables)
        {
            if(collision(c)) c.onCollision(...);
        }
    }
}

```

# Answer
> 0 votes
Questions about snake games are rather common, you should first check those for general directions:

For your specific question, I think you should use **less polling and more pushing**. You need to make sure your objects depend on the "game state" (objects *push* to the game), but not the other way around (game polls *from* the objects): circular dependencies are evil.

Here's what I would do for your two specific scenarios:

> I want to increase the score depending on size of snake, the score variable is inside game.cs, which means now I have to ask the snake its size on every hit of the apple... seems a bit unclean all this highly coupled code.

Let your snake affect the score every time it updates. E.g. add a new method such as `Game1::SetScore()` and call it from `Snake::Update()`.

> I DO NOT want to place the apple under the snake... now the apple suddenly has to know about all the snake parts, my head hurts when I think of that. Maybe there should be some sort of AppleLayer.cs class that should know about the snake...

As you figured yourself, and as Chandan Pednekar answered, you need some kind of map/level object, basically a 2D array of tile types for a simple snake. Push your snake "body parts" to the map, add a method to find a random free spot that take those in account, and use this to place new apples.

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


# Question
Title: How do I calculate the boundary of the game window after transforming the view?
My `Camera` class handles zoom, rotation, and of course panning. It's invoked through `SpriteBatch.Begin`, like so many other XNA 2D camera classes. It calculates the view `Matrix` like so:

```
public Matrix GetViewMatrix() {
    return Matrix.Identity
        * Matrix.CreateTranslation(new Vector3(-this.Spatial.Position, 0.0f))
        * Matrix.CreateTranslation(-( this.viewport.Width / 2 ), -( this.viewport.Height / 2 ), 0.0f)
        * Matrix.CreateRotationZ(this.Rotation)
        * Matrix.CreateScale(this.Scale, this.Scale, 1.0f)
        * Matrix.CreateTranslation(this.viewport.Width * 0.5f, this.viewport.Height * 0.5f, 0.0f);
}

```

I was having a minor issue with performance, which after doing some profiling, led me to apply a culling feature to my rendering system. It used to, before I implemented the camera's zoom feature, simply grab the camera's boundaries and cull any game objects that did not intersect with the camera.

However, after giving the camera the ability to zoom, that no longer works. The reason why is visible in the screenshot below. The navy blue rectangle represents the camera's boundaries when zoomed out all the way (`Camera.Scale = 0.5f`). So, when zoomed out, game objects are culled before they reach the boundaries of the window. The camera's width and height are determined by the `Viewport` properties of the same name (maybe this is my mistake? I wasn't expecting the camera to "resize" like this).

What I'm trying to calculate is a `Rectangle` that defines the boundaries of the screen, as indicated by my awesome blue arrows, even after the camera is rotated, scaled, or panned.

Here is how I've more recently found out how *not* to do it:

```
public Rectangle CullingRegion {
    get {
        Rectangle region = Rectangle.Empty;

        Vector2 size = this.Spatial.Size;
        size *= 1 / this.Scale;

        Vector2 position = this.Spatial.Position;
        position = Vector2.Transform(position, this.Inverse);

        region.X = (int)position.X;
        region.Y = (int)position.Y;
        region.Width = (int)size.X;
        region.Height = (int)size.Y;

        return region;
    }
}

```

It seems to calculate the right size, but when I render this region, it moves around which will obviously cause problems. It needs to be "static", so to speak. It's also obscenely ***slow***, which causes more of a problem than it solves.

What am I missing?

# Answer
> 3 votes
Ask your `Game` class what the properties of `Window.ClientBounds.Width` and `Window.ClientBounds.Height` are.

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


title: Crystal Transparency(Shadows)

text:
# Question
Title: Crystal Transparency(Shadows)
I'm having a really hard time getting the shadows the become transparent. I've looked online and followed tutorials, but it's not working(See Below).

It may be a little difficult to see so you should look at it in a different window.

How do I add transparency to the shadow(color less saturated), in a way to make the light look like it goes through the crystals?

# Answer
> 2 votes
I'm not sure if your materials are set up correctly, but your floor mesh should have the Receive Transparent option (I'm supposing the object selected is one of the crystals)

# Answer
> 0 votes
One option is to set the "Shadow Color" of the light that's set to cast the shadows. Check under the Shadow settings for a colour box.

The only drawback is that it changes the shadows for *all* objects in the scene. You might be able to use light groups or layers somehow to limit the shadow's effects, but I don't know how that would work.

---
Tags: blender
---


# Question
Title: In a resource manager, how do I handle a resource containing other resources?
I have a resource manager, handling the usual resource loading, unloading etc. With resources such an images and meshes, there is no problem. However, what do I do when I have a resource containing other resources? For example, `spriteFont` contains reference to a sprite and a letter description.

Should that sprite be added to resource manager, or should my `spriteFont` be the only owner of that resource?

# Answer
> 2 votes
My fonts own the images that represent their fonts. I see no reason to add the image to the general pool of resources. The resource manager doesn't even need to know about it. I use the same routines for loading the image, but it's loaded into the font object. Nothing other than the fonts will use that image.

---
Tags: resource-management
---


title: SDL blitting multiple surfaces at once

text:
# Question
Title: SDL blitting multiple surfaces at once
I'm trying to write a platforming game where the sprites for the level backgrounds are broken up into 512x512 chunks. I keep 3 chunks in memory at a time and I'm trying to write code to blit all three to the screen. Here is the current code I have:

```
SDL_Rect where;
where.y = -game->camera->y;

where.x = -game->camera->x - MAP_WIDTH;
SDL_BlitSurface(left_chunk, NULL, screen, &where);

where.x = -game->camera->x;
SDL_BlitSurface(center_chunk, NULL, screen, &where);

where.x = -game->camera->x + MAP_WIDTH;
SDL_BlitSurface(right_chunk, NULL, screen, &where);

```

The issue I'm running into is that whichever chunk gets blitted first is the only one that shows up. The rest fail to appear onscreen. I think the issue might have something to do with alpha transparency, but even if the chunks don't overlap at all they still fail to blit. In other parts of the code I'm blitting multiple things to the screen at once, such as characters and backgrounds, and they all show up correctly. This particular segment of code is the only area I'm encountering this problem.

If I comment out the line that blits left\_chunk, it changes to this:

# Answer
> 8 votes
The SDL documentation says that SDL\_BlitSurface saves the final rectangle to **dstrect** after blitting. Reseting the *where* variable fixes the problem.

---
Tags: sdl
---