# Question
Title: How do I swap two objects in C# (specifically Mono) without triggering GC?
I have two array lists. that I want to swap each frame. My question is, does the variable 'temp' need to be a member variable to avoid triggering GC, assuming this method is called on dozens of objects each frame? I'm not creating a new object, just a new reference to an object.

```
public void LateUpdate(){
    ArrayList<int> temp = previousFrameCollisions;
    previousFrameCollisions = currentFrameCollisions;
    currentFrameCollisions = temp;
    currentFrameCollisions.clear();
}

```

I've been told there's no reason to make a primitive into a member variable just to avoid GC, so my best guess is that this also applies to object references.

# Answer
> 6 votes
The GC is triggered by allocating new objects. In the simpler sense, it's only triggered if you use the 'new' keyword (or call a function or language feature that uses it internally, e.g. many GetEnumerator() implementations invoked by the 'foreach' keyword).

Assigning to variables -- member or otherwise -- will not cause the GC to trigger.

Also note that C# has excellent debugging and profiler tools, and you can always just test your code to see if it's triggering the GC or not.

# Answer
> 1 votes
Swap them, see if it causes any problems for you, and if not, then don't worry about it.

In other words - don't try to pre-emptively guess the runtime's behaviour. You risk causing even bigger problems for yourself that way. The time to deal with GC issues is when you know for certain that you have GC issues, not before - managed languages these days are extremely clever and GC overhead can be blown out of proportion in popular mythology; the common case is that the memory is just going to be returned to a "free" pool (a simple pointer swap) and very quickly reused (another pointer swap) so this is not really going to be that big a deal - particularly for simpler data types (like your ArrayList of ints).

# Answer
> 0 votes
GC uses reference counting and will only trigger cleanup of an allocated block if there are zero references remaining (at the time when the GC sweep comes around). So by using temp for the swap, you won't trigger GC.

In other words, at no point are there zero refs to either of the two arrays you are allocating, in your code above. So don't worry.

---
Tags: c#, optimization, mono
---


# Question
Title: How do I stop stretching during window re-size in XNA?
In my windowed mode XNA game when the user resizes the window the game stops updating the window and the last frame drawn is stretched and distorted until the user releases the mouse and the resize completes.

Is there any way to have the game continue to run "normally", updating frames and redrawing the screen, during the resize event?

I realize that keeping the render loop going while resizing may not be possible or recommended due do hardware managed resources getting continually created and destroyed, but is there any way to stop the ugly stretching? Ideally by leaving the existing frame unscaled in the top left, or with a black screen if that isn't possible.

# Answer
> 3 votes
There are at least 3 messages that you can track.

* `WM_SIZE` \- window resizing, mini/maximization, fullscreen/windowed switching. You shall read into wParam to find out what exactly happened and to lParam for current size.
* `WM_ENTERSIZEMOVE` \- begin window resizing in windowed mode
* `WM_EXITSIZEMOVE` \- end window resizing in windowed mode

Usually you will not want resize your app every frame between WM\_ENTERSIZEMOVE and WM\_EXITSIZEMOVE because its too way slooow and ugly. But give it a try, its surely nicely than stretching, maybe you'll like it =)

```
case WM_SIZE:
    // Save the new client area dimensions.
    m_ptViewportSize.x  = LOWORD(lParam);
    m_ptViewportSize.y = HIWORD(lParam);
    if( wParam == SIZE_MINIMIZED )
    {
        m_bAppSuspended = true;
        m_bMinimized = true;
        m_bMaximized = false;
    }
    else if( wParam == SIZE_MAXIMIZED )
    {
        m_bAppSuspended = false;
        m_bMinimized = false;
        m_bMaximized = true;
        OnResize();
    }
    else if( wParam == SIZE_RESTORED )
    {
        // Restoring from minimized state
        if( m_bMinimized )
        {
            m_bAppSuspended = false;
            m_bMinimized = false;
            OnResize();
        }
        // Restoring from maximized state
        else if( m_bMaximized )
        {
            m_bAppSuspended = false;
            m_bMaximized = false;
            OnResize();
        }
        else if( m_bResizing )
        {
            // Resizing in processs
            // You woldn't wanto to handle a massive stream of
            // WM_SIZE here because buffers resizing is very slow
        }
        else
        {
            // Resizing finished and you can handle it. For ex. with
            // m_SwapChain->SetFullscreenState
            OnResize();
        }

    }
    return 0;

// WM_EXITSIZEMOVE is sent when the user grabs the resize bars.
case WM_ENTERSIZEMOVE:
    m_bAppSuspended = true;
    m_bResizing  = true;
    g_pTimer->Stop();
    return 0;
// WM_EXITSIZEMOVE is sent when the user releases the resize bars.
// Here we reset everything based on the new window dimensions.
case WM_EXITSIZEMOVE:
    m_bAppSuspended = false;
    m_bResizing  = false;
    g_pTimer->Start();
    OnResize();
    return 0;

```

---
Tags: xna, xna-4.0, .net
---


title: GPU based procedual terrain borders?

text:
# Question
Title: GPU based procedual terrain borders?
I'm working on a game that preferably should feature a combination of designed and procedurally generated terrain where the designer specifies in somewhat detailed terms what type of terrain a given area will have (grasslands, forest etc...) and then a procedural algorithm takes care of the rest. I'm not talking about minecraft style biomoes, but rather the game map for a strategy game.

Each 'area' will not take up that much of the screen, and thus be more akin to a tile whose texture is procedurally generated. While procedurally generating terrain textures on the GPU are not that difficult, the hard part is making the borders between them look good. Currently, the 'tiles' are large enough to be visible (due to memory constraints mainly, we are talking planetary sized textures for a game taking place in space and on a continental ground view with seamless transitions between them) and creating good borders between them with an algorithm that is fast enough to be useful has proven difficult. Sampling the n-surrounding pixels and using the combined result did not yield very good borders and was fairly slow on the GPU to boot (ca 12ms for me, that is without any lighting or shading and with very simple terrain texture shaders).

So are there any practical known methods to solve this problem?

Edit:

To clarify, the 'tiles' are there only out of necessity and the whole idea is to make them essentially vanish entirely. This screenshot shows how the terrain looks like right now when the camera is zoomed in about as much as will be possible in the game, with no lighting and very simple texture shaders.

http://s7.postimage.org/y67o03swb/terrain\_Sample.png

While the 'internal' borders of each terrain type looks passable, the borders between different terrain types are far too sharp and really exposes the technical details. Shrinking terrain types further is not an option, as that will increase memory usage far too much and it did not actually solve the problem entirely in my test runs.

The good thing is that nearly all GPU resources will be devoted to rendering terrain, so there is room to work there.

Finally, having it done on the GPU both avoids the memory problem and makes it easier to make the terrain morphic without significant runtime slowdowns when large scale terrain changes happen. As the game will have methods to radically change terrain, though only in the large-scale sense, having it be morphic is a requirement.

# Answer
You could have all of your tile procedures utilize some smaller, tiled sections of the same perlin noise. Their borders would be correct so long as your tile generators are able to make the same border heights from the same noise value.

Also, you should not do this in real time on the GPU. You should generate procedural geometry once at asset load time, and keep it persisted. It should remain the same over all draw calls, right? There's no need to spend ms every frame.
> 1 votes

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


# Question
Title: assigning values to shader parameters in the XNA content pipeline
I have tried creating a simple content processor that assigns the custom effect I created to models instead of the default BasicEffect.

```
[ContentProcessor(DisplayName = "Shadow Mapping Model")]
public class ShadowMappingModelProcessor : ModelProcessor
{
    protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
    {
        EffectMaterialContent shadowMappingMaterial = new EffectMaterialContent();
        shadowMappingMaterial.Effect = new ExternalReference<EffectContent>("Effects/MultipassShadowMapping.fx");
        return context.Convert<MaterialContent, MaterialContent>(shadowMappingMaterial, typeof(MaterialProcessor).Name);
    }
}

```

This works, but when I go to draw a model in a game, the effect has no material properties assigned. How would I go about assigning, say, my DiffuseColor or SpecularColor shader parameter to white or (better) can I assign it to some value specified by the artist in the model? (I think this may have something to do with the OpaqueDataDictionary but I am confused on how to use it--the content pipeline has always been a black box to me.)

# Answer
Kikaimaru gave me some helpful tips, so here is an answer (a code example) to my own question based on what I've learned about custom shaders and building materials in the content pipeline:

```
[ContentProcessor(DisplayName = "Shadow Mapping Model")]
public class ShadowMappingModelProcessor : ModelProcessor
{
    protected override MaterialContent ConvertMaterial(MaterialContent material, ContentProcessorContext context)
    {
        // We want to use a custom shader we wrote ourselves, so we build our .fx file, putting shader parameter
        // values into opaque data and textures using our shader variable names as the keys.

        // You can see these default "key (value)" entries on "material" by using the content pipeline debug project here:
        // (http://badcorporatelogo.wordpress.com/2010/10/31/xna-content-pipeline-debugging-4-0/)

        // default "material" opaque data:
        // ===============================
        // DiffuseColor (vector3)
        // EmissiveColor (vector3)
        // SpecularColor (vector3)
        // Alpha (float)
        // SpecularPower (float)
        // VertexColorEnabled (bool)
        //
        // default "material" textures:
        // ============================
        // Texture (external texture reference)

        // use our custom effect
        EffectMaterialContent shadowMappingMaterial = new EffectMaterialContent();
        shadowMappingMaterial.Effect = new ExternalReference<EffectContent>("Effects/MultipassShadowMapping.fx");

        // transfer opaque data
        shadowMappingMaterial.OpaqueData.Add("DiffuseColor", new Vector4((Vector3)material.OpaqueData["DiffuseColor"], (float)material.OpaqueData["Alpha"]));
        shadowMappingMaterial.OpaqueData.Add("SpecularColor", material.OpaqueData["SpecularColor"]);
        shadowMappingMaterial.OpaqueData.Add("SpecularPower", material.OpaqueData["SpecularPower"]);

        // transfer texture
        if (material.Textures.ContainsKey("Texture"))
        {
            shadowMappingMaterial.OpaqueData.Add("DiffuseTextureEnabled", true);
            shadowMappingMaterial.Textures.Add("DiffuseTexture", material.Textures["Texture"]);
        }

        return context.Convert<MaterialContent, MaterialContent>(shadowMappingMaterial, typeof(MaterialProcessor).Name);
    }
}

```
> 2 votes

