# Question
Title: I need help with specific types of movement
I'm adding movable crates to my game and I need some help with my movement code. The way I've set up my movement code the crate's X and Y are moved according to a vector2 unless it hits a wall. Here's the movement code:

```
if (frameCount % (delay / 2) == 0)
        {
            for (int i = 0; i < Math.Abs(cSpeed.X); i++)
            {
                if (!Level.PlayerHit(new Rectangle(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height)))
                {
                    if (!Level.CollideTiles(crateBounds.X + (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height))
                    {
                        if (cSpeed.X != 0)
                        {
                            crateBounds.X += Math.Sign(cSpeed.X);
                        }
                        else
                        {
                            Equalize(2);
                        }
                    }
                    else
                    {
                        cSpeed.X = 0f;
                    }
                }
                else
                {
                    if (!Level.CollideTiles(crateBounds.X - (Math.Sign(cSpeed.X) * 32), crateBounds.Y, crateBounds.Width, crateBounds.Height))
                    {
                        if (cSpeed.X != 0)
                        {
                            crateBounds.X -= Math.Sign(cSpeed.X);
                        }
                        else
                        {
                            Equalize(2);
                        }
                    }
                    else
                    {
                        cSpeed.X = 0f;
                    }
                }
            }

            for (int i = 0; i < Math.Abs(cSpeed.Y); i++)
            {
                if (!Level.PlayerHit(new Rectangle(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height)))
                {
                    if (!Level.CollideTiles(crateBounds.X, crateBounds.Y + Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height))
                    {
                        crateBounds.Y += Math.Sign(cSpeed.Y);
                    }
                    else
                    {
                        cSpeed.Y = 0f;
                    }
                }
                else
                {
                    if (!Level.CollideTiles(crateBounds.X, crateBounds.Y - Math.Sign(cSpeed.Y), crateBounds.Width, crateBounds.Height))
                    {
                        crateBounds.Y -= Math.Sign(cSpeed.Y);
                    }
                    else
                    {
                        cSpeed.Y = 0f;
                    }
                }
            }
        }

```

The frameCount and delay variables just slow down the movement somewhat. Anyway, I've added a tool to my game that acts as a gravity well (drawing objects into it's center; the closer they get to the center the faster they go) and what I'm trying to do is make it so that the crate will bounce off the player (and vice versa) when they collide. Thus far, my code only keeps the crate and player from getting stuck inside each other (the player can still get stuck under the crate, but I'll fix that later.) So what I'd like to know is how I can best make the crate bounce off the player.

The other movement problem I'm having is related to another tool which allows the player to pick up crates and move around with them. The problem is that the crate's movement while being carried isn't tied to the movement script (it moves the crate itself, instead of adding to speed), which makes the crate go through walls and such. I know what I have to do: make the crate's speed match the player's speed while the player is holding it, but I need the crate to snap to a certain position (just in front of the player) when the player grabs it and it needs to switch to another position (just in front of the player on the other side) when they player faces the other direction while holding it. What would be the best way to make it switch places while keeping all the movement tied to the speed vector?

# Answer
You are doing too much things togheter. You see, five indentations level are *too much*. Now you should add even a sixth... I think your aproach is wrong and it can lead you only in an unmantainable code.

Well, enought criticism: lets work.

1. you should work in each frame (do less things but do them).
2. model things with a common base (both player and crates are solid objects with a position and an extent)
3. model dynamics for the common base, **Do not code it into this or that object** but do it in another function/class (class is better).
4. try to apply your position variation at once in a frame (not in a for loop): you will miss a collision only if you are travel very fast.
5. vector come from Latin *vector* "one who carries or conveys, carrier" so **NEWPOS** = **OLDPOS** \+ **VECTOR** ( a definition for vector is **V** = **B** \- **A** so you can use **V** to go from **A** to **B**)

If you do so, you can add a status to your crate so it can be FREE or PICKED, you change this status by the methods drop() and pickup(player): when you drop the crate's dynamic become the free status dynamic; when *player* picks up the crate, the crate will ask the player to give it the new dynamic it have to obey.

At each frame you:

* update each common-base-objects current dynamic step that will change the common-base-object position accordly;
* do the collision detection for each type - looking to the current status if needed and varing the dynamics parameters on collisions
* update your scene according to the updated objects status.

Doing so you decouple things and factor common behaviours without explore each possibility in a single deep tree of nested ifs and fors.

Comments are appreciated
> 2 votes

---
Tags: xna, collision-detection, movement
---


# Question
Title: Volume that encompasses the whole scene?
I'm thinking that the straight-forward way would be to just iterate through the objects and just find the maximum and minimum coordinates on each axis, but this seems a little bit unoptimal.

Is there a faster, more efficient way of doing this?

# Answer
> 1 votes
I don't know why or how exact your volume needs to be, but if you give each object a bounding sphere (you probably already have that, or it might be wise) you can very cheaply merge all these bounding spheres to find the entire volume. Of course this would still be O(N) but merging bounding spheres is really cheap.

Another solution would be spatial partitioning, you divide your world into large (axis aligned cube like) chunks and every time an object moves you update in which chunk it is, at the same time you can also check if the chunk it moved to is more to the outside as the last most outside part.

You have to take care though that if an object leaves one of the most outside parts you have to check if that outside chunk is now empty, and if so slightly shrink the volume.

A good way to do this would be to store an int\[x,y,z\] that stores how many objects are present, or another structure like a list, that stores a references to each object in that chunk.

Anyway if you clarify your question even further by describing what you're trying to accomplish we would probably be able to give you a better answer.

# Answer
> 2 votes
When building an Octree, you can start at any size and change it later, for example, I once wrote an octree to help reduce the interation tests in my physics collision detection routine, and started out with size 1.0f for each axis. As physics elements were added to the scene, the octree grew, the first element was a 4.0f radius object somewhere quite far from the origin, lets say (5,4,100), so as there were no elements in the octree, I merely **resized the root node** (doubling it until it fit) to 128.0f.

The second element is where you see interesting things, the second element added was also outside the existing octree, (200,200,200, Radius4) so the root node could not hold it, so instead, i created a **new double size root node**, and pushed the current root node contents out into the 8 new nodes (only one created in this case as the octree was brand new)

The new root was big enough, so now I had two nodes, one root and one octree branch.

This carried on until all the elements were added to the scene, adding a new node at the root whenever the content was outside the existing range, adding new nodes at the branch whenever the number of items in the branch went over my arbitrary limit.

The side effect of starting with a small size and resizing cannot be overstated. Unless you're working in a constrained world, you're bound to go *out-of-bounds* at some point.

---
Tags: bounding-boxes, octree
---


# Question
Title: What are some ways to separate game logic from animations and the draw loop?
I have only previously made flash games, using MovieClips and such to separate out my animations from my game logic. Now I am getting into trying my hand at making a game for Android, but the game programming theory around separating these things still confuses me. I come from a background of developing non game web applications so I am versed in more MVC like patterns and am stuck in that mindset as I approach game programming.

I want to do things like abstract my game by having, for example, a game board class that contains the data for a grid of tiles with instances of a tile class that each contain properties. I can give my draw loop access to this and have it draw the game board based on the properties of each tile on the game board, but I don't understand where exactly animation should go. As far as I can tell, animation sort of sits between the abstracted game logic (model) and the draw loop (view). With my MVC mindset, it's frustrating trying to decide where animation is actually supposed to go. It would have quite a bit of data associated with it like a model, but seemingly needs to be very closely coupled with the draw loop in order to have things like frame independent animation.

How can I break out of this mindset and start thinking about patterns that make more sense for games?

# Answer
Animation can still perfectly be split between logic and rendering. The abstract data state of animation would be the information that is necessary for your graphics API to render the animation.

In 2D games for example,that could be a rectangle area which marks the area that displays the current part of your sprite sheet that needs to be drawn (when you have a sheet consisting of lets say 30 80x80 drawings containing the various steps of your character jumping, sitting down, moving etc.). It can also be any kind of data that you don't need for rendering, but maybe for managing the animation states themselves, like the time left until the current animation step expires or the name of the animation ("walking","standing" etc.) All of that can be represented any way you want. That's the logics part.

In the rendering part, you just do it as usual, get that rectangle from your model and use your renderer to actually do the calls to the graphics API.

In code (using C++ syntax here):

```
class Sprite //Model
{
    private:
       Rectangle subrect;
       Vector2f position;
       //etc.

    public:
       Rectangle GetSubrect()
       {
           return subrect;
       }
       //etc.
};

class AnimatedSprite : public Sprite, public Updatable //arbitrary interface for classes that need to change their state on a regular basis
{
    AnimationController animation_controller;
    //etc.
    public:
        void Update()
        {
            animation_controller.Update(); //Good OOP design ;) It will take control of changing animations in time etc. for you
            this.SetSubrect(animation_controller.GetCurrentAnimation().GetRect());
        }
        //etc.
};

```

That's the data. Your renderer will take that data and draw it. Since both normal Sprites and animated ones are drawn the same way, you can use polymorphy here!

```
class Renderer
{
    //etc.
    public:
       void Draw(const Sprite &spr)
       {
           graphics_api_pointer->Draw(spr.GetAllTheDataThatINeed());
       }
};

```

TMV:

> I came up with another example. Say you have an RPG. Your model that represents the world map, for example, would probably need to store the character's position in the world as tile coordinates on the map. However, when you move the character, they walk a few pixels at a time to the next square. Do you store this "between tiles" position in an animation object? How do you update the model when the character has finally "arrived" at the next tile coordinate on the map?

The world map doesn't know about the players position directly (it doesn't have a Vector2f or something like that which directly stores the players position=, instead it has a direct reference to the player object itself, which in turn derives from AnimatedSprite so you can pass it to the renderer easily, and gets all necessary data from it.

In general though, your tilemap shouldn't be able to do just everything - I'd have a class "TileMap" which takes care of managing all the tiles, and maybe it also does collision detection between objects that I hand over to it and the tiles on the map. Then, I'd have another "RPGMap" class, or however you'd like to call it, which has both a reference to your tilemap and the reference to the player and makes the actual Update() calls to your player and to your tilemap.