---
Tags: xna, shaders, xna-content-pipeline
---


title: random spike in delta time

text:
# Question
Title: random spike in delta time
The title pretty much sums it up. I'm using delta time to move my objects and every few seconds the delta time will spike and all the objects will jump forward. Should I just Interpolate the delta time to eliminate spikes, I don't want to do this because it could cause other problems but it could be a solution

# Answer
> 1 votes
It might help if you'd post a simple code example demonstrating the problem, but I'm going to take a wild guess and suggest that your time resolution is too low.

In particular, consider what happens if your simulation loop takes, say, 0.02 seconds to run, but your timer only counts whole seconds. So, for 49 out of 50 loops, the delta time you'll calculate will be exactly zero, and so the simulation time will not advance — but then the timer ticks over, the delta time becomes 1 second, and the simulation loop suddenly goes "*Oh, wow, that last iteration sure took a long time! I'll have to use a huge time step to catch up!*"

The best solution is simply to use a more precise time source. However, if you really can't get the time resolution you want (or if something else is causing unavoidable jitter in your loop timings), you can stabilize the timing prediction by averaging the delta time over several iterations, i.e. instead of doing this:

```
var baseTime = getCurrentTime();
while ( running ) {
    var currentTime = getCurrentTime();
    var deltaTime = currentTime - baseTime;
    baseTime = currentTime;
    simulate( deltaTime );
}

```

you could do e.g. this:

```
var baseTime = getCurrentTime();
**var timeQueue = new Queue ();**
while ( running ) {
    var currentTime = getCurrentTime();
    **timeQueue.push( getCurrentTime() );**
    **if ( timeQueue.length > 10 ) {**
        **baseTime = timeQueue.shift();**
    **}**
    var deltaTime = (currentTime - baseTime) **/ timeQueue.length**;
    simulate( deltaTime );
}

```

---
Tags: game-loop, timer
---


title: Turn-based Strategy Loop

text:
# Question
Title: Turn-based Strategy Loop
I'm working on a strategy game. It's turn-based and card-based (think Dominion-style), done in a client, with eventual AI in the works. I've already implemented almost all of the game logic (methods for calculations and suchlike) and I'm starting to work on the actual game loop.

What is the "best" way to implement a game loop in such a game? Should I use a simple "while gameActive" loop that keeps running until gameActive is False, with sections that wait for player input? Or should it be managed through the UI with player actions determining what happens and when?

Any help is appreciated. I'm doing it in Python (for now at least) to get my Python skills up a bit, although the language shouldn't matter for this question.

# Answer
> 6 votes
Ok, if you don't care about the graphics, that's simpler. From a high-level pseudocode, what I suggest is like how any other game loop works:

```
while game has not ended yet:
   keep going

// we're out of the while loop; game has ended
show results, etc.
go back to main menu

```

Thing is, yours is turn-based, so we can do away with the loop part, or keep it and use coroutines. Let's keep it simple for now though. (Not sure if standard Python has coroutines built-in)

So instead of a loop, we'll basically use callback functions.

The entry point for starting our game would be like this (this is still pseudocode):

```
// call this at the start of the game
function OnStartTurn()
{
   currentPlayer.OnBeginTurn();
}

// call this function when the human player clicks on "End Turn" button, or if the AI decides it's finished.
function OnCurrentPlayerEndTurn()
{
   change currentPlayer variable to the next player in line
   OnStartTurn(); // will cause the next player to begin his turn
}

```

So from here, you can gather that we at least need a currentPlayer variable, which means we need some sort of Player class.

Also since we need to let the game pass control to the next player in line, we need to store all Player objects in a list (ordered in the way we want to). And on the OnCurrentPlayerEndTurn function, we simply cycle through that list so that the next player now begins his turn.

In OnStartTurn() we have a currentPlayer.OnBeginTurn(). You will want that for human players, this function will activate the GUI so the user can now act. For AI players you will want this function to start the AI's thinking process instead.

If you don't know how to do that, you have to learn polymorphism and object-oriented programming concepts.

Now for the human player, you'd provide some "End turn" button, which when clicked will call that OnCurrentPlayerEndTurn() function. For the AI, you'll want that immediately after the AI is done thinking and acting, it will likewise call OnCurrentPlayerEndTurn().

The idea is, either way, OnCurrentPlayerEndTurn() needs to get called in the end, so that the next player who needs to move gets his turn.

Unless a player won, in which case you don't need to bother calling that. Just go ahead and call your function to show results, etc.

# Answer
> 1 votes
The gamActive loop you discribed is the standard for making games, as far as your specific question goes you can do this a number of ways. I would recommend having a class that contains all the possible states of play, and in each of the player objects hold the status of each player. During your game loop you can skip through the active players putting them in a wait status, or a play status as you itterate through the players.

```
for(int activePlayer; activePlayer < playerArray.size(); activePlayer++)
{
if (playerArray.get(activePlayer).activeTurn)
{
    // Run code for this players turn
    ...
    // Give activeTurn to next player
    ...
}
}

```

This would work for a basic game but might not be efficient enough for a high level graphics based game. What language are you using to write your game in?

---
Tags: game-loop, turn-based, strategy, card-game
---


# Question
Title: Choosing 3D modeling software Maya or 3D max?
I've am a developer whose has spent most of my programming life developing web and business applications. I want to try my hand at something more challenging (but stay in the comfort of Visual Studio) ...perhaps XNA.

**Want 3D modeling software would be best for someone developing XNA?**
I have played with 3d MAX and Maya but never really did anything too involved.
**What are the pros and cons between them (in terms of game development)? <br>Does one win out over the other for game development?**
Or is it pretty much just preference?

I am new to game development and just trying to figure out the best tools to use before I really started. Any advice or other suggections would be greatly appreciated.

# Answer
This question has been beaten to the ground and then some. You will find many threads online discussing the same things. In the end, they will both give you a format that you will read, whether it be fbx, or obj or something else. The general concensus is that 3Ds Max is used for games, but I have seen/heard both being used in the industry as long as the pipeline supports it. I personally prefer Maya, but that does not mean it is better.

There are loaders out there for obj, fbx etc. for XNA, which Maya/3DsMax/XSI/Modo/Lightwave/Blender etc. can export to (or you can write your own). What are you comfortable with? Go with that!

http://www.google.ca/#hl=en&source=hp&biw=1920&bih=979&q=3ds+max+or+Maya+for+games&aq=f&aqi=g3&aql=&oq=&gs\_rfai=&fp=ce518d88d48a6dfe
> 4 votes

# Answer
My 2c (worked as professional 3d modeler/animator)

* For getting into the industry, I'd advice Max or Maya. May be best is to master one of those, though have some familiarity with the other, so you can get put up to speed in a company that uses the other with no big issues. 3D is 3D, so you'll be able once gained expertise with one.
* Blender is getting better and better. In features anda capabilities is yet behind, but if going for small/middle game studio, or video production, local TV studio, freelancing, etc, etc, is a really good thing, but its GUI standards are a bit different from the rest. I am a blender user that worked hard with 3ds Max before.
* Maya is used by animation companies, but also big console (PS3, etc) studios are using Maya. Not only for its better animation capabilities, but for Mel script and interaction allowed inside the team's pipelines. Those were worked hard through years, rarely they would move to another thing.
* Max is inmensely used in games production. I prefer it, but I'd say is 50% usage between Maya and Max, probably even more Maya.(Max ruled during some time, in games)
* Max learning can be a bit easier than Maya or Blender. Probably the hardest to learn is XSI, requires an special mindset, but its workflow seems well thought. And its renderer is great, photon based, and allowing partial viewport, dynamic rendering.(and one of the greatest hair simulations in the market)
* For rendering, XSI is best, Max and Maya have worse default renderers, but usually one uses plugged in external renderers (commercial or not) . For prerrendered games is ok tho scanline rendering, often.
* Advantages of going with one of these (both are great to go) are, apart of being able to do *anything* is that you could get into the indyustry one day, if unemployed. But will be 3500, 6000 dollars to purchase one.
* Blender (Wings3D is great as a modeler only, also) is free, on the other side ;) But for now, rarely any studio will pick you if not mastering Max or Maya.

(there are always more niche like tools, Cinema 4D (largely used in architecture), Lightwave (great modeler, also ok for animating), used in series like Babylon 5)

(XSI also, but been purchased by Autodesk, too, so, dunno...)
> 4 votes

# Answer
> What 3D modeling software would be best for someone developing XNA?

If you are just starting out and want to build some models I might suggest something like Blender. Since it will allow you to freely build some content as you are learning to work with 3D.

At the end of the day you'll likely be importing the models into your game either through the .fbx or .obj format so you can switch to one of the paid modeling packages once you feel more comfortable.

> I have played with 3d MAX and Maya but never really did anything to involved. What are the pros and cons between them (in terms of game development)? Does one win out over the other for game development?

Both are used in game development. In general animators tend to prefer Maya, character modelers go either way since these days they are often spending time in zbrush or mudbox, and scenary/architecture modelers tend to prefer Max.

Both software packages have their quirks but since Autodesk owns them all now (including XSI) so they are mostly at feature parity. Play with the demos of both and figure out which you like the best.
> 2 votes

# Answer
Between the two, I feel that 3ds Max is easier to learn, as the workspaces, panels, and shelves in Maya may be very confusing if you are just starting out with 3D modeling. The important thing is that you need to learn 3D modeling, not how to us program X. The disciplines that go with modeling are transferable between any modeling package, so if you feel it it is necessary or are curious of different workflows, it will be easy to get up and running a lot quicker. In addition to the 30 day trials Autodesk offers for their programs, the offer free 3-year licenses to students at Autodesk Education .