How you want to update the model when the player moves depends on what you want to do.

Is your player allowed to move in between tiles independently (Zelda style)? Simply handle the input and move the player accordingly every frame. Or do you want the player to press "right" and your character automatically moves one tile to the right? Let your RPGMap class interpolate the players position until he arrives at his destination and meanwhile lock all the movement-key input handling.

Either way, if you want to make it easier on yourself, all of your models will have Update() methods if they actually need some logic to update themselves (instead of just changing values of variables) - You don't give away the controller in the MVC pattern that way, you just move the code from "one step above" (the controller) down to the model, and all the controller does is call this Update() method of the model (The controller in our case would be the RPGMap). You can still easily swap out the logics code - you can just directly change the code of the class or if you need completely different behaviour, you can just derive from your model class and only override the Update() method.

That approach reduces method calls and things like that a lot - which used to be one of the main disadvantages of the pure MVC pattern (you end up calling GetThis() GetThat() very very often) - it makes the code both longer and a tiny bit harder to read and also slower - even though that might be taken care of by your compiler who optimizes a lot of stuff like that.
> 6 votes

# Answer
I can develop on this if you wish, but I have a central renderer that gets told to draw in the loop. Rather than

```
handle input

for every entity:
    update entity

for every entity:
    draw entity

```

I have a system more like

```
handle input (well, update the state. Mine is event driven so this is null)

for every entity:
    update entity //still got game logic here

renderer.draw();

```

The renderer class simply holds a list of references to drawable components of objects. These are assigned in the constructors for simplicity.

For your example, I would have a GameBoard class with a number of Tiles. Each tile obviously knows its position, and I assume some kind of animation. Factor that out into some sort of Animation class that the tile owns, and have it pass a reference of itself to a Renderer class. There, all separated. When you update Tile, it calls Update on the animation..or updates it itself. When `Renderer.Draw()` is called, it draws the animation.

Frame independent animation shouldn't need too much to do with the draw loop.
> 2 votes

# Answer
I've been learning the paradigms myself lately, so if this answer is incomplete, I'm sure someone will add to it.

The methodology that seems to make the most sense for game design is to separate the logic from the screen output.

In most cases you would want to use a multi threaded approach, if you're not familiar with that topic, it's a question all its own, here's wiki's primer. Essentially you want your game logic to execute in one thread, locking variables that it needs to access in order to ensure the data integrity. If your logic loop is incredibly fast (super mega animated 3d pong?) you can try to fix the frequency the loop executes by sleeping the thread for small durations (120 hz has been suggested in this forum for game physics loops). Concurrently, the other thread is redrawing the screen (60 hz has been suggested in other topics) with the updated variables, again asking for a lock on the variables before it accesses them.

In that case, animations or transitions, etc, go into the drawing thread but you must signal through a flag of some sort (a global state variable perhaps) that the game logic thread must do nothing (or do something different ... setup the new map parameters perhaps).

Once you get your head around the concurrency, the rest is fairly comprehensible. If you don't have experience with concurrency I strongly suggest you write a few simple test programs so that you can understand how the flow happens.

Hope this helps :)

\[edit\] On systems that don't support multithreading, the animation can still go into the draw loop, but you want to set the state in such a way to signal to the logic that something different is occurring and don't keep processing the current level/map/etc...
> 0 votes

---
Tags: software-engineering, android, design-patterns
---


# Question
Title: How can I test shaders for nVidia on an ATi system?
I and our other devs have ATi graphics cards. However we have encountered that some shaders that compile without warnings on ATi don't compile at all on nVidia. The problems are trivial to fix, but often go unseen.

My question is, how can I make sure that my shaders will compile everywhere?

# Answer
Have a bunch of different systems for testing, I can't imagine a way of getting around that.

Optimally you should have a card from every graphics generation.

* GeForce 7000 series
* GeForce 8000 series / 9000 series / 250
* GeForce 260 / 275 / 280 / 285 / 295
* GeForce 400 series / 500 series
* Radeon X1000 series
* Radeon HD 2000 series
* Radeon HD 3000 series
* Radeon HD 4000 series
* Radeon HD 5000 series / HD 6000 series
* Intel GMA X series
* Intel HD series

If you want a really thorough testing you can multiboot all these machines with a bunch of different operating system and driver configurations, but for a more manageable number of tests you can do multiple operating systems and drivers on just one machine each.

Apart from all this, why don't you diversify your dev machines? Maybe you'll also discover more subtle bugs earlier.

Even if you can find a way of testing this exact subtlety there is no way you'll be able to test all the things you should without getting at least one nVidia card.
> 1 votes

---
Tags: opengl, shaders, glsl, compatibility, nvidia
---


# Question
Title: XNA - just a few more characters accepted in a SpriteFont
I have a SpriteFont in XNA, which has the standard 126 characters that are usable.

However i would like to use the "ಠ" symbol in the game.

So is there anyway of adding just a few more symbols that the spritefont accepts?

# Answer
> 13 votes
Modify the sprite font file. It's XML. Double click it in Visual Studio.

Towards the bottom of the default file is a the following:

```
<CharacterRegions>
  <CharacterRegion>
    <Start> </Start>
    <End>~</End>
  </CharacterRegion>
</CharacterRegions>

```

Your character is unicode code point U+0CA0, which in decimal is 3232. So add another character region tag that contains it:

```
  <CharacterRegion>
    <Start>ಠ</Start>
    <End>ಠ</End>
  </CharacterRegion>

```

This assumes that the ಠ symbol exists in the font you are using.

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


# Question
Title: How do I create a 3D model based on 2D drawings?
I'm a programmer. I have a great draftsman, but I don't know how to take his drawings to 3D.

My gut feeling is to have him draw different view angles, then work based on those, adding each dimension to the model turn. But really I'm just guessing here.

How do I do this methodically and correctly?

# Answer
As Tim Holt said, you need a 3D modeler in order to translate the 2D designs into models. However, if you're willing to try your hand at modeling, the basic process generally goes like this:

1. Add the image you're working from to the 3D scene so that you can add vertices in front of it. Your modeling program may have a built in method for this, otherwise use a regular plane with the image as a texture.
2. Set your view so that you are viewing the image flat (camera's direction vector is perpendicular to the image)
3. If possible, follow step 1 and 2 for your alternative-angle images at an appropriate angle to the original and set up extra camera views so you can see both or all images from the correct angle simultaneously.
4. Start adding vertices to your model that match up to the image outlines.
5. Use your supplementary images to make any additional vertices you need, and to position your vertices from step 4 in the third dimension.

There are tool-specific and more in-depth tutorials available on the web.
> 12 votes

# Answer
The solution is not in coding, it's in talent. Bring someone into your team who's a 3d modeller. They will be able to take the 2d concept sketches and turn them into 3d models, just as you (as a programmer) can take someone's idea of an algorithm and turn it into code.
> 7 votes

# Answer
I recommend looking at Google Sketchup. It's a 3D modelling program that's mostly aimed at architectural modelling; it lends itself well to starting with a layout or side projection and extruding from that. It's got a bunch of tutorials and can export in several useful ways.

However, Sketchup will work best if you're designing 3D environments, not things like humanoid models. It doesn't really do the same sort of vertex-and-polygon-based archetype as typical 3D modellers, and I don't believe it has any sort of skeleton or animation functionality at all.

If you're feeling adventurous, I recommend trying Blender, like some responders have suggested, since it's free. Look for tutorials online. It will take a lot of learning, more than Sketchup, but it's a fully-featured modelling program.
> 2 votes

---
Tags: 2d, 3d, models, hand-drawn
---


title: Pen tablet input for FPS

text:
# Question
Title: Pen tablet input for FPS
So in my FPS camera look code, I have something like this:

```
window->camera->stepYaw( getMouseDx()*speed ) ; // mouseDx is mouse change since last frame
window->camera->stepPitch( getMouseDy()*speed ) ;

```

This works fine on a normal mouse. But with pen input, its very very janky and radical.

How should one control an FPS camera from pen tablet input instead of traditional mouse?

# Answer
On Windows from C++

```
// usFlags is ALWAYS ABSOLUTE, see
if( raw->data.mouse.usFlags == MOUSE_MOVE_RELATIVE )
{
  // its a 0 flag so
  // this is am real mouse

  // lLastX and lLastY are relative to last pos
}
else if( raw->data.mouse.usFlags | MOUSE_MOVE_ABSOLUTE )
{
  // its a tablet or positioning device
  // 1 .. 65537, ACROSS THE DESKTOP

  // get the relative change in position
  // to turn it into a pixel count,
  // you have to have the old values of lLastX
  // and lLastY (in the last call to this fcn).
}

```
> -1 votes

# Answer
Typically an FPS gets the relative mouse movement by locking the mouse to the center of the screen (put the cursor on center, wait a frame, get mouse position and repeat) with a tablet however you set the absolute position of the mouse and as such you can't lock the mouse.

What I would do is not lock the mouse cursor but calculate the difference between the current absolute position and the previous absolute position. One caveat however is if you take the pen off and move it somewhere else (for example if you reach the edge of the tablet) this is fixable by not returning any movement if the movement is larger than *some number*.

Something like this (pseudocode):

```
deltaX = currentX - previousX
previousX = currentX
if deltaX > 20 deltaX = 0

```
> 2 votes

# Answer
In essence PenTablet provides absolute coordinates for X and Y, not a relative like Mouse does. This means you can perform SetCursor(x,y) in your code - Mouse will not know a difference, and PenTablet will "ignore" it.

Now it depends on how you compute your mouseDx. If you stick the mouse on buttonDown or just hide it? Please provide more code and I will expand my answer according to it.
> 1 votes

---
Tags: input, windows
---


title: Random Position between ranges

text:
# Question
Title: Random Position between ranges
Does anyone have a good algorithm for generating a random y position for spawning a block, which takes into account a minimum and maximum height, allowing player to to jump on the block.

Blocks will continually be spawned, so the player must always be able to jump onto the next block, bearing in mind the minimum position which would be the ground, and the maximum which would the players jump height bearing in mind the ceiling

# Answer
You just have to generate some boundaries for the blocks you are going to make, maybe due to the last block or other limitations in your game; for example, if your game has some level of ground, no block should start below ground level. Having those parameters set, it's really easy to create a random number which has all the features you required.

In your game example: imagine a block starting at `NewStartPositionY` and ending at `NewEndPositionY`. We know `GroundLevel` is the ground height (you consider it as zero) and `CeilingLevel` is the ceiling height. A character might jump at most `MaxJump` units. Some other parameters might be `PlayerHeight`, which is the height of the character, and `LastStartPositionY` and `LastEndPositionY` which define the last block, and let's take `MinimumBlockSize` as the minimum size of platform. Knowing all these values you can set your boundaries :

```
// to initialize boundaries
NewStartPositionY = GroundLevel;
NewEndPositionT = min (LastEndPositionY + MaxJump,  CeilingLevel - PlayerHeight)
// to set actual random value
NewStartPositionY = random (NewEndPositionY - NewStartPositionY - MinimumBlockSize)
NewEndPositionY = random (NewEndPositionY - NewStartPositionY - MinimumBlockSize) + NewStartPositionY + MinimumBlockSize;

```

---

**Edit:**

Here is what the above code actually does; I just expanded it since it seems to cause many a headache! (It just needs more variables and does more operations but the result is the same.)

```
// -- first we define what are the boundaries of generated blocks
// it's obvious that no block can be under the ground level
MinimumBoundaryY = GroundLevel;
// we need to make sure player can jump over the new level
// and at the same time we have to make sure player can go over it
// and not hit the ceiling so we choose the minimum value from them both
MaximumBoundaryY = min(lastEndPositionY + maxJump, CeilingLevel - PlayerHeight)
// --now initialize startPosition of the Block
// we want the block to at least have `MinimumBlockSize` height
// so the start position should be somewhere between `minimumBoundaryY`
// and `MaximumBoundaryY - MinimumBlockSize`
StartYRange = MaximumBoundaryY - MinimumBoundaryY - minimumBlockSize;
// and now we a random value we assign the actual value of new StartPosition
newStartPositionY = random() % StartYRange + MinimumBlockSize;
// --now as the last part we have to calculate endPosition of the new block
// again we first calculate the range for endPosition value.
// note that end position should always be somewhere between
// `beginPositionY + MinimumBlockHeight` and `maximumBlockHeight` so the range well be
EndYRange = MaximumBoundaryY - newStartPositionY - MinimumBlockHeight;
// in the end just set the EndPosition of the Block, we now it's variation range
// and we know it's the minimum valid value is `beginPositionY + MinimumBlockheight`
NewEndPositionY = random() % EndYRange + newStartPositionY + MinimumBlockHeight;

```

Hope this second piece of code helps you all understand what my code does! (and change your downvotes to upvotes :D).
> -2 votes

# Answer
@Gajet's answer is impossible to follow (so I'm not even convinced it will work), and what I think @The Communist Duck meant his solution to be...

```
block_y = ground_y + random() % (previousBlock_y + playerJumpHeight)

```

...will be heavily biased towards creating blocks with y-values centered around `ground_y + playerJumpHeight`.

The easiest way to produce more satisfying results would be, rather than generate a height between `ground_y` and `previousBlock_y + playerJumpHeight`, generate a random value between `previousBlock_y - playerJumpHeight` and `previousBlock_y + playerJumpHeight`.

Of course, since we want to take `ground_y` and `maxBlockHeight` into consideration also, we *really* want to find a random value between `max(ground_y, previousBlock_y - playerJumpHeight)` and `min(maxBlockHeight, previousBlock_y + playerJumpHeight)`. This will skew our distribution a bit *(biased towards the center of the screen)*, but not enough to be noticeable.

The simplest way to do this would be

```
//delta_y is a random number between -/+ playerJumpHeight
min_y = max(ground_y, previousBlock_y - playerJumpHeight)
max_y = min(maxBlockHeight, previousBlock_y + playerJumpHeight)
range_y = max_y - min_y
block_y = random() % range_y + min_y

```

If you then want the block to have a random height as well, just generate a random number between `ground_y` and `block_y` to be the height.

---

**\[Edit\]** There *is* a way to have a probability of jumping down by any amount, while still giving the player equal probability of being anywhere on the screen at any given point.

Thanks to Didier Piau on the math forums for figuring this out. The full explanation is complex, so I'll leave it out; the curious can visit that page, from which I generalized this algorithm. The algorithm itself is actually pretty simple, though.

```
int getNextBlockHeight()
{
    int playingFieldHeight = screen_y - ground_y;
    int canonicalBlockMaxHeight = playingFieldHeight - playerHeight;
    int nextBlockMaxHeight = min(currentBlockHeight + playerJumpHeight, canonicalBlockMaxHeight);

    //Let's divide the screen vertically into chunks of size playerJumpHeight.
    //This code makes it so that each chunk is approximately twice as likely as being chosen
    //as the previous chunk
    float canonicalHeightRatio = (float)canonicalBlockMaxHeight / playerJumpHeight;
    float nextHeightRatio = (float)nextBlockMaxHeight / playerJumpHeight;

    //The following looks complicated, but really it just ensures that the minimum is 0, the maximum is
    //nextBlockMaxHeight, and everything in between is mapped logarithmically
    float randomMin = pow(2, -canonicalHeightRatio);
    float randomMax = pow(2, nextHeightRatio-canonicalHeightRatio);
    float randomVal = randFloat(randomMin, randomMax);
    float randomHeightRatio = log2(randVal)+canonicalHeightRatio;
    return (int)(randomHeightRatio*playerJumpHeight) + ground_y;
}

//Return the log-base-2 of a number
const float log_of_2 = log(2);
float log2(float value)
{
    return log(value) / log_of_2;
}

//Generates a random floating-point number between min and max
float randFloat(float min, float max)
{
    float randomNormalized = (float)rand()/RAND_MAX; //Between 0.0 and 1.0
    return randomNormalized*(max-min) + min;
}

```
> 6 votes

# Answer
Generate a random `y` value between a ground y value `g` and a max height `m`. `m` is simply `g+character jump height`.

I don't know how Obj-C's random works, but usually you'll want something like:

`block_y = (random() % m) + g;`
> 4 votes

# Answer
Coincidentally, I wrote a random number generator in Objective-C a few weeks ago to help teach myself the language.

If you're using it, you can generate numbers between two values using the following messages on the `Random` class:

```
/* Inclusive low to exclusive high. */
- (int32_t)uniformIntFrom:(int32_t)low to:(int32_t)high;
- (uint32_t)uniformUnsignedFrom:(uint32_t)low to:(uint32_t)high;

/* Inclusive low to inclusive high. */
- (float)uniformFloatFrom:(float)low to:(float)high;
- (double)uniformDoubleFrom:(double)low to:(double)high;

/* Inclusive 0 to exclusive 1. */
- (float)uniformFloat;
- (double)uniformDouble;

```

If you are curious about how to generate a good random number between two values, this is the main portion of the source code for it:

```
uint32_t range = high - low;
uint32_t reject;
uint32_t n;

if (range < 2)
    return low;

/* Trick borrowed from OpenBSD's arc4random_uniform. Figure out
 * the size of the bias given the requested range, and throw away
 * numbers within the biased range.
 */

if (range > 0x80000000)
    reject = 1 + ~range;
else
    reject = ((max - (range * 2)) + 1) % range;

do {
    n = [engine next];
} while (n < reject);
return low + (n % range);

```

Where `[engine next`\] gives me a number between 0 and `max` (which is usually UINT\_MAX, i.e. 232-1).
> 3 votes

# Answer
Not sure how this translates in Obj-C but here's my version for C++. You want to normalize your random value before turning it into a specific range so the rand() stays uniform.

```
float randomHeight( float heightMin, float heightMax )
{
    float normRand = rand() / (float) RAND_MAX;
    float range = normRand * (heightMax - heightMin);
    return range + heightMin;
}

```

Note that rand() returns values from 0 to RAND\_MAX so if you can find the equivalent in Obj-C, you can just replace these values with yours.
> 2 votes

# Answer
It sounds like what you want is just a 1D string of Perlin Noise. This is a very well documented problem and there are several examples available on the internet.
> -3 votes

---
Tags: 2d, random, objective-c, platform
---


# Question
Title: How can I get six Xbox controllers to provide input to an HTML5 game?
I'm creating a six player HTML 5 game designed to be played locally (Red Ice).

I've previous set up handling 7 Wiimotes using something along the lines of Joy2Key to map each input for each player to a separate keyboard key, but Wiimotes are pretty hard on the hands for these types of games and not very ergonomic so I thought I'd try and get Xbox controller support.

I don't believe that any simple key mapping solution will work due to the nature of the directional stick.

My inclination is that this will require a browser plugin and if so I'd prefer to write the plugin for Google Chrome.

How do I create a Chrome browser plugin to handle multiple Xbox controllers or is there some other way?

Please do not answer this question saying it can't be done, because it absolutely can.

EDIT: I don't believe any keymapping/mouse simulating solution will work unless it can reliably distinguish six axis of inputs, one per player.

# Answer
> 1 votes
I've created Boomstick, an NPAPI and ActiveX plugin that grants JavaScript an API to access native Joysticks and Gamepads. Assuming that 2 XBox 360 Wireless Gaming Receivers can each handle 4 controllers, Boomstick will grant HTML5 access to the 8 controllers. This works on all major platforms (Windows, Mac, and Linux) and browsers (Chrome, Firefox, IE).

# Answer
> 2 votes
Assuming your controllers are wireless, the first thing you'll need is the Xbox 360 Wireless Gaming Receiver. It's a $20 USB device that lets you use your Xbox 360 controllers as input devices.

Once all that's set up it's a matter of syncing the controllers with the dongle and binding the buttons and sticks of each controller to different keypresses.

Good luck!

---
Tags: html5, input, xbox-controller
---


# Question
Title: Do I need the 'w' component in my Vector class?
Assume you're writing matrix code that handles rotation, translation etc for 3d space.

Now the transformation matrices have to be 4x4 to fit the translation component in.

However, you don't actually *need* to store a `w` component in the vector do you?

Even in perspective division, you can simply compute and store `w` outside of the vector, and perspective divide before returning from the method.