If you decide to go the Maya route, I recommend checking out Digital Tutors as they have lessons that deal specifically with using Maya and XNA together (they also have tons of other great tutorials on getting you up and running, with game modeling specific lessons, in whatever 3D package you decide on).
> 2 votes

# Answer
I always preferred the interface of Lightwave, personally. I would also not discount Blender. The interface is really off-putting in my opinion, but once you learn the shortcut keys and figure out what's what, Blender is pretty fantastic, free, and well supported with tons of scripts to extend its feature-set.
> 1 votes

# Answer
Pick one and stick with it (by trying both out for a simple task) - both are fully capable and will do anything you'd want to do just starting out. Furthermore, as you learn more about general techniques you'll be able to go between modeling software packages with less of a learning curve.

The most important thing to remember is not to get hung up for too long on what technologies you're using in your quest to start out with game development.

For the record, I've only used Maya extensively, but I really like it.
> 0 votes

# Answer
As said before, both packages will let you do what needs to be done. Neither is better off the shelf for someone starting out, but you may find one more intuitive than the other. I personally prefer 3DSMax but you may not. They both have a 30 day free trial, so you might as well try both for 30 days and see which one feels better after that.

I know many game devs have used 3DSMax in the past, but I do believe other packages, including Maya, have started to gain a foot hold in the industry. I must point out that learning how to model and texture is package independent. Its the same concepts, just different buttons.

One thing to perhaps consider is that both packages have custom scripting languages you can use, but Maya also allows you to use Python for scripting. This may or may not be relevant but if you already know python and you have no other deciding factors, this may be a deciding point.
> 0 votes

---
Tags: xna, 3d
---


# Question
Title: What technology would you use to communicate between an iOS game and a Lua-based AI server?
What technology would you use to communicate between a two-player,turn-based, board game (like checkers or Othello) running native on iOS, and a remote game server

The remote game server is just the artificial intelligence portion of the computer player and it is coded in Lua.

# Answer
One option is Websockets.

There's a Lua Websocket server. I'm pretty sure iOS will be able to communicate with that (at least with regular sockets)
> 2 votes

# Answer
ZeroMQ is a great layer for taking care of the actual transport and has bindings available for both C# and Lua. For the actual messaging I would probably use either Protocol Buffers (again, available for both langs) or simply use JSON strings (available for everything ever).
> 1 votes

# Answer
For a turn-based board game? I would use typical REST programming and make it act like a website, with the server taking in POST or GET requests and returning information back. I wouldn't even bother with sockets unless it was closer to being real-time.

See this answer for more information.
> 1 votes

---
Tags: game-design, lua, game-loop, ios
---


title: Need help revolving a 2D array

text:
# Question
Title: Need help revolving a 2D array
Pretty much all I'm trying to do is revolve my 2D Array by its container. I'm using this array for a background and I seem to be having problems with it revolving.

```
public class TileTransformer : GridConstants
{
    public Tile[,] Tiles;
    ContentManager Content;
    public TileTransformer(ContentManager content)
    {
        Content = content;

    }
    public Tile[,] Wraping(Tile[,] tiles,Point shift)
    {
        Tiles = tiles;
        for (int x = shift.X; x < 0; x++)//Left shift
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (X + 1 >GridWidth-1)
                    {
                        Tiles[0, Y].Container =tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X+1, Y].Container =tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int x = shift.X; x > 0; x--)//right shift
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y< GridHeight; Y++)
                {
                    if (X-1==-1)
                    {
                        Tiles[GridWidth-1, Y].Container =tiles[0, Y].Container;
                    }
                    else
                    {
                        Tiles[X - 1, Y].Container =tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int y = shift.Y; y > 0; y--)//shift up
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (Y - 1 == -1)
                    {
                        Tiles[X, GridHeight-1].Container = tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X, Y - 1].Container = tiles[X, Y].Container;
                    }
                }
            }
        }
        for (int y = shift.Y; y < 0; y++)//shift down
        {
            for (int X = 0; X < GridWidth; X++)
            {
                for (int Y = 0; Y < GridHeight; Y++)
                {
                    if (Y + 1 == GridHeight)
                    {
                        Tiles[X, 0].Container = tiles[X, Y].Container;
                    }
                    else
                    {
                        Tiles[X, Y + 1].Container = tiles[X, Y].Container;
                    }
                }
            }
        }
        return Tiles;
    }

```

Now the Problems that I'm having is either when I shift up or left it seems the whole array is cleared back to the default state. Also when I'm revolving the array it appears to stretch it upon the sides of the screen that it is shifting towards.

# Answer
> 1 votes
It should be as simple as this, obviously untested but should point you in right direction

```
public Tile[,] Wraping(Tile[,] tiles,Point shift) {
  Tiles = tiles;
  Tile[,] shiftedTiles;

  for (int y = 0; y < GridHeight; y++) {
    for (int x = 0; x < GridWidth; x++) {
      shiftedTiles[(shift.X + x) % GridWidth, (shift.Y + y) % GridHeight] = tiles[x, y];
    }
  }
  return shiftedTiles;
}

```

The % part is modulus which ensure that the grid X,Y are wrapped round without using if statements to check edge boundaries.

If that doesn't quite work try exchanging the parameters around to:

```
 shiftedTiles[x,y] = tiles[(shift.X + x) % GridWidth, (shift.Y + y) % GridHeight];

```

---
Tags: xna-4.0
---


title: Platform game collisions with Block

text:
# Question
Title: Platform game collisions with Block
I am trying to create a platform game and doing wrong collision detection with the blocks.

Here's my code

```
// Variables
GTimer jump = new GTimer(1000);
boolean onground = true;

// The update method
public void update(long elapsedTime){
    MapView.follow(this);
    // Add the gravity
    if (!onground && !jump.active){
        setVelocityY(4);
    }
    // Jumping
    if (isPressed(VK_SPACE) && onground){
        jump.start();
        setVelocityY(-4);
        onground = false;
    }
    if (jump.action(elapsedTime)){
        // jump expired
        jump.stop();
    }
    // Horizontal movement
    setVelocityX(0);
    if (isPressed(VK_LEFT)){
        setVelocityX(-4);
    }
    if (isPressed(VK_RIGHT)){
        setVelocityX(4);
    }
}

// The collision method
public void collision(GObject other){
    if (other instanceof Block){
        // Determine the horizontal distance between centers
        float h_dist = Math.abs((other.getX() + other.getWidth()/2) - (getX() + getWidth()/2));
        // Now the vertical distance
        float v_dist = Math.abs((other.getY() + other.getHeight()/2) - (getY() + getHeight()/2));
        // If h_dist > v_dist horizontal collision else vertical collision
        if (h_dist > v_dist){
            // Are we moving right?
            if (getX()<other.getX()){
                setX(other.getX()-getWidth());
            }
            // Are we moving left?
            else if (getX()>other.getX()){
                setX(other.getX()+other.getWidth());
            }
        } else {
            // Are we moving up?
            if (jump.active){
                jump.stop();
            }
            // We are moving down
            else {
                setY(other.getY()-getHeight());
                setVelocityY(0);
                onground = true;
            }
        }
    }
}

```

The problem is that the object jumps well but does not fall when moved out of platform. Here's an image describing the problem.

I know I'm not checking underneath the object but I don't know how. The map is a list of objects and should I have to iterate over all the objects???

Thanks

# Answer
Collision detection at platform specific games can be implemented utilizing several techniques.

* Speculative Contacts
* Minkowski Difference, etc

The following resources may help you
> 2 votes

---
Tags: java, collision-detection, platformer
---


# Question
Title: How to get a good picture of the health of a level-based game from analytics?
I am designing a level-based game where the user completes the level 1, then 2, 3 and so on. There are 200 levels and each is rather short: 60-ish seconds.

I am tracking

* Each played, completed (cleared for the first time), failed and cleared level
* Milestones: number of players to reach level 1, 5, 10, etc. Also for number of failed and played levels.
* Separate new players from returning ones.

However, I still find it difficult to get a clear picture of what is going on from the stats. So what are the best practices for determining where I am losing players?

# Answer
> 3 votes
you are asking probably one of the hardest questions - you will find that a lot of data being collected, by a lot of companies, is not used because no one knows how to undersand it. its a full time job that few small studios / startups can invest in (althought they should, lol!)

I suggest, you start by collecing very little data at the begining - pick a few points that YOU think are important in the game. look at the data DAILY or in general regularly and look for patterns. Add more datapoints as you realize you want more insight into some part.

example - start by collecting - did player complete a level or not. look for patters - where are most ppl dropping off. then start breaking the leveldown further

Collecting too much data is the first step to being discouraged and not using any of it :)

Also, i suggest A/B testing. If you think some change you will make a difference, never, ever make the change for all players and try to read the data. Always change the game for 1/2 of the player (A group) and the other half continues to play as before (b group).

then compare the groups

good luck!

# Answer
> 0 votes
You say that you separate new players from returning ones. It may be possible on some platforms, but usually not because of privacy issues. And so cookies may be cleared, IP changed, Flash Shared Object flushed together with browser's history etc. In the end some of players that are supposed to be 'new' will really be old, returning players with changed identity, making some of your stats misleading.

I suggest that you track not places that players get to, but where they quit the game - generate random unique ID at start of the game, and save in stats new `lastPosition` for this ID every time the player gets to some checkpoint. Additionally, if you get some event like `onExit` or `onUnload`, you could use it to log soft quits. In the end you would have data of either

* User quits "soft" way exactly at point X
* User quits in hard way (disconnect/hard reboot/bug) between checkpoints A and B

You could also ask players for opinions on soft quits, or upload your game to a service with comments like Kongregate.

---
Tags: analytics
---


title: Rotating Sprite around Y-Axis (2D)

text:
# Question
Title: Rotating Sprite around Y-Axis (2D)
I'm going to be creating a game soon, and part of it involves spinning sprites. The sprites will be spinning around the Y-Axis (imagine a spinning plate on top of a stick, where the stick stands up vertically.