For example:

```
// post multiply vec2=matrix*vector
Vector operator*( const Matrix & a, const Vector& v )
{
  Vector r ;
  // do matrix mult
  r.x = a._11*v.x + a._12*v.y ...

  real w = a._41*v.x + a._42*v.y ...

  // perspective divide
  r /= w ;

  return r ;
}

```

Is there a point in storing `w` in the Vector class?

# Answer
**EDIT Disclaimer**: For convenience in this answer vectors with w==0 are called vectors and with w==1 are called points. Although as FxIII pointed out, that is not a mathematically correct terminology. However, since the point of the answer is not the terminology, but the need to distinguish both types of vectors, I'll stick to it. For practical reason this convention is widely used in game-development.

---

It is not possible to distinguish between vectors and points without a 'w' component. It is 1 for points and 0 for vectors.

If vectors are multiplied with a 4x4 affine transformation-matrix that has a translation in its last row/column, the vector would also be translated, which is wrong, only points must be translated. The zero in the 'w' component of a vector takes care of that.

Highlighting this part of the matrix-vector multiplication makes it more clear:

```
    r.x = ... + a._14 * v.w;
    r.y = ... + a._24 * v.w;
    r.z = ... + a._34 * v.w;
    r.w = ... + a._44 * v.w;

a._14, a._24 and a._34 is the translational part of the affine matrix.
Without a 'w' component one has to set it implicitly to 0 (vector) or to 1 (point)

```

I.e. it would be wrong to translate a vector, for instance a rotation axis, the result is simply wrong, By having it's 4th component zero you can still use the same matrix that transforms the points to transform the rotation axis and the result will be valid and its length is preserved as long as there is no scale in the matrix. That is the behavior you want for vectors. Without the 4th component you would have to create 2 matrices (or 2 different multiplication functions with an implicit 4th parameter. and make 2 different function calls for points and vectors.

In order to use the vector registers of modern CPUs (SSE, Altivec, SPUs) you have to pass 4x 32 bit floats anyway (its a 128 bit register), plus you have to take care of the alignment, usually 16 bytes. So you don't have the chance to safe the space for the 4th component anyway.

---

**EDIT:** The answer to the question is basically

1. **Either store the w-component: 1 for positions and 0 for vectors**
2. **Or call different matrix-vector multiplication functions and implicitly pass the 'w' component by choosing one of either functions**

One must pick one of them, it is not possible to store only {x, y, z} and still use only one matrix-vector multiplication function. XNA for example uses the latter approach by having 2 Transform functions in its Vector3 class, called `Transform` and `TransformNormal`

Here is a code example that shows both approaches and demonstrates the need to distinguish both kind of vectors in 1 of the 2 possible ways. We will move a game-entity with a position and a look-direction in the world by transforming it with a matrix. If we don't use the 'w' component, we can't use the same matrix-vector multiplication anymore, as this example demonstrates. If we do it anyway, we will get a wrong answer for the transformed `look_dir` vector:

```
#include <cstdio>
#include <cmath>

struct vector3
{
    vector3() {}
    vector3(float _x, float _y, float _z) { x = _x; y = _y; z = _z; }
    float x, y, z;
};

struct vector4
{
    vector4() {}
    vector4(float _x, float _y, float _z, float _w) { x = _x; y = _y; z = _z; w = _w; }
    float x, y, z, w;
};

struct matrix
{
    // convenience column accessors
    vector4&        operator[](int col)         { return cols[col]; }
    const vector4&  operator[](int col) const   { return cols[col]; }
    vector4 cols[4];
};

// since we transform a vector that stores the 'w' component,
// we just need this one matrix-vector multiplication
vector4 operator*( const matrix &m, const vector4 &v )
{
    vector4 ret;
    ret.x = v.x * m[0].x + v.y * m[1].x + v.z * m[2].x + v.w * m[3].x;
    ret.y = v.x * m[0].y + v.y * m[1].y + v.z * m[2].y + v.w * m[3].y;
    ret.z = v.x * m[0].z + v.y * m[1].z + v.z * m[2].z + v.w * m[3].z;
    ret.w = v.x * m[0].w + v.y * m[1].w + v.z * m[2].w + v.w * m[3].w;
    return ret;
}

// if we don't store 'w' in the vector we need 2 different transform functions
// this to transform points (w==1), i.e. positions
vector3 TransformV3( const matrix &m, const vector3 &v )
{
    vector3 ret;
    ret.x = v.x * m[0].x + v.y * m[1].x + v.z * m[2].x + 1.0f * m[3].x;
    ret.y = v.x * m[0].y + v.y * m[1].y + v.z * m[2].y + 1.0f * m[3].y;
    ret.z = v.x * m[0].z + v.y * m[1].z + v.z * m[2].z + 1.0f * m[3].z;
    return ret;
}

// and this one is to transform vectors (w==0), like a direction-vector
vector3 TransformNormalV3( const matrix &m, const vector3 &v )
{
    vector3 ret;
    ret.x = v.x * m[0].x + v.y * m[1].x + v.z * m[2].x + 0.0f * m[3].x;
    ret.y = v.x * m[0].y + v.y * m[1].y + v.z * m[2].y + 0.0f * m[3].y;
    ret.z = v.x * m[0].z + v.y * m[1].z + v.z * m[2].z + 0.0f * m[3].z;
    return ret;
}

// some helpers to output the results
void PrintV4(const char *msg, const vector4 &p )  { printf("%-15s: %10.6f %10.6f %10.6f %10.6f\n",  msg, p.x, p.y, p.z, p.w ); }
void PrintV3(const char *msg, const vector3 &p )  { printf("%-15s: %10.6f %10.6f %10.6f\n",         msg, p.x, p.y, p.z); }

#define STORE_W     1

int main()
{
    // suppose we have a "position" of an entity and its
    // look direction "look_dir" which is a unit vector

    // we will move this entity in the world

    // the entity will be moved in the world by a translation
    // in x+5 and a rotation of 90 degrees around the y-axis
    // let's create that matrix first

    // the rotation angle, 90 degrees in radians
    float a = 1.570796326794896619f;
    matrix moveEntity;
    moveEntity[0] = vector4( cos(a), 0.0f, sin(a), 0.0f);
    moveEntity[1] = vector4(   0.0f, 1.0f,   0.0f, 0.0f);
    moveEntity[2] = vector4(-sin(a), 0.0f, cos(a), 0.0f);
    moveEntity[3] = vector4(   5.0f, 0.0f,   0.0f, 1.0f);

#if STORE_W

    vector4 position(0.0f, 0.0f, 0.0f, 1.0f);
    // entity is looking towards the positive x-axis
    vector4 look_dir(1.0f, 0.0f, 0.0f, 0.0f);

    // move the entity using the matrix
    // we can use the same function for the matrix-vector multiplication to transform
    // the position and the unit vector since we store 'w' in the vector
    position = moveEntity * position;
    look_dir = moveEntity * look_dir;

    PrintV4("position", position);
    PrintV4("look_dir", look_dir);

#else

    vector3 position(0.0f, 0.0f, 0.0f);
    // entity is looking towards the positive x-axis
    vector3 look_dir(1.0f, 0.0f, 0.0f);

    // move the entity using the matrix
    // we have to call 2 different transform functions one to transform the position
    // and the other one to transform the unit-vector since we don't
    // store 'w' in the vector
    position = TransformV3(moveEntity, position);
    look_dir = TransformNormalV3(moveEntity, look_dir);

    PrintV3("position", position);
    PrintV3("look_dir", look_dir);

#endif

    return 0;
}

```

Initial Entity state:

```
position       :   0.000000   0.000000   0.000000   1.000000
look_dir       :   1.000000   0.000000   0.000000   0.000000

```

Now a transformation with a translation of x+5 and a rotation of 90 degrees around the y-axis will be applied to this entity. The correct answer after the tranformation is:

```
position       :   5.000000   0.000000   0.000000   1.000000
look_dir       :   0.000000   0.000000   1.000000   0.000000

```

We will only get the correct answer if we distinguish vectors with w==0 and positions with w==1 in one of the above presented ways.
> 31 votes

# Answer
If you're making a Vector class, then I presume the class will store the description of a 3D vector. 3D vectors have x, y, and z magnitudes. So unless your vector needs an arbitrary w magnitude, no, you won't store it in the class.

There is a big difference between a vector and a transformation matrix. Given that both DirectX and OpenGL deal with matrices for you, I don't typically store a 4x4 matrix in my code; rather, I store Euler rotations (or Quaternions if you'd like - which coincidentally do have a w component) and x,y,z translation. The translation is a vector if you'd like, and the rotation technically would fit in a vector as well, where each component would store the rotation amount around its axis.

If you want to dive a bit deeper into the math of a vector, a Euclidean vector is just a direction and a magnitude. So typically this is represented by a triplet of numbers, where each number is the magnitude along an axis; its direction is implied by the combination of these three magnitudes, and the magnitude can be found with the Euclidean distance formula. Or, sometimes it really is stored as a direction (a vector with length=1) and a magnitude (a float), if that's what is convenient (e.g. if the magnitude changes more often than the direction, it may be more convenient to just change that magnitude number than to take a vector, normalize it, and multiply the components by the new magnitude).
> 4 votes

# Answer
The fourth dimension in 3D vector is used to compute the affine transformations that will be impossible to compute using matrixes alone. The space remains three-dimensional so this mean that the fourth is mapped in the 3d space in some way.

Map a dimensions means that different 4D vectors indicates the same 3D point. The map is that if **A** = \[x',y',z'.w'\] and **B** = \[x",y",z",w"\] they represents the same point if x'/x" = y'/y" = z'/z" =w'/w" =α i.e. the component are proportional for the same coefficient α.

Said that you can express a point - say (1,3,7) - in infinite manners like (1,3,7,1) or (2,6,14,2) or (131,393,917,131) or in general (α·1,α·3,α·7,α).

This means that you can scale a 4D vector to another representing the same 3D point so that w = 1: the form (x,y,z,1) is the canonical form.

When you apply a matrix to this vector you may obtain a vector that has not the w = 1, but you can always scale the results to store it in canonical form. So the answer appears to be *"you should use 4D vectors when doing math but don't store the fourth component"*.

This is quite true but there are some points that you **can't** put in canonical form: points like (4,2,5,0). Those points are special ones, they represent directed infinite point and can be normalized to unit vector consistently: you can safely go to the infinite and return (even twice) without being Chuck Norris. You will get a miserable division by zero if you try to force those vectors in canonical form.

Now you know, so the choice is yours!
> 4 votes

# Answer
Yes, you do. Your transformation is incorrect for some kinds of vector. You can see this in the D3DX mathematical library- they have two different matrix-vector multiplication functions, one for w = 0 and one for w = 1.
> 1 votes

# Answer
Depends on what you want and need. :)

I'd store it, b/c it IS necessary for transforms and such (you can't multiply a 3 vector with a 4x4 matrix), though if you always just have a w of 1, I guess you could just fake it.
> 0 votes

---
Tags: mathematics, vector, projection
---


title: loading 3d model data into buffers

text:
# Question
Title: loading 3d model data into buffers
I am using assimp to load 3d model data. I have noticed that each loaded model is made up of different meshes. I was wondering should each mesh have it's own vertex/index buffer or should there just be one for the whole model? From looking through the index data that is loaded it seems to suggest that I will need a vertex buffer per mesh but I'm not 100% sure. I am using C++ and DirectX9

Thank you,

Mark

# Answer
> 3 votes
Most games nowadays use a vertex buffer for each mesh. It's true that having a single vertex buffer for the whole model reduces the number of draw calls, which is more efficient, but it tends to make your design more complex. Here's a discussion about this

By the way, you might get better answers at GameDev.net (about this kind of stuff, that is)

# Answer
> 3 votes
Having all your data in the same vertex buffer lets you batch all those objects in a single draw call, as long as they have the same render states.

The game would have to be draw call bound for that technique to give you any performance gain and this won't happen before having thousands of calls per seconds on modern hardware.

Batching introduces a lot of complexity to your engine and will force you to defer most rendering, which will introduce some performance penalities.

Conclusion, don't mess with that until strictly necessary, that is, you profiled your game and it is clearly draw call bound.

---
Tags: c++, models, 3d, directx
---


# Question
Title: Outputting wrong colours from pixel shader in Direct3D
The output from the pixel shader in Direct3D is four floats, normalized 0-1 for each channel (RGBA). But what happens if these floats haven't been normalized correctly and are above 1?

# Answer
> 1 votes
If you're target surface is a floating point variety (HDR rendering for example) then it just outputs the color; during later processing your tone mapper decides how to move this full range down to 0..1 for display. If the surface is a typical RGB display it gets saturated (forced to a range 0..1).

In any case, it's a very easy test to do to see how it looks in real life =)

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


# Question
Title: What are the things to know before to start Game Development Using C++?
I just want to ask the question above ^. I want to learn C++ language. Someday i want to develop Game Application in c++ and I think it is so difficult for me to achieve that but im willing to learn and achieve that goals for may personal satisfaction and also for my CV as well. Can you give me a guidelines on how to achieve that goals? What are the languages that i need to learn together with c++? please help me.. Thank you!

# Answer
> 3 votes
You would probably be well served to know quite a bit

**First:** Game programming is easier than it's made out to be, it's not extremely simplistic, however it *is* easy to wrap your head around.

**Second:** C++ doesn't offer graphical abilities right off the bat. There is *nothing* in the standard library that does straight graphical stuff. Therefore you must learn another library/API in order to work with graphics.

**Third:** Be prepared to spend time learning. Be prepared to spend time troubleshooting. Be prepared for crappy programs/games, simply because you don't know better. You will get good with time, dedication, and will power.

**Fourth:** Game programming, and graphical programming in general is *AMAZING!* It's like creating worlds with your fingertips. Nothing is beyond reach.

# Answer
> 1 votes
I recommend you try to replicate a basic 2d game with libraries like SDL or SFML. For example, tetris, arkanoid. These libraries have many tutorials and manuals to do basic ( and less basic ) things. The best form to learn program games is to program games.

I think that c++ is a good language to begin because is not very high level like Java, or Python that abstract some concepts like memory management.

---
Tags: c++
---


# Question
Title: Regulating how much to draw based on how much was drawn last frame
\[Edit: I found an answer - see below\]

I have a 3D game world on an iPhone (limited graphics speed), and I'm already regulating whether I draw each shape on the screen based on it's size and distance from the camera. Something like...

```
if (how_big_it_looks_from_the_camera > constant) then draw

```

What I want to do now is also take into account how many shapes are being drawn, so that in busier areas of the game world I can draw less than I otherwise would.

I tried to do this by dividing how\_big\_it\_looks by the number of shapes that were drawn last frame (well, the square root of this but I'm simplifying - the problem is the same).

```
if (how_big_it_looks / shapes_drawn > constant2) then draw

```

But the check happens at the level of objects which represent many drawn shapes, and if an object containing many shapes is switched on, it increases shapes\_drawn lots and switches itself back off the next frame. It flickers on and off.

I tried keeping a kind of weighted average of previous values, by each frame doing something like `shapes_drawn_recently = 0.9 * shapes_drawn_recently + 0.1 * shapes_just_drawn`, but of course it only slows the flickering down because of the nature of the feedback loop.

Is there a good way of solving this?

My project is in Objective-C, but a general algorithm or pseudo-code is good too.

Thanks.

Edit: Please, I'm not asking for general advice on rendering performance. I need an answer to the specific question of how to take the shapes drawn in previous frames into account without getting flickering.

# Answer
Make each object remember whether it was drawn or not the previous frame.

It it was, be more lenient with it when deciding whether it should be drawn this frame than you would be if it hadn't been drawn the last frame. So...

```
if (how_big_it_looks * (1.2 if drawn last frame, 1.0 if not) / shapes_drawn > constant2) then draw

```

Voila, no flicker. Can't believe I didn't think of this sooner.
> 0 votes

# Answer
That's what Z buffering is for. Once you cull outside your frustum, and apply LoD to further-away objects, then you draw closest first. This will ensure that the graphics hardware can easily reject pixels that it doesn't need to draw.

Ultimately, if the shapes are part of your scene, then you can't not draw them and still get a correct image. You may try decomposing the resulting frames and see how many you actually needed.
> 0 votes

# Answer
First order of business is that you've discovered that it's best to measure before optimizing =) So now you know that it's object count that's killing your speed and not screen real estate.

Measure how many drawn objects your rendering can handle at the needed speed.

Now we need to test drawing distance, create a maximum distance at which you will draw objects and stress test your environment at different distance settings by running around and catching object counts. From this you will come up with a good distance to clip objects being drawn.

Now your basic render loop becomes one of throwing away any object that's farther away than that distance.

At this point most studios will pass that information along to the artists and designers so that they can make their data fit within the drawing parameters you've laid down.

Tip 1 is do do distance in units squared, this will avoid a sqrt() on every object every frame.
> 0 votes

---
Tags: 3d, mathematics, algorithm, animation, performance
---


title: Heightmap generation

text:
# Question
Title: Heightmap generation
I want to implement something like this to create a heightmap: 'Place a group of coordinates evenly across a map, and give them height values within a certain range. Repeatedly create coordinates between all of those coordinates, setting their height by deriving a value that was a mean value of all the surrounding coordinates.'

However, I'm not sure how I would go about it - I'm not sure how I could code the part where I place the coordinates in between the existing coordinates. Can anyone give any help/advice?

# Answer
Although it seems others also gave some answers in the comments, here's my experience:

There is a physics simulation problem known as heat flow/heat equation. That link gives you the whole idea about what you are going to simulate in that problem and there are many ways to create an optimized version of that simulation (just need a little Google search).

In my experience if you just give a constant heat value to some points and then leave the surface to rest for a while, you can get a very good height map based on the temperature of each point (just set each point height as its temperature). There are also some algorithms that generate the final result directly from the input values, but in your case I wouldn't recommend them unless you want to generate maps at runtime.

There are also some algorithms that give you the ability to modify the normal heat flows to get more complex heightmaps with less effort.
> 4 votes

---
Tags: maps, procedural-generation, heightmap
---


# Question
Title: How do I remove an object from the GUI class?
In the Esenthel engine, you can easily add an object like a button to your GUI class with `Gui += buttonInstance.create("click on me")`, but I'm just wondering how can you remove an on object from from GUI members.

As far as I have found, there is no such a method as `removeChild` or `getChildren`, or anything similar.

# Answer
Well, seeing as you use the += operator to add a button, perhaps you use the -= operator to remove one? So something like the following *pseudocode*:

```
mybutton = buttonInstance.create("click on me")
Gui += mybutton
// when it comes time to remove the button...
Gui -= mybutton

```

I'm just speculating here, but I would be surprised to find otherwise, because it would strike me as inconsistent for `+` to add but `-` not to remove.

---

According to Gajet in the comments, `Gui.desktop()->removeChild(mybutton)` is the proper code to remove a GUI element.
> 0 votes

---
Tags: esenthel-engine
---


# Question
Title: What AI for a resource management + combat?
I have a very simple game: 2 players (one human and a computer) and both have 1000 tokens. They must build an army. Depending on the type of soldier, it cost from 10 to 100 token to train one. Eventually I want them to attack the each other.

What would be the AI to use in that case? Is there any example around that I could learn from?

Thanks!

# Answer
> 3 votes
For this type of game, I'd like to refer you to a question that I asked before:

Basically the idea is that you keep a **power score for every unit** owned by a player. This score can be based on the unit's cost, the unit's stats or even a score that you chose arbitrarily for every unit.

Then you **calculate the power score of each player**, based on the power score of all their units.

Finally, you **compare the score** of the computer and the human player to make AI decisions.

For example, a computer with a Hard AI difficulty level could decide to always try to keep 20% more power than the player, or whatever. You can even put different random play styles like Aggressive, Defensive, etc. based on the power level of the opponent.

This technique certainly is not the best way to go and won't work with all games, but it sure is simple to implement and it did the trick for my AI demands. I always prefer to try out a simple solution first, and then move on to a more sophisticated one if the first approach looks too stupid or inappropriate.