The main way I've thought of is to have a series of sprites for various rotation values that I blur between as the 'plate' rotates (the sprite is more complex than a plate, though).

The game will be for iPhone, but I'm open to using any 2D gave development library for it.

# Answer
This answer will help if you want to use a textured quad, but not if you want to use a series of pre-rotated sprites.

First, determine the pivot point of your sprite. If your sprite is `32x32` and you want to spin the sprite around its center, then its pivot point will be `(16, 16)`. Simple.

```
const tb::Vec2& pivot = m_Sprite->GetPivot();
const tb::Vec2& dim = m_Sprite->GetDimensions();

```

Then, create a 2D matrix. In your case, you want:

```
tb::Mat3x3 transform;
transform.Identity();
transform.AddRotation(angle);
transform.AddTranslation(m_Position);

```

2D matrices are really easy. Here's what the final matrix looks like from the inside:

```
float rads = tb::Math::DegToRad(m_Rotation);

values[X1] = -tb::Math::Sin(rads);
values[Y1] =  tb::Math::Cos(rads);
values[WX] =  0.f;

values[X2] =  tb::Math::Cos(rads);
values[Y2] =  tb::Math::Sin(rads);
values[WY] =  0.f;

values[TX] =  m_Position.x;
values[TY] =  m_Position.y;
values[CZ] =  1.f;

```

Construct four corner points in object space. That sounds difficult, but it looks like this:

```
tb::Vec2 pos_ul = tb::Vec2(m_Position.x - pivot.x,         m_Position.y - pivot.y        );
tb::Vec2 pos_ur = tb::Vec2(m_Position.x - pivot.x + dim.x, m_Position.y - pivot.y        );
tb::Vec2 pos_ll = tb::Vec2(m_Position.x - pivot.x        , m_Position.y - pivot.y + dim.y);
tb::Vec2 pos_lr = tb::Vec2(m_Position.x - pivot.x + dim.x, m_Position.y - pivot.y + dim.y);

```

Using your matrix, you can transform those corner points:

```
pos_ul = transform * pos_ul;
pos_ur = transform * pos_ur;
pos_ll = transform * pos_ll;
pos_lr = transform * pos_lr;

```

And now you can use those coordinates for a textured quad.

For future reference:

* Any transformation can be done with a matrix.
* Try getting the end result you want without a matrix first and then try to turn it into a single matrix.
* Math is your friend!
> 3 votes

# Answer
I use rotsprite - it was designed for this purpose.
> 1 votes

# Answer
The normal way of rotating graphics on iOS is to add a translucent border to the image to have antialiased borders. There are many questions like these on SO, like https://stackoverflow.com/questions/8285354/line-is-not-smooth-on-layer-border-when-its-rotated, which includes a link to http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/ (most answers do).
> 0 votes

---
Tags: 2d, iphone, sprites, rotation
---


# Question
Title: Which algorithm used in Advance Wars type turn based games
Has anyone tried to develop, or know of an algorithm such as used in a typical turn based game like *Advance Wars*, where the number of objects and the number of moves per object may be too large to search through up to a reasonable depth like one would do in a game with a smaller search base like chess?

There is some path-finding needed to to engage into combat, harvest, or move to an object, so that in the next move such actions are possible.

With this you can build a search tree for each item, resulting in a large tree for all items. With a cost function one can determine the best moves.

Then the board flips over to the player role (min/max) and the computer searches the best player move, and flips back etc. upto a number of cycles deep.

Finally it has found the best move and now it's the players turn. But he may be asleep by now...

So how is this done in practice?

I have found several good sources on A\*, DFS, BFS, evaluation / cost functions etc. But as of yet I do not see how I can put it all together.

# Answer
> 4 votes
if you are only asking about the path finding problem you can use your answer in this question, but for the whole idea of how to implement an AI read the rest of my answer.

It's not always finding algorithm like A\* that decide what AI should do, usually for games with too many possiblities they use some state-machine that controls the actions and those search algorithm are used both to describe how choosed action should be done and to extrant usable information from all the game data.

for example i've been in robocup soccer simulatoin 3d team. the game is just like real soccer with some humanoid robots moving inside the field but the problem is you only have control over joints of robot body, so you have at first try not to lose your balance while moving! I think this problem is just as hard as implementing AI for an strategy game. in our team (and other teams in league) there was 3 stages of thinking: first to understand what server told us about the game field. server describes field using relative positions to the player so we have to transform all the input to undestand world position of object seen. then we had to choose which action should player do. should it run toward the ball? or is the robot already in possession of the ball and should kick it? or should he pass it to another player? and so on. this was decided using a state machine. and the last stage was to describe how the should we do the action state machine chose. for example if it's running how should I run to maintain my balance, or if I fall what should I do to stand up.

so to apply this approch to your AI problem, first we have gather all the input we can, in an strategy game it can be number units their position and their type. remember if you want your AI to act normal you can't give it any information on the map, if the player can't see what the AI is doing, AI shouldn't be able to know what's happening in player's base. then you have to extract useful information from that data. for example it's not really important if your opponent has many units far away from you, the only important ones are the ones near.

next step is to decide about high concept of what your AI should do in the next turn. just think as a general, you have some information, and for any action you order, your soldiors know how they should obey. so based on the information you just give an order, it can be moving units to some specific point or constructng a building or what ever you think you have to do at the moment. so there is a list of data, and a list of possible high level actions. it's usual to use an state-machine to determine for each dataset which action is better. in this stage state machine can also use algorithm to generate new data to help itself decide. for example based on the position of the units you can use A\* to determine minimum time needed to gather your soldiers around opponents base.

and for the last step you have to translate those high concept orders to game level commands. for example you've already defined for tanks how to move to the point a player assigns them using a click. so you can easily traslate what your state machine decides to the available user commands, like mouse clicks or keyboard shortcuts. you can also implement your AI version of controls like setting the exact position of AI units for the next step, but remember giving your AI much more abilies may lead to unrealistic AI opponent.

# Answer
> 0 votes
Working with @Gajet and @BlueRaja 's input (the optimum is somewhere in the middle?):

Let's assume a finite state machine for the item/character that decides on an item level how it behaves (e.g. idle, create and follow path, attack, capture building, heal, defend other item) with some cost function. That would give 6 possible scores for this item.

Note: behavior may not be the right term, because it's the overall AI that decides in the end what each item is to do (see below).

In the screenshot below, red has 5 items, blue has 7 (neglecting the factories for the time being). Lets assume, blue is the AI and is to move next.

(picture to follow, I am not allowed to post yet, need \> 10 rep points)

With 7 units and 6 states/scores per unit, there are 7\*6=42 possible scores in total, yet not independently, as the scores of items may interfere, i.e. if the enemy is killed by item A, it cannot be killed again by item B.

So this is where the search tree starts: out of the 42 states/scores, select 1, e.g. start with the higher scores first. With this state fixed, there are 6\*6=36 states remaining for the second level of this node. We now need to check if something has changed in the situation because of the action of item 1, or if the remaining 36 states are still valid. With, or without update, again pick one out 36 and proceed with the remaining 5 items. When at the lowest level move backwards to the top and pick the 2nd best move of the 1st item and build the next branch. This will create a tree of 42\*36\*30\*24\*18\*12\*6=1.4 billion nodes.

This is too much, but it is also clear that there are many useless nodes in this tree, for one because the order of actions may have an effect, but in most cases it has no effect. Also, branches with low scores may turn out be be beneficial after the opponent has played (like an piece offer in chess), but most of them are not. (how to decide?).

To reduce the search tree, you could decide to limit the number of states per item to be considered. E.g. only pick the best and 2nd best. (could be a parameter in the program setting). This helps: 7\*2=14 possible states to start with and 14\*12\*10\*8\*6\*4\*2=645 thousand nodes in total. Probably still many doubles.

Assuming this can still be much improved, but a search tree is created. Add the scores per branch up to the top and select one (there will be many) with the highest score. This is the first AI move.

Now we get to the minimax.

Flip sides and repeat the above for the red items. Minimizing the score. Pick a move, execute and flip back to the blue side. Depth = 1.

Store the score - create a new search tree - blue moves - flip - new tree - red moves - flip - depth = 2 - store score. Continue up to a predefined depth.

This blows up, because at every blue move (645 thousand), red can respond with a similar amount of moves (actually 5\*2=10\*8\*4\*2=640 in this case), but with 7 units the total number of combinations would be 0.4 trillion. And for each you would like to search some levels deep...

Unless the search tree is seriously pruned, this goes nowhere.

Will alpha beta sort this mess?

# Answer
> 0 votes
To have pathfinding (A\*) and high-level systems (state machines) is not an either/or approach. You'll want to use both. The high-level systems tell each unit how to act, and each unit performs the best way it knows how (pathfinding).

I doubt that Advance Wars doesn't use pathfinding for unit movement. The maps are very small and the unit cap is so low, and with the Nintendo DS' specs on such a manageable scenario, A\* would hardly be time-consuming.

I think you're looking at this like Chess where the AI plans so and so moves ahead for each unit. It doesn't work like that. Ray Dey does a good job at explaining how strategy game AI works so I'll link to his explanation: https://gamedev.stackexchange.com/a/21617/22314

Here's a few things I'll add:

There are many methods to make the high level A.I. system.

Finite-state machines, as mentioned, are the most basic systems. You define states (idle, attack, defend, etc.), how the AI behaves in each state, and how and when should the AI move between the various states. Do that, and you can watch the AI move on its own.

There's behaviour trees, which eschew states and work like a decision tree. They work similar to programming flowcharts.

There's goal-oriented action planning (GOAP). This is where you define actions that units can do, the goals for a unit, and which action satisfies which goal. Its up to the AI then to decide which action to do to achieve some goal.

---
Tags: algorithm, path-finding, turn-based, strategy, chess
---


title: SharpDx: using maximized RenderForm