# Answer
> 2 votes
I think that the Jesse Emond answer is a very good solution. It's simple and effective, the games purpose is that they look real, and many times this is achieved with simple rules.

But if you want to complicate more, you can try to investigate in the use of behavior trees. The use of a data-driven AI system in a plain-text format or a script language as Lua, Scheme or Python can be useful. Age of Empires use scripts to define the AI of the enemies that can be modified by the players. A sample:

```
(defrule
(or
    (goal TRAIN_UNIT TRUE)
    (goal NEED_MANGONEL TRUE)
)
(soldier-count >= POPULATION-5)
(can-train-with-escrow mangonel-line)
=>
(chat-local-to-self "train mangonel:Anti Scorpion")
(release-escrow wood)
(release-escrow gold)
(train mangonel-line)

```

# Answer
> 2 votes
The term AI is misused here. Well you need no AI. Hey i don't want to be rude! This is just an optimization problem that generally can be solved using greedy strategy. Alas, greedy solution means boring game: as the player gains experience he will adopt the same optimum greedy solution and your game becomes simply an advanced tic-tac-toe.

But don't worry! Let's talk about your problem and the possible strategies.

Here the (greedy) solution is to build as much strong-superpower-invincible-lastlevel unit as possible, because this kind of units overwhelm the others in term of power. Normally those units are slow to build so your base is left undefended until they are ready so your opponent can build a single demolition-unit and "the white wins in a move".

Then you start to think to build some "lower-level-but-faster-to-build" units before start to build the "final-weapon". This is still a greedy solution: you simply put a "defence" parameter in the objective function to minimize.

In general you should model your objective function leaving room for such parameters and let the computer to choose among a pre-fixed set of parameters or to choose randomly.

This gives to your otherwise booring optimum finder algoritm, a sort of character, a personality.

Once those parameters are choosed you should simply apply your favorite optimization algorithm.

---
Tags: ai
---


# Question
Title: Channelling an explosion along a narrow passage
I am simulating explosions in a 2D maze game.

If an explosion occurs in an open area, it covers a circular region (this is the easy bit.)

However if an explosion occurs in a narrow passage (i.e narrower than the blast range) then it should be "compressed", so that it goes further and also it should go around corners.

Ultimately, unless it is completely boxed-in, then it should cover a constant number of pixels, spreading in whatever direction is necessary to reach this total area.

I have tried using a shortest-path algorithm to pick the nearest N pixels to the origin avoiding walls, but the effect is exaggerated - the blast travels around corners too easily, making U-turns even when there is a clear path in another direction. I don't know whether this is realistic or not but it is counter-intuitive to players who assume that they can hide around a corner and the blast will take the path of least resistance in a different direction.

Is there a well-known (and fast) algorithm for this?

# Answer
Look at water/fluid simulations. The basic idea is that the area is divided into little cubes and each one has a velocity that it's pushing and a "pressure" gauge of how hard it's pushing into the adjoining cubes. All things being equal your explosion will grow outwards in a circle/sphere.

In a situation where the cubes can't expand in one direction (hallways) they'll end up pushing towards the way out.

This might be a good place to start: http://cowboyprogramming.com/2008/04/01/practical-fluid-mechanics/
> 2 votes

# Answer
I've done something to this similar recently in my game. Mine was for water flow, but it could be adapted for explosions. I've already adapted mine for lighting too :).

Essentially your explosion starts with a fixed amount of "blast", this is the total area your explosion covers. Through each iteration of moving your blast outwards you're subtracting from this total number of "blast" pixels. When the count runs out, your explosion stops.

When moving outward, the pixels lined up with the vector that's directly away from the blast is allowed to channel the most blast pixels, it has a higher throughput. This way the paths directly away from the blast get the most blast throughput. You can add rules that when the blast changes direction, the throughput is halved or whatever ends up working best. This ends up being very cellular automata. You define the rules of a cell, and they go out and do all the work.

In my image, black represents walls and you see the height of each cube defines the throughput and the color represents it's current pressure from red to white.

Basically you have a bucket of blast and you need to define the size and direction of the pipes leading away from the blast to flow that blast out. High pressure to low.

What inspired this algorithm for me was Dwarf Fortress and the way the water flowed with pressure. Obviously I don't know exactly how it was done in Dwarf Fortress, but I hacked together my own version that works pretty well. There's a little more info on how I did my algorithm and an interview with the Dwarf Fortress creator here.
> 5 votes

# Answer
This is a fluid dynamics problem, there is no simple way of solving this in a realistic fashion.

In any case, you only need "realism" as far as it gives the game the right feel.

Here is a couple of suggestions:

You might not want the area to stay exactly the same, that could get out of hand in very tight scenarios, so in your equation you could count far pixels as taking more of the blast. Eg. An explosion has 100 blast points, for the centre pixel you subtract 1 point, for those next to it 2, then 3 etc. so an explosion that has to reach far will spend more points per pixel on average.

For the corner thing, in your pathfinding you can add a penalty for corners, so any curve on the path will count as extra distance.
> 3 votes

# Answer
It is just an idea (physically incorrect but who cares?) what about a straight-first aproach?

Starting from the explosion the blasts move to the four directions losing a fixed amount of energy per tile, once a blast keep a direction it will follow it, ignoring the side apertures, until it find an obstacle:

if there are a single way to go(a turn), follow it and go ahead in that direction;

if there are two possible directions (T-intersection) split the blast in two (loosing the energy faster)

if is a dead end stop the blast (this will leave more energy for the other blasts).

Stop when you run out of energy. If no direction are possible but you have still some energy you may choose to stop anyway or to start to consider the skipped + intersections.

This may work if you are in a tiled world. If is not your case, you may try a ray casting aproach: working with growing circles testing if the pixel is in visibility from the explosion point. Once again each pixel set as blast decreases the explosion's energy so you have a stop criterion.
> 2 votes

---
Tags: physics
---


# Question
Title: Animating Tile with Blitting taking up Memory
I am trying to animate a specific tile in my 2d Array, using blitting. The animation consists of three different 16x16 sprites in a tilesheet. Now that works perfect with the code below. BUT it's causing memory leakage. Every second the FlashPlayer is taking up +140 kb more in memory. **What part of the following code could possibly cause the leak:**

```
//The variable Rectangle finds where on the 2d array we should clear the pixels
//Fillrect follows up by setting alpha 0 at that spot before we copy in nxt Sprite
//Tiletype is a variable that holds what kind of tile the next tile in animation is
//(from tileSheet)
//drawTile() gets Sprite from tilesheet and copyPixels it into right position on canvas

        public function animateSprite():void{

                    tileGround.bitmapData.lock();

                    if(anmArray[0].tileType > 42){
                        anmArray[0].tileType = 40;
                        frameCount = 0;
                    }
                    var rect:Rectangle = new Rectangle(anmArray[0].xtile * ts, anmArray[0].ytile * ts, ts, ts);
                    tileGround.bitmapData.fillRect(rect, 0);

                    anmArray[0].tileType = 40 + frameCount;
                    drawTile(anmArray[0].tileType, anmArray[0].xtile, anmArray[0].ytile);

                    frameCount++;

                    tileGround.bitmapData.unlock();
                }

        public function drawTile(spriteType:int, xt:int, yt:int):void{

                    var tileSprite:Bitmap = getImageFromSheet(spriteType, ts);
                    var rec:Rectangle = new Rectangle(0, 0, ts, ts);
                    var pt:Point = new Point(xt * ts, yt * ts);
                    tileGround.bitmapData.copyPixels(tileSprite.bitmapData, rec, pt, null, null, true);

                }

                public function getImageFromSheet(spriteType:int, size:int):Bitmap{

                    var sheetColumns:int = tSheet.width/ts;
                    var col:int = spriteType % sheetColumns;
                    var row:int = Math.floor(spriteType/sheetColumns);
                    var rec:Rectangle = new Rectangle(col * ts, row * ts, size, size);
                    var pt:Point = new Point(0,0);

                    var correctTile:Bitmap = new Bitmap(new BitmapData(size, size, false, 0));
                    correctTile.bitmapData.copyPixels(tSheet, rec, pt, null, null, true);
                    return correctTile;

                }

```

# Answer
The main memory consumption is because you're allocating new memory by creating a new Bitmap in your `getImageFromSheet` method.

You could write your code without any of these allocations. Instead of creating new Points and Rectanlges and Bitmaps every time, you could use two private member variables for the `Point` and `Rectangle` (where you simply change properties) and perform the `copyPixels` method directly from your sprite-sheet to your canvas. There's no need for the intermediate copy to a `Bitmap`. *If* you still want to pass around new bitmap-data, use `BitmapData` directly and not a `Bitmap` which is only a `DisplayObject` wrapper so that you can add it to the flash stage (which you don't need).

How long did you monitor your memory consumption? That allocated memory should actually be released by the garbage collector... but it would of course be better if you did not allocate that memory in the first place (since it's redundant).
> 2 votes

---
Tags: actionscript-3, memory-efficiency, bit-blit
---


# Question
Title: Switching between levels, re-initialize existing structure or create new one?
This is something I've been wondering for quite a while. When building games that exist out of multiple levels (platformers, shmups etc) what is the prefered method to switch between the levels?

Let's say we have a level class that does the following:

* Load data for the level design (tiles), enemies, graphics etc.
* Setup all these elements in their appriopate locations and display them
* Start physics and game logic

I'm stuck between the following 2 methods:

1: Throw away everything in the level class and make a new one, we have to load an entirely new level anyway!

2: pause the game logic and physics, unload all currents assets, then re-initialize those components with the level data for the new level.

They both have their pros and cons. Method 1 is alot easier and seems to make sense since we have to redo everything anyway. But method 2 allows you to re-use exisiting elements which might save resources and allows for a smoother transfer to the new level.

# Answer
> 2 votes
If your physics and game logic has little initialization or does not need any information from the last level stored, then the effect of throwing it away is negligible.

If the above is not true, or if you have a large amount of shared assets, I would pause the gameplay.

Another option is to copy the shared assets over to the new level and delete all the old unwanted ones, and do method 1. This probably is only a benefit if there is a large amount of shared assets.

# Answer
> 1 votes
It simply depends on the type of game you are working on. If it requires you to have smooth transitions or to stream the content of a level (like in crysis for example) then you should go for the second method.

This question is rather vague... For a platformer I'd recommend to create a new level from scratch, because you are likely to have seperate levels in seperate files...

---
Tags: methodology, levels, loading, asset-management
---


# Question
Title: XNA VertexBuffer.SetData performance suggestions
I have a 3d world in a grid layout where each grid cell contains its separate vertex and index buffer for the mesh/terrain of that cell.

When the player moves outside the boundaries of his cell, i dynamically load more cells in his walking direction based on his viewing distance. This triggers x number of vertex and indexbuffer initializations depending on how many cells that needs to be generated and causes the framerate to drop annoyingly during this time.

The generation of terrain data is handled in a separate thread and runs smoothly. The vertex and index buffers are added during the update cycle of the game loop.

I´ve tried batching the number of cells to be processed to avoid sending too much data at once into the buffers, which worked ok at a shorter viewing distance (about 9 cells to process), but not as well at greater distances with around 30 cells to process.

Any idea how i can optimize this?

# Answer
> 2 votes
In case anyone follows up on this post, here is how i finally solved it:

Having a VB pool with equally large buffers is a nice idea, but in my case, it ate **almost 300mb of ram** which only left 200 for the rest of the game (since the target platforms are both pc and xbox 360). This led me to a similar yet cheaper solution after several nights of tweaking :)

I still have a VB pool, but each VB has a custom tailored size for the world data within that cell. When a VB item gets recycled (the cell moves outside the players visibility scope) i check if the next batch has any cells which require a VB of the same size or less. This approach lets me reuse enough buffers to keep the fps smooth, yet resulting in a memory consumption of **between 80-90 mb of ram**. Not bad!

# Answer
> 2 votes
The solution to this seems pretty simple, really:

You're already generating your terrain data on a separate thread. You can **create your vertex and index buffers on a separate thread** as well!

Also, you are probably best off making your buffers quite huge - thousands of triangles.

# Answer
> 0 votes
Do you need to process all the new cells at once or could you queue them up and do a few each frame? Is the terrain data in memory or are you loading it from disk and processing it all on your main thread? (if so, perhaps you could read the data on a background thread).

---
Tags: xna-4.0
---


# Question
Title: What C++ containers should I use for my UI elements?
I am writing some UI stuff for my games in C++. Basically its a very common problem, but I dont know the best answer yet. Suppose inside my UI Library I have a view class which renders 2D/3D scene. This view can contain many subviews. I needs a container which allows me to iterate over these views fast and also insert/delete subviews. I am not sure which container is best for the job - list, vector or something else?

# Answer
Chances are you'll be iterating over your collection a *lot* more than inserting/deleting screens, so `vector` is probably the best choice. Sure, inserting and removing things from the middle of vectors is "slow" if you just look at "Big O", but in practice it's actually really fast simply because your elements are contiguous in memory. It's highly unlikely that you have so many screens that it becomes an issue.

Then again if you ask me I'll say never use `list` unless there's a really, really good reason to and benchmarks show that it's faster for that particular use case.

I'll point to my answer in the when should vector/list be used question to go into more detail.

Also, if you end up using `map`, make sure your keys are something that's fast to compare (i.e. not strings). If you must use string keys, use a hash map like `unordered_map`.
> 12 votes

# Answer
Vector is a great choice- very fast iteration. You'd need an extremely high amount of Scenes to make inserting one, even at the beginning, to be slow for a vector. This is especially true if you're storing pointers rather than values.
> 1 votes

# Answer
`List` is probably a good choice here. A linked list is fast to delete and insert elements into the middle, the front, and the end. You can iterate over it, but you cannot do random access (i.e. `myList[3]` for the 4th element).

`Arrays` could be good if you have a fixed number of GUI subviews.

`Vector` is less of a good choice. It's implemented as a resizable array, so deletion/insertion anyway except the back of the vector requires shifting the elements along. You can iterate over it just as easily, and you have random access if you need it. For a GUI, I doubt you will.

The other option is `Map`. This is almost certainly not a good idea unless you need to store them by keys.
> 0 votes

---
Tags: c++, gui
---


# Question
Title: Using raw vertex information for sprites rather than SpriteBatch in XNA
I have been wondering whether using SpriteBatch is the *best* option. Obviously for prototyping or small games it works well. However, I've been wanting to apply techniques such as shaders and lighting to my game. I know you can use shaders to some extent with `SpriteSortMode.Immediate`, but I'm not sure if you lose power using that.

The other major thing is that you cannot store your vertex data in the graphics memory with buffers.

In summary, is there an advantage of using `VertexTextureNormal` (or whatever they're called) structs for vertex data for 2D sprites, or should I stick with SpriteBatch, provided I wish to use shaders?

# Answer
> 5 votes
If you are using XNA 4.0 you can use shaders with any `SpriteSortMode`. To do so you pass an `Effect` to one of the overloads of `SpriteBatch.Begin` that accepts it as a parameter.

In XNA 3.1 and earlier `Immediate` was the fastest mode. In XNA 4.0 it is the *slowest*.

`SpriteBatch` uses a dynamic vertex buffer internally. It is pretty much the best strategy for doing what it does (batching together arbitrary sprite draws).

You could recreate `SpriteBatch`, adding or removing functionality and potentially changing the performance profile. But you should probably avoid doing that.

`SpriteBatch` "uses" up performance in the following ways: It does some CPU-based transformations (cheap CPU), possibly some sorting depending on mode (cheap CPU), and sends data to the GPU in batches (somewhat heavy CPU *per batch*, cheap bandwidth). Then on the GPU it has negligible vertex costs, and pixel costs that will depend mostly on your pixel shader and what you are drawing (ie: very little to do with `SpriteBatch` itself).

So if you can "bake" your vertices into a regular vertex buffer, instead of a dynamic one, you can shave off some time. You could also micro-optimise the draw calls and the transformations they do. These will get you very tiny performance improvements - generally not worth it unless you are doing large particle systems.

You can probably get much better optimisation results by optimising your batching (see this question and answer) - grouping textures together and **particularly** by not using `Immediate` sort mode in XNA 4.0. Or by optimising your pixel shader if you are GPU-bound, or other areas of your program if you are CPU-bound.

**Rewriting SpriteBatch is almost always not worth the effort.**

**As always with optimising for performance: *Measure It!***

---
Tags: xna, shaders, sprites, vertex, spritebatch
---


# Question
Title: Time calculation between openGL update calls
In XNA, the system calls update and draw function with the time information. This contains information such as how much time has passed since last update was called. This makes easy to integrate time and do animation calculation accordingly. But I dont see any such mechanism in openGL. I see openGL requires programmers to have their own implementation which could be buggy or inefficient. Is there any standard (and efficient) code that demonstrate this practice in openGL?

# Answer
XNA can do this because it knows it's sitting on top of a Windows-like platform, and therefore has Windows-compatible timer functions. OpenGL can sit on top of any OS, and therefore it can't provide any such thing itself.

GLFW provides a lightweight cross-platform wrapper around OpenGL, including high-precision timing routines.

This is also something that is fairly straightforward to implement yourself, using `QueryPerformanceCounter` on Windows, `mach_absolute_time` on OS X, and `clock_gettime` on POSIX (e.g. Linux).
> 3 votes

---
Tags: xna, opengl, timer
---


# Question
Title: How can I exclude some rigid body from rayTest in Bullet Physics?
I'm trying to picking some object with `rayTest` method of BulletPhysics. The problem is my stage is surrounded with walls (`btStaticPlane`) and the target objects (`btSphereShape`) are in there. And I'm trying to pick with a line from the outside of the surrounding box.

So I have to exclude the planes from `rayTest`. How can I do this?

# Answer
> 1 votes
when you call raytest function from `btCollisionWorld` class it returns all the object your ray hits (according to this page). so you just need to iterator over all the collisions and then just pick the ones you want.

you can also create a new instance of btCollisionWorld and call raytest from that instance.

---
Tags: bullet-physics, raycasting
---


title: V8 JavaScript Engine and Mac App Store

text:
# Question
Title: V8 JavaScript Engine and Mac App Store
If I embed the V8 JavaScript Engine in my game is it still possible to distribute it in the Mac App Store?

# Answer
> 2 votes
Since there are both Python and Ruby apps on the Mac App Store I would imagine an embedded V8 engine would be allowed. I can't find anything in the guidelines that suggests otherwise.

The guidelines do however explicitly state that "Apps that download or install additional code or resources to add functionality or change their primary purpose will be rejected".

So, as long as your app doesn't download any code, you should be ok.

You can read the Mac App Store Approval Guidelines here.

---
Tags: javascript, appstore
---


# Question
Title: What is eigenvalue decomposition and why would it be useful in games?
In various math libraries developed for game engines, I see 2x2 and 3x3 square matrices having this function (along with some helper functions). I tried to find information regarding it but did not come across game specific material (wikipedia entry is quite heavy and does not relate to games).

It would be great if in your answer, you could provide an example or two on how it is used in games.

# Answer
Eigenvalues and eigenvectors are very commonly used in math, so it's good to understand them even if you don't have an immediate use for the in games. They're generally covered near the end of an undergraduate-level linear algebra course.

One I can think of is for dealing with the moment of inertia in physics. This is a symmetric positive-definite matrix, so all the eigenvalues are guaranteed to be real and positive. If you compute the principal axes of a rigid body (which are the eigenvectors of the matrix), you can rotate the body so that its moment of inertia is diagonal - this would allow you to store just the diagonal components as a vector3, instead of the full matrix.

Another place I've seen them used is computing the best-fit plane to a set of points, or to find the best-fit bounding box (section 6.1.2 in the link)

Have you searched in the WildMagic or Ogre code to see where else they're used?
> 3 votes

# Answer
As far as I know, eigenvalue decomposition is a middle-step that can be performed in some algorithms for things with more readily apparent uses, such as matrix inverting.
> 0 votes

---
Tags: mathematics, matrix, rotation
---


# Question
Title: Tile based isometric depth sorting on different size objects.
I am creating a tile based isometric game.

The problem we are having is with depth sorting, we tried a lot of methods but none work.

They all do a great job but its not perfect, they seem to bug sometimes.

We have tiled objects of different sizes, like 2x2, 2x6, 3x4. This makes it so hard.

We are trying to avoid slicing the bitmaps.

Anyone has a idea?

# Answer
You need to compare your object's bound boxes and check if one object is supposed to be in front of each other, then apply a topological sort based on this information.

Here are some articles with further details:

http://bannalia.blogspot.com/2008/02/filmation-math.html

http://bannalia.blogspot.com/2008/02/isometric-room.html
> 4 votes

# Answer
You are experiencing the reason why many systems prefer to use a Z-buffer rather than the simpler but more error-prone painter's algorithm. Unless extremely strict rules are enforced on your objects, there is no way to sort them totally by depth without slicing them.

It would help if you could show us what your objects look like, how you compute depth, and an example of the bugs you mention.
> 3 votes

# Answer
i too have been looking for a good way to depth sort different sized objects, i have thought that i could get the bottom x,y co-ords and if the x,y co-ords are higher up they get rendered first. Although they may be some bugs and i have not actually tested it or tried coding (im in the process of coding my theory in javascript with canvas). Although i have found a very good way to store the odered list in order of rendering, it uses a technique to dramatically increase efficiency in ordering a list, it is of course a BinaryHeap array Here is a good article about it Hope that helps.
> 0 votes

---
Tags: tiles, isometric
---


# Question
Title: Hidden operations of the Direct3D pipeline
I'm curious- what operations are there in Direct3D that *aren't* controlled directly through shader, or directly to do with shader manipulation- i.e., that occur behind the scenes.

So far, I've got just pixel interpolation.

# Answer
> 4 votes
Off the top of my head: There is triangle setup, triangle clipping, backface removal, rasterization, raster operations (blending), z testing, tessellation, texture filtering, shadow map texture depth testing, stencil ops, pixel/buffer format conversion.

# Answer
> 0 votes
Tessellation. It is a separate fixed function system that doesn't have a 1:1 with OpenGL and will result in different tessellation unlike shaders which can be ported fairly easily. http://msdn.microsoft.com/en-us/library/bb206188%28v=vs.85%29.aspx

---
Tags: directx
---


title: openfeint or gamecenter?

text:
# Question
Title: openfeint or gamecenter?
which one has more potential customers, easier API, and wider feature list? i'm going to develop implement one of those two for highscore recording in my game which ones gives more advantages?

and by the way I might be going to port my game to android, so if you know any thing that can help me not to rewrite my code (for example a C++ wrapper for both of them) that would mean a greate plus for openfeint in my point of veiw.

# Answer
> 1 votes
> more potential customers

GameCenter

> easier API

They're all trivially easy

> wider feature list

OpenFeint

> I'm going to develop implement one of those two for highscore recording in my game which ones gives more advantages?

Use GameCenter unless you need some of the features beyond "high score list" that OpenFeint currently provides.

---
Tags: game-center, openfeint
---


# Question
Title: Simulating a 2D rope from a top down perspective
I was wondering if anyone could point me to any resources and/or explain how to properly simulate a 2D rope from a top down perspective?

I found a game that has the exact mechanic I'm looking for...

http://www.newgrounds.com/portal/view/300760

Play at least one level to get an idea of what I mean.

# Answer
The behavior of that "shoe string" is achieved by using splines. You will find a lot of resources by just googling that keyword.
> 1 votes

---
Tags: software-engineering, graphics-programming, procedural-generation
---


# Question
Title: Question on methods in Object Oriented Programming
I’m learning Java at the minute (first language), and as a project I’m looking at developing a simple puzzle game.

My question relates to the methods within a class. I have my `Block` type class; it has its many attributes, set methods, get methods and just plain methods. There are quite a few.
Then I have my main board class. At the moment it does most of the logic, positioning of sprites collision detection and then draws the sprites etc...

As I am learning to program as much as I’m learning to program games I’m curious to know how much code is typically acceptable within a given method. Is there such thing as having too many methods?

All my draw functionality happens in one method, should I break this into a few ‘sub’ methods? My thinking is if I find at a later stage that the for loop I’m using to cycle through the array of sprites searching for collisions in the `spriteCollision()` method is inefficient I code a new method and just replace the old method calls with the new one, leaving the old code intact.

Is it bad practice to have a method that contains one if statement, and place the call for that method in the for loop? I’m very much in the early stages of coding/designing and I need all the help I can get! I find it a little intimidating when people are talking about throwing together a prototype in a day too! Can’t wait until I’m that good!

# Answer
> 1 votes
Java is a good language to start with for your Object Oriented Programming learning! A simple and important advice to you.

*Don't ever follow any "coding-best-practice" from books or individual without understanding the underlying purpose. Keep questioning WHY before you BUY.*

**1)** METHOD SIZE: There are no standard rules for method size. The following things have helped me in managing them.