text:
# Question
Title: SharpDx: using maximized RenderForm
I'm trying to learn DirectX via SharpDX, very new to this. What I want to do is be able to draw 2D shapes for a game I'm trying to make. So I started with the demo "MiniRect" that came with SharpDX. Since I want my game to be full-screen, I changed the RenderForm to be maximized (using WindowState) and set the FromBorderStyle to None.

I noticed that even if the form is set to maximized, it's size is always 800 by 600. In my renderloop, if I specify the location for the rectangle has 400 by 300, it is drawn in the middle of the screen. If I try to set the location via mouse-click (using the RenderForm's MouseClick event, there is always an offset present between where the mouse was clicked and where the drawing shows up. My system DPI is set to the standard (96) so there shouldn't be any scaling. But it looks like there is a scaling factor of about 2.4

If it's not the DPI settings, does anyone have any idea what this be related to? The problem doesnt happen if the RenderForm is not maximized. Is there another way to be drawing full-screen using SharpDX?

Thanks

# Answer
> 1 votes
I found the problem.

I have maximized the size of the renderform, but forgot to change the size of the buffers in the swapchain. Once I got the new form size using form.MaximumSize and set that in the SwapChainDescription, my graphics were no longer stretched out.

---
Tags: c#, directx, sharpdx
---


title: Developing for iOS on Linux

text:
# Question
Title: Developing for iOS on Linux
I am looking for an engine or library to develop a game for iOS on Linux.

High level, low level, GUI, no GUI, does not matter too much. I am really looking for anything.

I'm not actually talking about deploying to iOS from Linux or anything like. I just want to do the bulk of the work on Linux, with minimal changes required to run it on iOS.

Edit: YES, I do have access to a Mac, but it is limited. So I want to be able to work on the project on my regular Ubuntu box.

Also, I am in the paid developer program, so I can deploy to iOS devices from the Mac.

# Answer
You're pretty much screwed - while there are many libraries and frameworks that allow development on Linux, to do any serious testing you'll need a Mac (or Hackintosh, din't say it). Deployment is one problem, but testing on any simulator is another.

Linux also doesn't run Unity, which would be another good solution.

However, you can take a look at one of the many home rolled solutions. In particular, a really low level solution would be using SDL 1.3+ -- it has built in support for iOS as a target.
> 1 votes

# Answer
If you want to test your app on a real iOS device and later release it, there is no legal way but to purchase a mac device. but If you are looking for a way to develop an app and test it on emulators, you can try using gnustep. note that can try an app written by gnustep, using a jail broken device.

besides if you don't mind working with C++ there is cocos2d-x you can try.

the last option (which also is illegal) is to use emulated MacOS.

this question is also somehow duplicate on StackOverFlow: https://stackoverflow.com/questions/276907/starting-iphone-app-development-in-linux
> 1 votes

# Answer
I now have full time use of a Mac, so I no longer need to develop for iOS on a Linux machine.

However, gameplay (gameplay3d.org), an open source project by Research In Motion (RIM), looks really good. It is primarily a 3D engine, and uses C++. It also has Lua scripting support.

I haven't actually tested gameplay on Linux, but it appears to have full support.
> 1 votes

# Answer
You can use Moai to develop iOS and Android apps from Windows, Mac, and Linux.

However, you're going to need a Mac in order to deploy or test your app.
> 0 votes

# Answer
You can develop a game with flash and build it to iOS using Adobe Air

However, you're going to need a Mac in order to deploy or test your app.
> -1 votes

---
Tags: ios, iphone, linux
---


# Question
Title: Lerping to a center point while in motion
I have an enemy that initially flies in a circular motion, while facing away from the center point. This is how I achieve that:

```
position.Y = (float)(Math.Cos(timeAlive * MathHelper.PiOver4) * radius + origin.Y);
position.X = (float)(Math.Sin(timeAlive * MathHelper.PiOver4) * radius + origin.X);

if (timeAlive < 5)
{
   angle = (float)Math.Atan((0 - position.X) / (0 - position.Y));

   if (0 < position.Y)
      RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(-1 * angle);
   else
      RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(MathHelper.Pi - angle);
}

```

That part works just fine. After five seconds of this, I want the enemy to turn inward, facing the center point. However, I've been trying to lerp to that point, since I don't want it to simply jump to the new rotation. Here's my code for trying to do that:

```
else
{
   float newAngle = -1 * (float)Math.Atan((0 - position.X) / (0 - position.Y));
   angle = MathHelper.Lerp(angle, newAngle, (float)gameTime.ElapsedGameTime.Milliseconds / 1000);

if (0 < position.Y)
   RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(MathHelper.Pi - angle);
else
   RotationMatrix = Matrix.CreateRotationX(MathHelper.PiOver2) * Matrix.CreateRotationZ(-1 * angle);
}

```

That doesn't work so fine. It seems like it's going to at first, but then it just sort of skips around. How can I achieve what I want here?

# Answer
It looks like you want 3 states for your enemy: facing away, transitioning, and facing in.

Try something like this:

```
// facing away
if (timeAlive < 5)
{
    angle = (float)Math.Atan((0 - position.X) / (0 - position.Y));

    // set rotation matrix
}
// transitioning
else if (timeAlive < 7) // i arbitrarily picked a transition time of 2 (7 - 5 = 2)
{
    float oldAngle = (float)Math.Atan((0 - position.X) / (0 - position.Y));
    float newAngle = -1 * (float)Math.Atan((0 - position.X) / (0 - position.Y));
    angle = MathHelper.Lerp(oldAngle, newAngle, timeAlive - 5);

    // set rotation matrix
}
// facing in
else
{
    float angle = -1 * (float)Math.Atan((0 - position.X) / (0 - position.Y));

    // set rotation matrix
}

```
> 1 votes

---
Tags: xna, linear-algebra
---


# Question
Title: Draw Rectangle To All Dimensions of Image
I have some rudimentary collision code:

```
public class Collision {
    static boolean isColliding = false;
    static Rectangle player;
    static Rectangle female;

    public static void collision(){
        Rectangle player = Game.Playerbounds();
        Rectangle female = Game.Femalebounds();

        if(player.intersects(female)){
            isColliding = true;
        }else{
            isColliding = false;
        }
    }
}

```

And this is the rectangle code:

```
public static Rectangle Playerbounds() {
    return(new Rectangle(posX, posY, 25, 25));
}

public static Rectangle Femalebounds() {
    return(new Rectangle(femaleX, femaleY, 25, 25));
}

```

My InputHandling class:

```
public static void movePlayer(GameContainer gc, int delta){
    Input input = gc.getInput();

    if(input.isKeyDown(input.KEY_W)){
        Game.posY -= walkSpeed * delta;
        walkUp = true;

        if(Collision.isColliding == true){
            Game.posY += walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_S)){
        Game.posY += walkSpeed * delta;
        walkDown = true;

        if(Collision.isColliding == true){
            Game.posY -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_D)){
        Game.posX += walkSpeed * delta;
        walkRight = true;

        if(Collision.isColliding == true){
            Game.posX -= walkSpeed * delta;
        }
    }

    if(input.isKeyDown(input.KEY_A)){
        Game.posX -= walkSpeed * delta;
        walkLeft = true;

        if(Collision.isColliding == true){
            Game.posX += walkSpeed * delta;
        }
    }
}

```

The code works partially. Only the right and top side of the images collide. How do I correct the rectangle so it will draw on all sides?

# Answer
```
//This checks overlap in a single dimension -- either x or in y
public boolean checkOverlap(int start0, int end0, int start1, int end1)
{
    if(start0 > start1 && start0 < end1)
        return true;
    if(start1 > start0 && start1 < end0)
        return true;
    return false;
}

//This does it for two dimensions. If overlapping in X AND Y, you've collided.
//You can call this in your movePlayer handler, but if the "females" (er!) move
//AS WELL, then you must do it per update or you will miss collisions (unless
//you make sure all "females" are moved before the player, on each update).
public bool isColliding(Rectangle rect0, Rectangle rect1)
{
    if (checkOverlap(rect0.x, rect0.x + rect0.width, rect1.x, rect1.x + rect1.width) &&
        checkOverlap(rect0.y, rect0.y + rect0.height, rect1.y, rect1.y + rect1.height))
    {
        //resolve your collision. You don't need to store isColliding -- just
        //calculate, then act on the result.
    }
}

```

On each game loop update: Get your inputs, move the player, get all inputs for other entities and move them, then at the end, run through the full entities list (player + "females") and run `isColliding()` on each. This the standard way to do 2D AABB collisions.

Actually if you are running through the full list of n entities and comparing them against n-1 other entities, then for the first entity in the list, call it **a**, you will have to check against **b** through **n**, but on checking **b** you will not have to check it against **a** (since **a** was just checked against **b** in the prior step) or itself, so you would check from **c** through **n**... and so on for each remaining entity. This essentially looks like:

```
for (int i = 0; i < entities.length; i++) //run through ALL entities
{
   Entity e1 = entities[i];
   for (int j = i+1; j < entities.length; j++) //run through each entity AFTER e1
   {
       Entity e2 = entities[j];
       if (isColliding(e1.rect, e2.rect))
           resolveCollisionFor(e1, e2);
   }
}

```
> 2 votes

# Answer
Looking at your code I think you forgot calling `Collision.collision();` before checking if `Collision.isColliding == true` so `Collision.isColliding` has always the same value
You should do something like this:

```
if(input.isKeyDown(input.KEY_W)){
    Game.posY -= walkSpeed * delta;
    walkUp = true;
    Collision.collision();
    if(Collision.isColliding == true){
        Game.posY += walkSpeed * delta;
    }
}

```
> 0 votes

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


# Question
Title: References about Game Engine Architecture in AAA Games
Last weeks I focused on game engine architecture and learned a lot about different approaches like component based, data driven, and so on. I used them in test applications and understand their intention but none of them looks like the holy grail.

So I wonder how major games in the industry ("AAA Games") solve different architecture problems. But I noticed that there are barely references about game engine architecture out there.

Do you know any resources of game engine architecture of major game titles like Battlefield, Call of Duty, Crysis, Skyrim, and so on? Doesn't matter if it is an article of a game developer or a wiki page or an entire book.

I read this related popular question: Good resources for learning about game architecture? But it is focused on learning books rather than approaches in the industry.

Hopefully the breadth of our community can carry together certain useful informations! Thanks a lot!

Edit: This question is focused but not restricted to first person games.

# Answer
> 2 votes
**Book References**

**Community References**

**Source Code References**

# Answer
> 0 votes
ID Software recently released the sourcecode of Doom 3 on Github: https://github.com/TTimo/doom3.gpl

There are also a lot of articles which analyzed it, like this one: http://fabiensanglard.net/doom3/index.php

---
Tags: education
---


# Question
Title: javascript game loop and game update design
There is a main game loop in my program, which calls game update every frame. However, to make better animation and better control, there is a need to implement a function like `updateEveryNFrames(n, func)`.

I am considering implementing a counter for each update. The counter will be added by one each frame. The update function will be invoked according to the `counter % n`.

For example, in a sequence of sprites animation, I can use the above function to control the speed of the animation.

Can some give some advice or other solutions?

# Answer
> 3 votes
So what you want is one loop to run slow (say 10 fps or hz), and another loop for animation to run faster (30fps or hz), yes?

You can do it the way you say but actually it's much simpler when done something like:

```
//we are working in ms for setTimeout's sake; 1000ms per second
var ANIMATION_FREQ = 33;
var ANIMATION_PERIOD = 1000 / ANIMATION_FREQ;
var LOGIC_FREQ = 10;
var LOGIC_PERIOD = 1000 / LOGIC_FREQ;

setTimeout(ANIMATION_PERIOD, updateAnimation);
setTimeout(ANIMATION_PERIOD, updateGameLogic);

void updateAnimation() { ... do animation stuff... }
void updateGameLogic() { ... do game logic stuff... }

```

There is nothing wrong with just running two separate timers in parallel like this -- since your view should be well decoupled from your data and control logic anyway.

An excellent source on how best to implement timing is Gaffer's Fix Your Timestep.

As to what you do inside `updateGameLogic`:

1. Accept input from player(s) (via input devices, eg. pressing up arrow might equate to input code "up")
2. Accept input from AIs (via either functions or classes that produce same as input codes for player, eg. FSM AI wants to go up means it will produce output "up")
3. Based on inputs, perform your basic physics or otherwise do movement per entity, and add new entities. You must not add or remove entities *directly* to your entity list in this phase, because you are still in the midst of processing the entity list. You can add eg. new bullet entities in this phase by adding them to an "additions" list.
4. Run through entities, testing each against every other for a possible collision (see 2nd part of my answer here). Any entities that get expired (eg. due to a collision) must *still not* be removed immediately, but rather **added** to a "removals" list (because otherwise you will break the list while it's being processed for physics.
5. Finally, add everything in the additions list to the main entity list, and remove everything in the removals list from the main entity list. Then flush those two auxiliary lists so they are ready to be used for the next update.

You're using a separate loop for animation / rendering, so you don't need to worry about including it here, but many people put that in as a final step (which causes issues as Gaffer notes in his article.)

You can also refer to this question for some overview of the order inside your update function.

---
Tags: javascript, game-loop
---


title: Greiner-Hormann clipping problem

text:
# Question
Title: Greiner-Hormann clipping problem
I have a set of planar polygons in 3D space defined by their vertices in **counterclockwise** order. Let's define the 'positive face' as being the face of the 3D polygon such as when observed, the vertices appear in **counterclockwise** order, and the 'negative face', the face which when observed, the vertices appear in **clockwise** order.

I'm doing perspective projection of the set of polygons onto a *projection* polygon defined by the points in this order: (0, h, 0), (0, 0, 0), (w, 0, 0), and (w, h, 0), where w and h are strictly positive integers. The positive face of this projection polygon is oriented towards positive Z, and the camera point is somewhere at (0, 0, d), where d is a strictly negative number.

In order to 'clip' the projected polygons into the projection polygon, I'm applying the Greiner-Hormann (PDF) clipping algorithm, which requires that the clipper and the to-be-clipped polygons be in the same order (i.e. clockwise or counterclockwise).

My question is the following:

How can I determine whether the projected face of the 3D polygon is the negative or the positive one? Meaning, how do I find out if I have to work with the vertices in normal or inverted order for the algorithm to work?

I noticed that only if the 3D polygon is facing the projection polygon with its negative face, both of them are in the same order (counterclockwise), otherwise, a modification needs to be done.

Here is a picture that illustrates this:

Note that the planes described by the polygon from the set and the projection polygon may not always be parallel.

# Answer
> 0 votes
Given three points of the polygon in normal order `p0`, `p1`, `p2`

1. Calculate the direction of the normal of the plane the triangle defined by points p0, p1, p2 lies in:

```
normal_direction = cross(p0 - p1, p2 - p1)

```

Do it for both polygons, the projection polygon and the 3D polygon in question
2. Take the dot product of the normal of both polygons. if the dot-product is bigger or equal 0, both are in the same order. If it is smaller than zero, you need to inverse the order of the points.

---
Tags: 3d, projection, clipping
---


title: Rendering multiple squares fast?

text:
# Question
Title: Rendering multiple squares fast?
so I'm doing my first steps with openGL development on android and I'm kinda stuck at some serious performance issues...

What I'm trying to do is render a whole grid of single colored squares on to the screen and I'm getting framerates of ~7FPS. The squares are 9px in size right now with one pixel border in between, so I get a few thousand of them. I have a class "Square" and the Renderer iterates over all Squares every frame and calls the draw() method of each (just the iteration is fast enough, with no openGL code the whole thing runs smootlhy at 60FPS). Right now the draw() method looks like this:

```
// Prepare the square coordinate data
GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                GLES20.GL_FLOAT, false,
                                vertexStride, vertexBuffer);

// Set color for drawing the square
GLES20.glUniform4fv(mColorHandle, 1, color, 0);

// Draw the square
GLES20.glDrawElements(GLES20.GL_TRIANGLES, drawOrder.length,
                        GLES20.GL_UNSIGNED_SHORT, drawListBuffer);

```

So its actually only 3 openGL calls. Everything else (loading shaders, filling buffers, getting appropriate handles, etc.) is done in the Constructor and things like the Program and the handles are also static attributes. What am I missing here, why is it rendering so slow? I've also tried loading the buffer data into VBOs, but this is actually slower... Maybe I did something wrong though.

Any help greatly appreciated! :)

# Answer
Several thousand draw calls is enough to slow down a desktop, let alone a mobile.

Refer to geometry batching. That is, instead of creating 1000 tiny meshes, just create 1 gigantic mesh. Just try to make sure the number of vertices doesn't exceed 65536 (since the vertex index register is only 16-bit wide, 2 to the 16th power = 65k).

Further, to get the same sort of output you're getting right now, you'd use vertex coloring. I would just search on "OpenGL ES 2 vertex color". This answer gives you a good idea -- it's just another array like the position or index arrays that you already supply for upload to the graphics card.

**NB:** Because you want hard colour edges between your tiles (as opposed to interpolated vertex colours), you will need to create duplicate vertices at all of the corners which you might ordinarily think a vertex would be shared by two or more tiles. This is just a limitation you'll have to live with. (There is another way to do this without duplicating verts, but it involves using a non-bilerp texture laid onto one very large 4-vertex quad -- definitely efficient but I don't know how if you need your tiles destructible / replaceable so ignore this for now, you can comment here later if you want me to elaborate.) So in a grid like this, which accomodates 4 quads:

```
1-2-3
| | |
4-5-6
| | |
7-8-9

```

You would need 1 vertex each at **1, 3, 7, 9**, 2 vertices at **2, 4, 6, 8**, and 4 vertices at **5**, reflecting how many quads each labeled position is shared by.

So just as if you were setting up one of your current draw calls, you run a big nested loop to create all your vertex positions, vertex colours and vertex indices in order, and upload them like so. You will need an extra `glVertexAttribPointer` for your colour array, among other things. But I leave the nasty codey bits to you, as this is more a conceptual answer. I would suggest that you work from the simplest test case, i.e. change your code to spit out just one simple quad, as you have it at present, make it white for instance, enlarge its dimensions, then start pushing additional geometry into that same batch and get it working that way until you have all your mini tiles overlaid over your larger white tile.
> 4 votes

---
Tags: opengl, 2d, android, 3d-meshes, procedural
---


title: Android Array Lag?

text:
# Question
Title: Android Array Lag?
I am making a platform game for Android. It is sort of a tile based game. I added bullets and enemies with AI and a bunch of tile types.

I created a simple map with no Enemies. Everything was running well and smooth until I shot a bunch of bullets randomly everywhere. A couple of hundreds of bullets later, the FPS lowered.

I made a test to find out if the bullets were the problem so I made another simple map with just a tile to stand on and left it for a while. Minutes later, I played around with it a bit to check if the FPS changed and it didnt. I reloaded the same map and shot a lot of bullets. Minutes later, the FPS was visibly lower even after the number of bullets were zero.

Points to note:

* Programmed FPS is 30
* Tested on a Samsung Galaxy Y and Samsung Galaxy W
* Any tile, enemy, bullet that is off screen is not drawn to prevent lag
* Bullets collide with Tiles (if they dont collide with in 450 frames, they are removed from the array)
* I used List bullets = new ListArray();
* I used bullets.add(new Bullet(x, y, params...));
* I used for(...){ if(...){ bullets.remove(i); } }

Code for bullet:

```
private void drawBullets(Canvas canvas) {
    for (int i = 0; i < bullets.size(); i++) {
        Bullet b = bullets.get(i);
        b.update(canvas); //updates physics
        if (b.t > blm) { //if the bullet is past its expiry
            bullets.remove(i);
            i--;
        } else {
            if (svx((b.x)) > 0 && svx(b.x) < width && svy((b.y)) > 0
                    && svy(b.y) < height) { // if bullet is not off screen
                b.draw(canvas); // draw the bullet
            }
        }
    }
}

```

I tried searching for solutions and references but I have no luck. I'm guessing that the lag has something to do with the Array and the Bullets or Classes that I've loaded? I'm not sure!

Someone please help!

Thanks in advance! :)

# Answer
> 3 votes
Sounds like you're not cleaning up your bullets. They can't stay in the world forever, because everything that exists in the world requires processor time and consumes memory, also.

So you really need to keep track of projectiles that will just "expire" after a while (in most games we just do an alpha fade to prevent it from looking jarring). The simplest way to do that is just to have an "age" value on each bullet object that tracks the time in seconds/milliseconds/nanoseconds since the object was created. Each age value starts out at zero. Then on each game loop update, you're running through every entity to process it anyway, so you just look at the ones that are bullets and say

```
for (Entity entity : entities)
{
    //...stuff to do wtih other entity types
    if (entity instanceof Bullet) //or eg. if (entity.category == "bullet")
    {

        if (bullet.age >= EXPIRY_AGE)
        {
           //make sure bullet gets removed from list after we exit this foreach loop
        }
        else
        {
            bullet.age += howeverManyTimeUnitsHavePassedSinceLastUpdate;
        }
    }
}

```

This requires you to know how much time passed since the last step. If you're using a fixed timestep, that's easy -- it's whatever value your fixed timestep period is (1/fps). If not, then you may need to calculate time deltas.

# Answer
> 0 votes
**Step 1**

Try at other devices + OS versions

> On some devices that have auto-frame rate, this sets the maximum frame rate, not a constant frame rate. Actual frame rate will vary according to lighting conditions.

Because

> The actual frame rate is dependent on the certain device(hardware) and OS version. It seemed that HTC Desire has a higher FPS than the HTC Desire z. Moreover, Android 2.2.1 has better frame rate control method than Android 2.3.3 does.

**Step 2**

If not solved then, check any problem at your algorithm or try to improve your algorithm.

* Are you cleaning up your bullets?
* Is there other codes that requires much processor time?
* Is there other codes that consumes much memory?

---
Tags: java, android, html-canvas
---


# Question
Title: Architectural approaches to creating a game menu/shell overlay on PC/Linux?
I'm am working on a collection of games for a custom digital tabletop installation (similar to Microsoft Surface tables). Each game will be an individual executable that runs full-screen. In addition, there needs to be a menu/shell overlay program running simultaneously. The menu/shell will allow users to pause games, switch to other games, check their game history, etc.

Some key requirements of the shell:

* it intercepts all user input (mainly multitouch) first before passing it on to the currently running game (so that it can, for instance, know to pop-up at a "pause" command);
* can reveal on arbitrary portions of the screen, with the currently running (but presumably paused) game still showing underneath, ideally with its shape/size being dynamic, to allow for creation of an animated in/out drawer effect over the game.

I'm currently looking into different architectural approaches to this problem, including Fraps and DirectX overlays, but I'm sure I'm missing some ways to think about this. What are the main approaches I should be considering?

(Note the table is currently being run by Windows PC, but it could potentially be a Linux box instead. By this I don't mean I need an OS-agnostic solution. I'd be happy with a Windows-specific solution. But I would be willing to consider switching to Linux and using a Linux-specific solution if it's much easier to achieve this in Linux.)

# Answer
> 3 votes
I don't think there's much to evaluate, really. Performance / responsiveness comes first, especially on an installation of this sort. You can use either DirectX or OpenGL deferred rendering / render-to-texture (RTT).

To do so, render the shell underlay to the default frame buffer (the front / onscreen buffer), render your active game overlay to a screen-sized quad, shift this quad to the appropriate position in world space as per current status of "drawer" transition, then render it's to the default frame buffer as well. You now should have the active game laid over the shell, and it's a very rapid operation and thus lends itself to slick transitions (given some nice interpolation math).

Re interactions, you can even make the under/overlay hit detection pixel-perfect if you read back the RTT data to CPU-side, per frame. In that case, you'd need to return at least the overlay buffer as a cheap, 1-bit mask RTT.

**EDIT** Another way is to go fully browser based, as you can do full screen mode. You could load the games in as modules rather than having separate "programs". The problem with the browser is you aren't going to get the same performance. You could still use WebGL (since you would have control over which browser you'd be using) for layering and fast graphics, but the games would need to be simple. Aside from performance, it might be a fair bit easier to develop this way, and still OS-agnostic.

---
Tags: architecture, windows, linux
---


title: Character equipment combinations

text:
# Question
Title: Character equipment combinations
> **Possible Duplicate:**
> Which is the best approach to make a 2D character to be able to use tons of different equipments when in action?

I'm developing a 2d isometric game (typical Tolkien RPG) and wondering how to handle character/equipment combinations. So for example, the player wears leather boots with chain-mail and a wooden shield and a sword - but then picks up plate-armour instead of chain-mail.

I'm using Blender3D to create objects, environments and characters in 3D, then a script runs to render all 3D meshes into 2D orthographic tile maps. So I can use this script to create all the combinations of character equipment for me, but there would be an explosion in terms of the combinations required.

# Answer
Most 2d games solve this problem with the "paperdoll" technique.

You create a spriteset for the "naked" player character (you might want to add underwear to avoid nudity), and you create separate spritesets for all boots, shirts, pants, headgears etc. These equipment spritesets only contains the item itself, nothing else. When the player character is drawn, all the sprites are drawn on top of each other in a predetermined order.

So you first draw the naked character, then its boots over the naked sprite, then its pants, then its shirt and then its helmet.

When performance is a concern, you can optimize it by caching the appearance of all the sprites over each other until the equipment changes.
> 4 votes

---
Tags: isometric
---


# Question
Title: Movement on the X an Z axis are combined?
This is probably a stupid question, but I'm trying to simply move a 3D object up, down, left, and right (Not forward or backward).

The Y axis works fine, but when I increment the object's X position, the object moves BOTH right and backwards! when I decrement X, left and forwards!

```
setPosition(getPosition().X + 2/*times deltatime*/, getPosition().Y, getPosition().Z);

```

I was astonished that XNA doesnt have its own setPosition function, so I made a parent class for all objects with a setPosition and Draw function. Setposition simply edits a variable "mPosition" and passes it to the common draw function:

> ```
>     // Copy any parent transforms.
>     Matrix[] transforms = new Matrix[block.Bones.Count];
>     block.CopyAbsoluteBoneTransformsTo(transforms);
>
> ```

```
    // Draw the model. A model can have multiple meshes, so loop.
    foreach (ModelMesh mesh in block.Meshes)
    {
        // This is where the mesh orientation is set, as well
        // as our camera and projection.
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();
            effect.World = transforms[mesh.ParentBone.Index] *
                Matrix.CreateRotationY(MathHelper.ToRadians(mOrientation.Y))
                * Matrix.CreateTranslation(mPosition);
            effect.View = game1.getView();
            effect.Projection = game1.getProjection();
        }
        // Draw the mesh, using the effects set above.
        mesh.Draw();
    }

```

I tried to work it out by attempting to increment and decrement the Z axis, but nothing happens?! So using the X axis changes the objects x and z axis', but changing the Z does nothing. Great. So how do I seperate the X and Z axis movement?

# Answer
> 1 votes
First..

you can set the translation of matrix easily...

```
Transform.Translation = yourTranslation;

```

Second...

I would render the axis base to see if it´s moving right.. because of your parent rotation or your camera view the behaviuor described maybe is right...

---
Tags: xna, c#, matrix, movement
---


# Question
Title: How to handle shoot instructions, in a multiplayer TD
I'm currently working on a Multiplayer Tower Defense game, using ImpactJS & Node. I seek some clarification about how to handle projectiles from towers, let me explain.

So the server is running the master game, and the clients just follow the instruction from the server. Lets say there is about 20 towers on the stage, all needs instructions for which creeps to shoot at. Now lets say each towers fires twice in a second, that's 40 shots each second, (worst case scenario) which is 40 request per second to each client, would't this casue alot of stress to the server, saying that we have 50 games running the same time. So what i am really asking, is this method inefficient, and is there a smarter way to handle all these instructions.

Thank you.

# Answer
First optimization: you don't need to grab instructions individually.

You have twenty towers firing twice a second. Synchronize their fire, or snap it to the nearest quarter second, and now you only have four updates per second, each containing ten fire instructions. Much more tractable.

If people can place towers to modify creep pathing, that's more of an issue. A quarter second of delay might result in creeps leaking when they shouldn't have. You can adjust game mechanics to make this less likely -- towers take time to construct and are passable terrain during that time, maybe, which also helps in that you don't need to provide firing instructions for towers as soon as they're placed.

Failing that, you can follow the tactic used by most FPS games: the client assumes that nothing important will change in the world before the next update to the server and simulates everything independently. When it gets a server update, it replaces its current world state with the newly provided one. This will produce things like teleporting creep, which isn't too great, but provides a lot more flexibility in game mechanics.
> 0 votes

---
Tags: javascript, optimization, node.js
---


# Question
Title: fast 3d point -> cuboid volume intersection test
Im trying to test whether a point lies within a 3d volume defined by 8 points. I know I can use the plane equation to check that the signed distance is always -1 for all 6 sides, but does anyone know of a faster way or could point me to some code?

I should add that ideally the test would produce 3 linear interpolation parameters which would lie in the range 0..1 to indicate that the point is within the volume for each axis (since I will have to calculate these later if the point is found to be in the volume)

# Answer
**Fast ray-box intersection (Andrew Woo)**

Graphics Gems (volume I) page 395.

source code

There used to be a full version of his original paper online, not not anymore it seems. In future, you can use this reference when you need any intersection test algo's.

FYI, this algorithm is derived from Amanatides & Woo's seminal paper on 3D-DDA, if you want some insight into how the diff logic operates.
> 1 votes

# Answer
Generate BSP (Binary Space Partioning) using the Cuboid. Each face of the cuboid is the partioning plane, and define the inside volume to be the volume that is always on the same subspace of all the faces. E.g:

1. Get next face. Calculate if point is in front or behind the plane