**Lines:** I believe that if the methods have less than 15 lines of code, it would be readable and manageable. It doesn't mean that one has to stick to this number. Let's not break a 20 lines method into 2 different 10 lines methods and compromise the readability.

**Method Naming:** Yes! Method naming helps to maintain the size of a method. Name a method in such a way that it does a single action. Try to avoid "and" in method names. Then don't add even a single line of code in that method which does something other than what your method name says. Its always tempting to give some name that comes to our mind immediately and jump to the implementation. But it is important and okay to spend some time in choosing a right name for a method.

**2)** With respect to your draw method, can you post your code so that we can discuss about it specifically.

**3)** Calling "if method" in a for loop: Generally, there is no problem in calling a method from a for loop. I hope you are not talking about performance here. There might be some room for improvement w.r.t. complexity, but it depends on the actual code.

And yeah, this is not a game development related question. You would have more people to help you in Software development exchange :)

# Answer
> 1 votes
I shall do my best to answer your questions, and then give some general advice.

1) No, you cannot have too many methods. However, having a large amount could be a bad design. If there's a function which does one very simple line and is only accessed internally, why does it need to be a method? Could you replace getters and setters with a public variable?

2) Not really. There's little point in it being a method, so you may want to change that - unless it does something specific that you may need again.

In terms of design as a whole, I would say 50% is common sense and the other 50% is knowledge, be it from other bits of code, questions like this, and other material. It makes no sense to force everything to a design.

---
Tags: architecture, java, software-engineering, objects
---


title: Draw contour around object in Opengl

text:
# Question
Title: Draw contour around object in Opengl
I need to draw contour around 2d objects in 3d space. I tried drawing lines around object(+points to fill the gap), but due to line width, some part of it(~50%) was covering object. I tried to use stencil buffer, to eliminate this problem, but I got sth like this(contour is green):

http://goo.gl/OI5uc (sorry I can't post images, due to my reputation)

You can see(where arrow points), that some parts of line are behind object, and some are above. This changes when I move camera, but always there is some part, that is covering it. Here is code, that I use for drawing object:

```
    glColorMask(1,1,1,1);
    std::list<CObjectOnScene*>::iterator objIter=ptr->objects.begin(),objEnd=ptr->objects.end();
    int countStencilBit=1;
    while(objIter!=objEnd)
    {
        glColorMask(1,1,1,1);
        glStencilFunc(GL_ALWAYS,countStencilBit,countStencilBit);
        glStencilOp(GL_REPLACE,GL_KEEP,GL_REPLACE );
        (*objIter)->DrawYourVertices();

        glStencilFunc(GL_NOTEQUAL,countStencilBit,countStencilBit);
        glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);
        (*objIter)->DrawYourBorder();

        ++objIter;
        ++countStencilBit;
    }

```

I've tried different settings of stencil buffer, but always I was getting sth like that. Here is question: **1.Am I setting stencil buffer wrong?**

**2. Are there any other simple ways to create contour on such objects?**

Thanks in advance.

**EDIT:**

**1.** I don't have normals of objects.

**2.** Object can be concave.

**3.** I can't use shaders(see below why).

# Answer
* Draw your entire scene, except highlighted objects.
* Draw the objects you want to highlight, in pure color, sorted from back to front, and with a small scale applied (1.05f - 1.1f).
* Draw the final objects, again, from back to front.

For extra eye-candy, try drawing the contour pass to a separate render target and apply a small blur, then blend this texture with your final scene using the appropiate Z values.
> 12 votes

# Answer
I'll do this like that:

* Sort objects in front-back(distance from camera) order
* Draw object's border(as lines and points) with disabled `GL_DEPTH_TEST`
* Draw object with enabled `GL_DEPTH_TEST`
* Do last two steps for every object

I'll try to do this like that, but if anyone have ideas of better solution to this problem(MIND CONCAVE OBJECTS, PLEASE)- feel free to share with us.

PS. I'm not fully satisfied with my solution-changing OpenGL states so often can be harmful. But if no one can help me with stencil buffer settings, I guess that's the only way for me.
> 0 votes

---
Tags: opengl, c++, graphics, directx, graphics-programming
---


# Question
Title: How do I accomplish fading texture trails in UDK?
**I would like to know how to leave a fading texture/material trail in udk.**

For example (I'm not sure if there is a special name for this effect):

* A character may leave footprints that fade after x number of seconds
* Or, a tank may leave a tracks trail as in Civilization IV.

Here is another example of this type of effect. Skip to 1:00 and watch the green slime texture.

> http://www.youtube.com/watch?v=KdJIauWjE8s

**How do I accomplish this effect in UDK? Any good tutorials?**

Thank you.

# Answer
I haven't used UDK before, but I'm sure it supports a texture alpha channel. In order to fade a texture out over time, you just update it's alpha channel based on the amount of time elapsed since it was placed. For example:

```
if(time >= 10000 && time <= 20000)
    texture.alpha = 1 - ((20000 - time)/10000);

```

Where time is the time elapsed since the texture was placed and is stored in milliseconds. This will start fading the texture after 10 seconds (10,000 milliseconds), and fade for 10 seconds until it's completely faded. I'm not sure it's that what you're looking for :/

This page seems like it has good information on texture painting and alpha. And a video here.
> 2 votes

---
Tags: textures, udk
---