1. A: If it is behind, point is outside.
    2. B: If it is in front, goto 1
2. If you pass all the tests, point is inside
> 1 votes

# Answer
I think the solution to this problem in the scenarios Im certain to encounter (twisted sample points which dont maintain an "inside" and "outside" to the form) with this is to approach this as a transform to move a unit cube to the "cube" described by the 8 (most likely twisted & incoherent) sample points.

If it is possible to create such a transform, it means I can both test whether a point lies within this volume as well as generating the interpolation parameters needed for tri-linear and tri-cubic interpolation

To make this all clearer, Ive asked a more specific question!

matrix to transform unit cube to space defined by 8 arbitrary points

Thanks
> 0 votes

---
Tags: 3d
---


# Question
Title: How to update entity states and animations in a component-based game?
I'm trying to design a component-based entity system for learning purposes (and later use on some games) and I'm having some troubles when it comes to updating entity states.

I don't want to have an update() method inside the Component to prevent dependencies between Components.

What I currently have in mind is that components hold data and systems update components.

So, if I have a simple 2D game with some entities (e.g. player, enemy1, enemy2) that have Transform, Movement, State, Animation and Rendering components I think I should have:

* A MovementSystem that moves all the Movement components and updates the State components
* And a RenderSystem that updates the Animation components (the animation component should have one animation (i.e. a set of frames/textures) for each state and updating it means selecting the animation corresponding to the current state (e.g. jumping, moving\_left, etc), and updating the frame index). Then, the RenderSystem updates the Render components with the texture corresponding to the current frame of each entity's Animation and renders everything on screen.

I've seen some implementations like Artemis framework, but I don't know how to solve this situation:

Let's say that my game has the following entities. Each entity have a set of states and one animation for each state:

* player: "idle", "moving\_right", "jumping"
* enemy1: "moving\_up", "moving\_down"
* enemy2: "moving\_left", "moving\_right"

**What are the most accepted approaches in order to update the current state of each entity?** The only thing that I can think of is having separate systems for each group of entities and separate State and Animation components so I would have PlayerState, PlayerAnimation, Enemy1State, Enemy1Animation... PlayerMovementSystem, PlayerRenderingSystem... but I think this is a bad solution and breaks the purpose of having a component-based system.

As you can see, I'm quite lost here, so I'd very much appreciate any help.

**EDIT:** I think the solution to make this work as I intend is this one:

> You make statecomponent and animationcomponent generic enough to be used for all entities. The data they contain will be the modifier for changing things like which animations are played or which states are available. – Byte56

Now, I'm trying to figure out how to design these 2 components generic enough so I can reuse them. Might having an UID for each state (e.g. walking, running...) and storing animations in a map into the AnimationComponent keyed by this identifier be a good solution?

# Answer
> 5 votes
IMHO the `Movement` component should hold the current state (`Movement.state`) and the `Animation` component should observe changes of `Movement.state` and update its current animation (`Animation.animation`) accordingly, using a simple lookup of state id to animation (as suggested at then end of the OP). Obviously this means `Animation` will depend on `Movement`.

An alternative structure would be to have a generic `State` component, which `Animation` observes, and `Movement` modifies, which is basically model-view-controller (state-animation-movement in this case).

Another alternative would be to have the entity dispatch an event to its components when its state changes. `Animation` would listen to this event and update its animation accordingly. This eliminates the dependency, although you could argue that the dependent version is a more transparent design.

Good luck.

# Answer
> 2 votes
About your problem, if the STATE is only used in Animations, then you don't even need to expose that to other Components. If it has more than one use, then you need to expose it.

The system of Components/Subsystem that you describe feels more hierarchy-based than component-based. After all, what you describe as components are in fact data structures. It doesn't mean it is a bad system, just that I don't think it fits the component-based approach too well.

As you noted, dependencies are a big problem in component-based systems. There are different ways to deal with that. Some require each component to declare their dependencies and do a strict check. Others query for components implementing a specific interface. Still others pass reference to the dependant components when they instantiate each of them.

Independently of the method you use, you will need a GameObject of some sort to act as collection of Components. What that GameObject provides can vary a lot and you can simplify your inter-component dependencies by pushing some often-used data to the GameObject level. Unity does that with the transform for example, force all game object to have one.

Concerning the problem you ask of different states/animation for different game objects, here's what *I* would do. First, I wouldn't get too fancy at this stage of the implementation: only implement what you need now to get it working, then add bells and whistles as you need them.

So, I'd start with a 'State' component: PlayerStateComponent, Enemy1State, Enemy2State. The state component would take care of changing the state at the appropriate time. State is something pretty much all your objects will have, so it can reside in the GameObject.

Then, there would be an AnimationCompoment. This would have a dictionary of animations keyed to the state. In update(), change the animation if the state changes.

There's a great article about building framework that I can't find. It said that when you don't have experience in the domain, *you should pick one problem and do the simplest implementation that solves the current problem*. Then you add another problem/use-case and expand on the framework as you go along, so it grows organically. I really like that approach, particularly when working with new concept as you are doing.

The implementation I proposed is quite naive, but here are some possible improvements as you add more use-case:

* replace the GameObject variable with a dictionary. Each component use the dictionary to store values. (make sure to handle collision properly...)
* replace the dictionary of plain values with references instead: class FloatVariable() { public value \[...\] }
* Instead of multiple state component, create a generic StateComponent in which you can build variable state machines. You need to have a generic set of condition upon which a state can change: key presses, mouse input, variable changes (you can tie that to the FloatVariable above).

# Answer
> 0 votes
In addition to the answer of ADB you could use http://en.wikipedia.org/wiki/Dependency\_injection, which helps when you need to construct a lot of components via passing them as references to their constructors. Obviously they will still depend on each other (if that is required in your code base), but you can put all that dependency in one place where the dependencies are setup and the rest of your code does not need to know about the dependency.

This approach also works well if you use interfaces because each component class just requests what it needs or where it needs to be registered and only the dependency injection framework (or the place where you set everything up, usually the app) knows about who needs what.

For simple systems you might get away without using DI or clean code, your RenderingSystem classes sounds like you need to call them statically or at least have them available in each component, which pretty much makes them dependent on each other and hard to change. If you are interested in a more clean approach check the links of the DI wiki link above and read about Clean Code: http://clean-code-developer.com/

---
Tags: animation, entity-system, component-based, state
---


# Question
Title: How to model / where to store relational data between classes
I'm trying to figure out the best design here, and I can see multiple approaches, but none that seems "right."

There are three relevant classes here: Base, TradingPost, and Resource. Each Base has a TradingPost which can offer various Resources depending on the Base's tech level.

Where is the right place to store the minimum tech level a base must possess to offer any given resource? A database seems like overkill. Putting it in each subclass of Resource seems wrong--that's not an intrinsic property of the Resource. Do I have a mediating class, and if so, how does it work? It's important that I not be duplicating code; that I have one place where I set the required tech level for a given item. Essentially, where does this data belong?

P.S. Feel free to change the title; I struggled to come up with one that fits.

# Answer
> 1 votes
IMHO, the responsibility of managing which `Resource`s are available in a `TradingPost` should be in a separate controller-like class, `TradingPostController` for example.

`TradingPostController` observes changes of `Base.techLevel` and updates the `TradingPost`'s set of offered `Resources` accordingly. In this approach, `TradingPostController` will contain a mapping of tech level -\> resource set.

So the sequence of events would be:

* Tech-level of `Base` is increased.
* `Base` fires a "tech level changed" event.
* `TradingPostController` observes the event.
* `TradingPostController` updates `TradingPost.resources` (or so).

Good luck!

---
Tags: architecture, design-patterns, databases, data
---


title: Random Movement for multiple entities

text:
# Question
Title: Random Movement for multiple entities
I have this code for a arraylist of entities.

All the entities use the same random and so all of them move in the same direction. How can I change it so it generates a new random number for each entity?

```
public void moveFemale() {
    for(int i = 0; i < 1000; i++){
        random = rand.nextInt(99);
    }

    if (random >= 0 && random <= 25) {
        posX -= enemyWalkSpeed; // right
    }

    if (random >= 26 && random <= 50) {
        posX += enemyWalkSpeed; // left
    }

    if (random >= 51 && random <= 75) {
        posY -= enemyWalkSpeed; // up
    }

    if (random >= 76 && random <= 100) {
        posY += enemyWalkSpeed; // down
    }
}

```

Is this correct?

```
public void moveFemale() {
    for (Female female: GameFrame.females){

        female.lastChangedDirectionTime += elapsedTime;

        if (female.lastChangedDirectionTime >= CHANGE_DIRECTION_TIME)
        {
            female.lastChangedDirectionTime = 0;

            random = rand.nextInt(100);

            if (random >= 0 && random <= 25) {
                posX -= enemyWalkSpeed; // right
            }

            if (random >= 26 && random <= 50) {
                posX += enemyWalkSpeed; // left
            }

            if (random >= 51 && random <= 75) {
                posY -= enemyWalkSpeed; // up
            }

            if (random >= 76 && random <= 100) {
                posY += enemyWalkSpeed; // down
            }
        }
        }
    }

```

# Answer
> 1 votes
Your entities ("females") need to have a public member on them, something like

```
public int lastChangedDirectionTime = 0; //milliseconds

```

You also need some time interval at which you want them to change direction, set up as a constant:

```
public final int CHANGE_DIRECTION_PERIOD = 1000; //milliseconds

```

As each game loop goes by, get the amount of time that has elapsed since the last game loop iteration (if you don't have this value, comment!), and do

```
for (Entity entity : entities) //every one!
{
    entity.lastChangeDirectionTime += timeElapsed; //presumably both in the same time unit eg. seconds

}

```

As soon as you've done the addition, do this:

```
if (entity.lastChangeDirectionTime >= CHANGE_DIRECTION_PERIOD)
{
    entity.lastChangeDirectionTime = 0;

    //do your directional change logic, here.
}

```

I'm not 100% sure of your structure so you'll need to figure out where to slot these into your code.

---
Tags: java, random
---