# Question
Title: How should I implement a first-person camera?
I'm a beginner programmer and I'm creating a project which allows me to walk around rooms via a first person camera. So far, I have the buildings drawn and on, but now I'm stuck and don't know how to make a first-person camera to allow me to walk around.

Could anyone point me towards a camera class I could use, or some useful code?

# Answer
Here are some tips on camera rotation (mouselook). After naiively implementing a camera class from scratch, I found I had to do a few additional tweaks for good rotational behavior:

1. Reset mouse coordinates to center-of-screen on each frame, so that mouse never gets caught on the screen borders
2. Maintain the camera's "up" vector (disallow roll) and recompute the "sideways" vector
3. Disallow looking up past the vertical +y axis, or down past the -y axis (too far up/down)
4. Get the order of rotations correct (up/down first, then left/right)
5. Renormalize the "up", "aim", and "sideways" vectors each frame

Hopefully you can use some of this code to your advantage:

```
    const int mouseDeltaX = mouseAxisX * (input.GetMouseX() - int(app.GetWidth()/2));
    const int mouseDeltaY = -mouseAxisY * (input.GetMouseY() - int(app.GetHeight()/2));  // mouse y-offsets are upside-down!

    // HACK:  reset the cursor pos.:
    app.SetCursorPosition(app.GetWidth()/2, app.GetHeight()/2);

    float lookRightRads = mouseDeltaX * CAMERA_ANGULAR_SPEED_DEG * DEG_TO_RAD;
    float lookUpRads    = mouseDeltaY * CAMERA_ANGULAR_SPEED_DEG * DEG_TO_RAD;

    // Limit the aim vector in such a way that the 'up' vector never drops below the horizon:
    static const float zenithMinDeclination = DEG_TO_RAD * MIN_UPWARDS_TILT_DEG;
    static const float zenithMaxDeclination = DEG_TO_RAD * (180.0f - MIN_UPWARDS_TILT_DEG);

    const float currentDeclination = std::acosf(camera.aim_.y_);  ///< declination from vertical y-axis
    const float requestedDeclination = currentDeclination - lookUpRads;

    // Clamp the up/down rotation to at most the min/max zenith:
    if(requestedDeclination < zenithMinDeclination)
        lookUpRads = currentDeclination - zenithMinDeclination;
    else if(requestedDeclination > zenithMaxDeclination)
        lookUpRads = currentDeclination - zenithMaxDeclination;

    // Rotate both the "aim" vector and the "up" vector ccw by
    // lookUpRads radians within their common plane -- which should
    // also contain the y-axis:  (i.e. no diagonal tilt allowed!)
    camera.aim_.rotateAboutAxis(camera.right_, lookUpRads);
    camera.up_.rotateAboutAxis(camera.right_, lookUpRads);
    ASSERT_ORTHONORMAL(camera.aim_, camera.up_, camera.right_);

    // Rotate both the "aim" and the "up" vector ccw about the vertical y-axis:
    // (again, this keeps the y-axis in their common plane, and disallows diagonal tilt)
    camera.aim_.rotateAboutAxis(Y_AXIS, -lookRightRads);
    camera.up_.rotateAboutAxis(Y_AXIS, -lookRightRads);
    camera.updateRightAxis();

```

Note that:

mouseAxisX and mouseAxisY are defined to be +/-1, depending on whether you want the x or y axis mouselook inverted. Usually games offer this option at least for the vertical axis.

MIN\_UPWARDS\_TILT\_DEG is defined to be 1.0 degrees (so the viewer is allowed to look from -89 deg downwards to +89 degrees upwards, which looks quite convincingly like a full 180 degree vertical range -- the missing 2 degrees at the extremes are quite negligible).

camera.aim\_, camera.right\_, and camera.up\_ are of course 3D vectors, and the rotateAboutAxis() method you can cobble together from wikipedia and any number of online sources. Y\_AXIS is a fixed constant (0,1,0) vector.

ASSERT\_ORTHONORMAL() is a debug-mode-only sanity check, which never gets compiled in optimized/release mode.

Apologies in advance for the C-style code... then again, here you are taking advice from a guy named Mediocritus! ;^)
> 7 votes

# Answer
There are several ways of going about this (see tutorials here, here and here for example, with plenty more available on the Internet via Google). The technology used in the resources you may find online may vary slightly (in terms of D3D, XNA, OpenGL, et cetera), but the underlying principles are going to be the same:

* your camera object maintains its position and its direction, and optionally another pair of vectors that, alongside the direction, form an orthogonal basis for the camera's coordinate system.
* your camera's public API exposes methods for yawing, pitching, and optionally rolling the camera around it's basis vectors -- the act of adjusting the camera orientation will update the basis vectors for subsequent use.

You can elect to store the vectors directly, or recompute the underlying view matrix every time, as you need and prefer. There's a lot of flexibility to the technique, so if you need help beyond those general steps you may want to post a new question with a more specific query.
> 5 votes

# Answer
For a specific reference to an implementation of camera system using Direct3D, I recommend this article: http://www.toymaker.info/Games/html/camera.html. The author also describes other methods and features that may be used to expand on the implementation.
> 2 votes

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


# Question
Title: Getting started using C# and Physics (Resources, Tutorials, Samples, etc.)
As an application developer, I plan on now getting started in game development so I have come along to this site.

I am a proficient C# developer so I guess it makes sense to start game development in the same language, unless someone directs me otherwise.

I'm looking for some "getting started" type of tutorials that cover basic game architecture and essential physics such as collision, velocity, gravity, friction etc.

I know about XNA and physics engines such as farseer but, at the moment, I'd like to get started without attaching myself to a particular framework or set of classes.

Please let me know of good resource, tutorials, etc. that will get me started in this manner.

# Answer
> 1 votes
> I know about XNA and physics engines such as farseer but, at the moment, I'd like to get started without attaching myself to a particular framework or set of classes.

You'll need to use some API for rendering, otherwise you won't be seeing the effects of your physics simulation. You say you are proficient in C#, but do you have any experience with graphics in C#? It could be for instance, just plain old GDI in WinForms, a DirectX wrapper like SlimDX or SharpDX, an OpenGL wrapper like OpenTK, or a game-oriented framework like XNA. Doesn't really matter which, but you'll need to learn at least one graphics API, otherwise how do you expect to see your physics running?

> I guess I'm trying to avoid using too large a framework that will do too much for me.

Then the suggestion to use XNA is quite valid. Take a look at this. This is the amount of code you need to add to an empty XNA project to get it to render a sprite. And that's pretty much the extent of what you'd need to learn from the framework in order to to play around with physics. In comparison, it's a lot less work than any of the alternatives I mentioned.

So if your intent is just to get your hands dirty with physics, I'd recommend learning the bare minimum required to do some rendering in XNA; and then try and play around with Velcro Physics (formerly Farseer Physics) for instance. Shouldn't be hard to find some tutorials by googling.

---
Tags: c#, physics
---


title: RTS engine tick rate

text:
# Question
Title: RTS engine tick rate
I've seen some varying tick rates used for RTS engines. Supreme Commander ran at a super-low 10 ticks per second. Is this normal for RTS engines, or do they normally have a higher tick rate?

# Answer
Most RTSes I've worked on (or seen the source code to) simulate at 25-60hz. Slower than that, and characters start to feel unresponsive to commands and the controls feel generally laggy.

It's fairly common to run some game components only once per *N* ticks, however — ie, to undersample them. For example, run AI at only 5hz while the rest of the game is at 30hz, so that AI only runs one out of six frames. Or you can "think" only ¼ of the entities per frame to balance load, stuff like that.
> 2 votes

# Answer
If we're stritcly talking about physics and logic, a super-low tick rate is probably OK.

But I would recommend to run animations and movement at a smooth 30 fps, especially if the game is 3d, zoomable, etc.
> 0 votes

# Answer
I assume that you're using a fixed-timestamp and variable rendering framerate, which is the sensible way of doing it on all systems nowadays.

I can't see a big motivation for running \> 20 ticks per second, because graphics rendering will interpolate anyway, doing more logic ticks just increases CPU usage without making the game better.

If you are going to be "clever" about collision detection, etc, you might manage with fewer ticks per second. Maybe 5?

There just need to be enough ticks per second that objects can't visibly move through each other (or other artifacts) due to the granularity of the simulation.

It's unlikely that a player's action will be responded to instantly anyway, the player expects some degree of lag when ordering objects to do things.

Construction, or even a simple "move this to there", is likely to take at least 5 seconds of real-time anyway.
> 0 votes

---
Tags: physics
---


title: Debug data visualization best practices

text:
# Question
Title: Debug data visualization best practices
I found debugging games especially hard for some obvious reasons. It's hard to monitor some internal values in dynamic, conditional breakpoints helps somehow, but only to detect some specific conditions. You don't get information that lead you there. Sometimes you just want to monitor some value, sometimes value are hard to interpret in their internal form (say a current path calculated by AI).

So I'm thinking about implementing kind of debug layer which will draw this information above gameplay in real time. The question is how to do it in most convenient and reusable way.

I'm currently thinking to make interface say `IDebugInfo`, implement it in all entities which I want to monitor, and add then to debug layer (it's a `DrawableGameComponent`) via GameServices. The debug layer will draw them. It can be turned on or off in realtime by removing/adding debug layer.

Does this sound good? I'm almost sure this was done many times already, is there some proved patterns?

**Update**. So, I implemented it this way:

```
// iface
public interface IDebugDrawable
{
    void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch);
}

// service
public class StateManager
{
    public StateManager()
    {
        this.DebugDrawables = new List<IDebugDrawable>();
    }

    public List<IDebugDrawable> DebugDrawables { get; private set; }
}

// debug screen draw
public override void Draw(GameTime gameTime)
{
    SpriteBatch sb = this.ScreenManager.SharedSpriteBatch;
    StateManager sm = this.ScreenManager.Game.GetService<StateManager>();

    sb.Begin();

    foreach (IDebugDrawable debugDrawable in sm.DebugDrawables)
    {
        debugDrawable.DrawDebug(gameTime, sb);
    }

    sb.End();
}

// implementation in game entity
public void DrawDebug(GameTime gameTime, SpriteBatch spriteBatch)
{
    spriteBatch.DrawString(
        DebugScreen.DebugFont,
        this.Cell.ToString(),
        this.Position,
        Color.White);
}

```

this looks like:

# Answer
You can collect draws from all your methods and then draw them all at once. (Because in debug draws you don't really care about ordering)

This you will call anywhere in your code (like in update method) - you an make DebugRenderer singleton

```
  DebugRenderer.Commands.Enqueue((sb)=> sb.DrawString(DebugScreen.DebugFont,
            this.Cell.ToString(),
            this.Position,
            Color.White);

```

This is a component that will do the drawing

```
    public class DebugRenderer : DrawableGameComponent
    {
       // Action of this queue can take DebugRenderer as parameter then you will have access to spritebatch and graphics device

       public Queue<Action<SpriteBatch> Commands;

       public void Draw(GameTime gameTime)
       {
            spriteBatch.Begin(); // we only have commands to spritebatch so you call begin
            while (Commands.Length > 0)
            {
                 var command = Commands.Dequeu();
                 command(this.spriteBatch);
            }
            spriteBatch.End();
       }
    }

```

It's not really a good design but for debugging it's great.
> 1 votes

# Answer
you could just do a key binding (that is not normally used in your game) that modifies the game state, and then in some section of your screen print out specific information about what is going on. Keep in mind that I have not worked with the debug layer, but I have done this with output.

remember that somethings are easier to see what is going on numerically (seeing that valueX is changing/not changing in this way), and other are easier to debug visually (it looks like that model is interpenetrating the wall)

the biggest thing is figuring out is what information is really needed for you to know that everything is working or not.

When I have done this in the past (was designing debug for keyboard) I mapped AI states/positions to one button, another button showing bounding volumes, another button outputting positions, and bounding data, and a final button that displayed every collision that was not purely Y (at one point I had things falling through the world, and had to just revers the bool check, but that a different story)
> 0 votes

---
Tags: xna, architecture, debugging
---


# Question
Title: What is the best way to make UI for an Isometric game in java
What do you think is the best way to make UI for an isometric game.. I dont have much experience in UI so im not sure where to start.

I need something the mouse can interact with and that works good and fast. I already created a world that is isometric you can move and the world scrolls and stuff but i would like to start with UI and im not sure what i should do.

I would like to have maybe a display that displays an image that i give it, that is part invisible, that it is on top of the main game panel and that i route an area to be clicked on it by a mouse. i would like some help with the code behind because I'm not sure how to get the specific area. By the way do you think this would be a good way?

Thanks for the help..

# Answer
> 3 votes
The best way is to use a library designed to provide GUI functionality. This will be specific to how you want to use it, and what you're using already. Here are some common ones:

---
Tags: java, gui
---


# Question
Title: Tutorial or Example of creating custom sprite tool/map editor for XNA?
I want to create various sprite tool and map editor using XNA. Now, the problem is I do not know how would I implement the window forms and components (such as button, check box, sprite list, etc.) into my program and allow it to completely control my XNA environment. If there is any tutorials or examples that show how to make editor for XNA, then I would be very pleasing.

Thanks

# Answer
I have done several editors... and the easier is using c# winform... it provides you with buttons, panels, listbox...

Of course, you can integrate it in a panel, like proposes @milkboat, but I think that winform series is not a good example.. because the xna code part is not driven as usual, there is no game class, and the code becomes ugly...

I prefer use this code, http://pastebin.com/kkkmKm8n, is not mine, but I've modified it to add the interface and the CreateAndShow method.

This way your game will not suffer many modifications among using the editor or not using it.

You only have to inherit your game class from XnaControlGame, and the editor form that will host the xna control should implement IXnaFormContainer.

I think is easy and more elegant than other approachs.... because let you difference xna part from the winform part

An editor with this approach:

http://www.youtube.com/watch?v=0wiuhZeq1cs&feature=plcp

An editor with a simple form approach, when the form is visible is editor mode, when dissapears is game mode.

http://www.youtube.com/watch?v=4QDeY15Ox-g
> 1 votes

# Answer
http://create.msdn.com/en-US/education/catalog/sample/winforms\_series\_1

This example from the XNA site shows you how to implement a xna device into a windows forms project.
> 3 votes

---
Tags: xna, sprites, editors
---


# Question
Title: Is Gresham's Law relevant for modern online games that allow the use of real money as additional currency?
More and more online games are planning to allow the use of real money to purchase ingame items in addition to the standard ingame currency. Diablo III for example, which will be released next year, will feature a gold-auction house (only ingame gold allowed) and a real money auction house (only real money allowed) to trade items between players inside the game.

Gresham's Law says that: "When government compulsorily overvalues one money and undervalues another, the undervalued money will leave the country or disappear from circulation into hoards, while the overvalued money will flood into circulation."

People are worried that ingame gold will be severely undervalued and real money will be dominating because the developers of the game get their share from real money transactions and want to push this currency. They are the government that might compulsorily overvalue real money and undervalue ingame-gold. This means according to Gresham's Law that we will see the ingame currency gold vanish over time, leaving the real money auction house as the only option to buy and sell items.

This leads to the question, if Gresham's Law can be applied to this scenario. What are the reasons why or why not Gresham's Law will effect online games with real money and virtual currencies combined in the same market.

# Answer
> 8 votes
Although the theory applies, I suspect that you would not see the in-game currency driven out of circulation.

Gresham's law requires legal tender laws to enforce a particular price relationship between two monies. For example, legal tender laws in the US set the price of silver in terms of gold at 16:1 in 1834. But the market price for silver was higher than that, for example 15.5:1 (no citation available). This caused people to use the gold coins and to melt down silver coins.

Now let's say that the market equilibrium between US dollars (USD) and Diablo III Gold (D3G) is 1:100. This market value is based on the supply of USD, the supply of Diablo III, and the demand for goods that are priced only in USD versus the demand for goods that are priced only in D3G. (Example: if Diablo III suddenly becomes very popular and players suddenly demand more in-game items, then the D3G may appreciate in value, such as changing the ratio from 1:100 to 1:80.)

The game's publisher creates the equivalent of "legal tender" laws by mandating the ratio between USD and D3G. If they set the ratio at 1:200, then they have overvalued the USD and Gresham's law predicts that gamers will spend their USD (putting it into circulation) and to hoard their D3G.

But the problem is what do gamers do with their hoard of D3G? In the gold/silver example above, people could melt down silver to reform it into items of higher value, but you can't do that with in-game currency. In real life, people can smuggle their valuable coins to other countries where legal tender laws don't apply. But in the video game, there is nowhere to take your money that is beyond the reach of the game's creator.

Left with no other choice, I imagine that gamers will continue to use the inferior currency due to lack of better options.

# Answer
> 7 votes
Airline miles would seem to be a useful "real-world" example of such a proprietary currency:

> Both history and recent financial troubles suggest that frequent-flyer miles will not improve with age. If you can't use all your miles on flights now, you could try to sell them. The fine print of every programme prohibits the sale or barter of miles, but there is a black market of brokers, such as Award Traveller, which will buy your miles at a discount (by paying you to redeem them for a ticket for one of their customers). However, if the buyer is caught with your award ticket, it will be confiscated and your frequent-flyer account permanently frozen. Some members who have sold their miles on eBay have also had their miles revoked.

From The Economist.

As with airline miles, the likelihood is that secondary exchanges will emerge (such as Account Market) which permit people to trade. These are technically illegal in terms of the license conditions of the game worlds, but similar rules haven't stopped airline miles exchanges.

# Answer
> 1 votes
Gresham's Law only applies if, when you want to sell something, you are forced to accept different kinds of currency, and you cannot set the price in each of those currencies independently.

In Diablo III you can choose which currency to accept: in the gold-based auction house only gold can be used, and in the currency-based auction house only real currency can be used.

---
Tags: game-industry
---


# Question
Title: Optimized rendering of a cube mesh world
I want to render a cube-mesh (a.k.a. Minecraft-style) world. If I render each existing cube it will eat up FPS pretty quickly. How can I optimize it? I understand that the point is to not render invisible meshes (faces?) but my problem is to find out what is invisible and what isn't.

# Answer
> 3 votes
You'll have good use of a `isSolidAt(x,y,z)` function. This will be useful for not only the action you want to preform, but other things such as collision checking.

Basically you want to iterate through your cubes and check which faces will be hidden. You know they're hidden when the adjacent cube is solid. For example some pseudo code:

```
Verticies[] verticesToDraw
for(x = 0 to x = chunkXMax)
    for(y = 0 to y = chunkYMax)
        for(z = 0 to z = chunkZMax)
            if(!isSolidAt(x+1,y,z))
                verticesToDraw += AddXPlusFace(x,y,z)
            if(!isSolidAt(x-1,y,z))
                verticesToDraw += AddXMinusFace(x,y,z)
            if(!isSolidAt(x,y+1,z))
                verticesToDraw += AddYPlusFace(x,y,z)
            //and so on for the rest of the faces
Buffer(verticesToDraw)

```

Of course you'll be more detailed. You can also keep track of the faces in a separate array, perhaps using a byte with bit positions 0 through 5 indicating whether a face is set or not.

Eventually you'll probably want to improve upon this with special checks for "short cubes", transparent but solid cubes and so on.

**EDIT**

I've updated the code to show that you run this on a per chunk basis. This only address the issue of faces that are invisible because they are adjacent to a solid cube. Sending the vertices for all the cubes and "letting the GPU do the culling" would be a bad idea. I assume you may know that already since you asked this question. The above code is only run when the chunk is dirty, as in, something has changed. It's not to be run every frame.

You'll see significant performance improvements with the above change. I know because I've gone through the process before. You may also find performance improvements with spacial partitioning, but the improvements are unlikely to be as significant as drastically reducing the number of vertices sent to the GPU (as you will do when you implement the above).

# Answer
> 1 votes
There are two problems to this:

1. Eliminate entire cubes to avoid rendering them.
2. Eliminate invisible faces

As for #1, you need to take a look at space partitioning algorithms. They divide up space into smaller subspaces in order to make searches faster (in your case, you're searching for every cube that collides with your view frustum).

Since most things you have are static, and also cubes, an easy suggestion for you would be the Octree.

As for #2: I'm pretty sure that's not going to be a problem. Not drawing faces that you can't see with cubes usually equals not drawing faces that don't face towards you. The process of this is called backface culling and is usually done by the graphics card.

So the only really limiting factor for #2 could be bandwidth consumption on the way to your graphics card. But I really doubt that's the case, since your world is static and thus only needs to be sent to the graphics card whenever something in the terrain changes, which will not be very often. Even if you sent everything you need to draw over once every frame, this will most likely be no bottleneck as long as you batch everything together in a reasonable manner (faces with same textures, etc). However, if this really turns out to be a bottleneck, you should search the internet for software backface culling algorithms. Here's an example.

# Answer
> 0 votes
A simple octree should be a fine enough algorithm for this- it can achieve this in O(log(N)). In addition, you have an advantage in that you can prove which cubes are visible and which aren't in easy time.

Let's say that you start off with a totally flat map. You know in advance that only the top level of cubes are visible, since all the ones below it are concealed. Then when the player removes a cube, you know in advance which cubes are now visible. When the player adds a cube, it's easy to test if the cubes near it have been blocked from view. This is because each cube can only affect the potential visibility of the six cubes on it's primary faces. Thus, it's trivial to exploit the temporal coherency of the map to prove which cubes are visible and which aren't in a very short period of time. If you use terrain generation or static maps, then simply apply this logic when your algorithms apply each change.

This will easily provide you with a small count of visible cubes, and frustum culling with an octree should do the rest.

Backface culling on the GPU is more than sufficient for eliminating invisible faces.

---
Tags: c++, opengl, optimization, voxels, irrlicht
---


# Question
Title: string and int concatenation resulting in null for a Tetris clone?
I'm writing a tetris clone, and I have sprites (of every possible piece and rotation) loaded through the XNA content pipeline. For example, I have assets "i", "i2", "i3", and "i4" for each rotation of the 4-block-long I-tetrimino. For the O-tetrimino, I only have asset "o", because the O-tetrimino doesn't require any rotations.

I want to load each of these assets into a 2D array of `Texture2D`s. Here's my attempt:

```
1 Texture2D[,] tetriminoTextures = new Texture2D[7, 4];
2 char[] tetriminos = { 'o', 'i', 'l', 'j', 'z', 's', 't' };
3 string t;
4
5 for (int i = 0; i < 7; i++)
6 {
7     for (int j = 1; i <= 4; i++)
8     {
9         if (i == 0 || j == 1) // If char[i] == 'o', then don't consider rotations.
10                              // The square piece doesn't have rotations.
11                              // If j == 1, then leave the asset name as is.
12            t = letters[i].ToString();
13        else // (i != 0 && j <= 2 && j <= 4)
14            t = letters[i].ToString() + j;
15        tetriminoTextures[i, j-1] = Content.Load<Texture2D>(t);
16    }
17 }

```

However, when I attempt to

```
spriteBatch.Draw(tetriminoTextures[x, y], /* some position vector */, Color.White);

```

I get an `ArgumentNullException`. Apparently `tetriminoTextures[x, y]` is `null` when `y >= 1 && y <= 3`.

I have no idea what's going on. I think it may have something to do with my concatenating a `string` and an `int` together in line 14. But I'm getting an `ArgumentNullException` even when `i == 0 && j >= 2 && j <= 4` (i.e. for each rotation of the O-tetrimino excluding the first one), though the if statement in line 9 should have caught these cases. Any help would be appreciated!

# Answer
> 2 votes
You should change the var i to j here

```
7 for (int j = 1; j <= 4; j++)
8     {
9

```

Maybe you should use the step trace to debug your execution flow... worth it... :)

Anyway is a common copy/paste bug... hehehe

---
Tags: xna
---


title: Timer for pop up text in XNA

text:
# Question
Title: Timer for pop up text in XNA
I am making an xna game which contains turn-based RPG battle elements. Any good game that features turn-based battle has to have a good feedback to the user.

For example, When my guy attacks, there should be a text popup that says something like "HERO DOES 15 DMG!". And this text should disappear several seconds after.

I am currently able to put text on the screen via standard spritefont drawing. However, in order to make it disappear I am currently using bools and a timer. I have been doing research on timing related stuff but I seem to be very bad at it.

Using some of the suggestions I have received, I have made a messagesystem class. But I am still confused about the implementation. Here is the new code:

```
public class MessageSystem
    {

        public static readonly MessageSystem Instance = new MessageSystem();
        public float timenow;

        struct Message
        {
            public SpriteFont Font;
            public string Data;
            public Vector2 Position;
            public float Duration;
            public bool isActive { get; set; }

        }

        List<Message> Messages = new List<Message>();

        public MessageSystem()
        {

        }

        public void Show(string data, Vector2 pos, SpriteFont font, float duration)
        {
            Messages.Add(new Message() { Data = data, Font = font, Position = pos, Duration = duration });
        }
        public void Update(GameTime gameTime)
        {
            timenow += (float)gameTime.ElapsedGameTime.TotalSeconds;

            for (int i = 0; i < Messages.Count; )
            {
                if (Messages[i].Duration < timenow)
                {
                    Messages.RemoveAt(i);
                    continue;
                }
                i++;
            }
        }

        public void Draw(SpriteBatch batch)
        {

            foreach (Message msg in Messages)
            {
                batch.DrawString(msg.Font, msg.Data, msg.Position, Color.Lime);
            }

        }

    }

```

Here is the implementation part:

```
if (p1atktimer >= 10)
            {
                AttackMsg.Show(playerBattler.Name + " attacks furiously!", battlemsgs, battlefont, 2.0f);
                DealDmgFromLeft(gameTime);
                p1atktimer = 0;
                timenow = 0;
            }

```

In my update method I just have:

```
Attackmsg.Update(gameTime);

```

And similarly, in my Draw method I have:

```
Attackmsg.Draw(spriteBatch);

```

So, it goes away when it is supposed to, but it does not appear again when the p1atktimer condition becomes true again. I guess i have to surround the attackmsg.Draw(spriteBatch) command with conditionals instead of the show? But this brings me back to my previous question: Do I have to make bools for everytime I want to show this kind of text.

Let's continue with this example, I am going to make a bool atkmsgshowing = false. And make it true when someone's attackguage reaches 10. Because, if I do not do this, the msg works only once. So then, the attacker attacks, and I will make the bool true. When the attack ends, atkmsgshowing will go back to false. Doesn't this defeat the purpose of making a MessageSystem class?

# Answer
> 1 votes
```
public class Message
{
  public string Text {get;set;}
  public TimeSpan Appeared {get;set;}
  public Vector2 Position {get;set;}
}

static readonly Vector2 BattleTextDisplacement = new Vector2(80, -100);
List<Message> messages;

```

Then to add a message

```
messages.Add(new Message() {Text = "Player attacks",
   Appeared = gameTime.TotalGameTime,
   Position = playerBattler.Position + BattleTextDisplacement});

```

And then to display them:

```
foreach (var message in messages)
  spriteBatch.DrawString(battlefont, message.Text, message.Position, Color.Lime)

```

To remove old messages:

```
while (messages.Count > 0 &&
       messages[0].Appeared + MaxAgeMessage > gameTime.TotalGameTime)
  message.RemoveAt(0);

```

And of course, making the text float up on the screen is easy now, simply change its position (or use the age of the message to figure out where the position should be).

A lot of the code can be put into methods in the Message class itself, so instead of drawing the text you can have a `Message.DrawMessage(battlefont, spriteBatch)`, this way you can make a subclass that draws the text differently (such as having a graphic behind it, or display an animation instead of text).

# Answer
> 1 votes
I'd recommend you to create an specific manager for showing text...

To Add a message:

```
     MessageSystem.Instance.Show("My string data", Pos, 1);

```

The Class

```
public class MessageSystem {

    public static readonly MessageSystem Instance = new MessageSystem();

    struct Message {
        public SpriteFont Font;
        public string Data;
        public Vector2 Pos;
        public float Duration;
        public float Alpha;
        ....
    }

    List<Message> Messages = new List<Message>();

    public void Show(string data, vector2 pos, float Duration = 1, SpriteFont font = DefaultFont, Alpha = 1)
    {
        Messages.Add(new Message() { Data = data, Font = font, Pos = pos, Duration = duration, ...});
    }
    public void Update(float Seconds) {  // == (float) gametime.ElapsedTime.TotalSeconds

       for (int i=0; i<Messages.Length; )
       {
           Message[i].Duration -= Seconds;
           if (Message[i].Duration<0)
           {
              Messges.RemoveAt[i];
              continue;
           }
           i++;
       }
    }

    public void Draw(SpriteBatch batch)
    {
       batch.Begin();
       for (int i=0; i<Messages.Length; )
       {
            batch.DrawString(Message[i].Font, ....)
       }
       batch.end()
    }
}

```

---
Tags: xna, 2d, rpg, timer, text
---


title: XNA create differences in enemies

text:
# Question
Title: XNA create differences in enemies
I created an enemy class for my game. It works well, except for one dilemma. When I spawn more than one enemy, eventually they begin to "overlap" and look like one enemy. I was wondering if anyone had any ideas on how to create more differences and spontaneity between the enemies. All help would be greatly appreciated.

Here is the class:

```
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace Defender
{
public class Enemy
{

    Vector2 Location;
    public static Texture2D texture;

    float rotation;
    Rectangle rectangle;
    int shootTimer = 50;

    public void Draw(SpriteBatch spriteBatch)
    {
        rectangle = new Rectangle((int)Location.X, (int)Location.Y, 32, 32);
        spriteBatch.Draw(texture, Location, null, Color.White, rotation, new Vector2(16, 16), 1, SpriteEffects.None, 0);

    }

    public void Update(GameTime gameTime)
    {
        Rotate();
        Shoot();
        Move(gameTime);

    }

    public void Move(GameTime gameTime)
    {
        if (Vector2.Distance(Location, Game.player.Location) > 75)
        {

                Location.X += findDirection(Game.player.Location).X * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 20);
                Location.Y += findDirection(Game.player.Location).Y * (float)(gameTime.ElapsedGameTime.TotalMilliseconds / 20);

        }

    }

    private void Rotate()
    {

            float XDistance = Location.X - Game.player.Location.X;
            float YDistance = Location.Y - Game.player.Location.Y;

            rotation = (float)Math.Atan2(YDistance, XDistance);

    }

    private Vector2 findDirection(Vector2 target)
    {

            Vector2 direction = target - Location;
            direction.Normalize();
            return direction;

    }

    public void Shoot()
    {
        if (shootTimer > 0)
        {
            shootTimer--;
        }
        if (shootTimer == 0)
        {

            //find slope

            //create bullet
            Bullet bullet = new Bullet(Location, findDirection(new Vector2(Game.player.Location.X, Game.player.Location.Y)));
            Game.bulletList.Add(bullet);

            //reset timer
            shootTimer = 50;

        }

    }

    public Enemy(Vector2 loc)
    {

        Location = loc;
    }

}

```

}

# Answer
There are a couple of things you can do to fix this.

First off, you can try implementing collision on enemies so that they don't walk through one another. Depending on the enemy type you're fighting, it may or may not make sense for them to easily pass through one another (flying bugs, ghosts, and small creatures might make sense, but who knows how those T-rexes are all running in the same spot).

Alternately, you can try and add some random factor to the pathing algorithm your enemies are using. A couple of people talked about this in more detail on this page: Making the AI take different paths to each other
> 2 votes

# Answer
Have a look at Steering Behaviors.

There are many different kinds of behaviors that could help your enemies navigate more realistically, but one behavior that relates to what you are looking for is a "Separation" type of behavior (often used in Flocking behaviors (or boids)). This behavior states that all entities under this "rule" try to keep a small distance between each other. Using this rule, your enemies wouldn't overlap, and you wouldn't need to check for collisions either.

Some pseudo-code can be found here as well as a bit more in-depth explanation of how it works and can be implemented.
> 1 votes

# Answer
Well, you can use random number generator to create a little differences between enemy characteristics (speed, initial position, etc.)
> 0 votes

---
Tags: xna, ai, movement, rotation
---


title: Detect Mip mapping level in the shader?

text:
# Question
Title: Detect Mip mapping level in the shader?
Is there a way to do this in pixel shader 2.0/3.0? I've got on or off transparency so when the mipmapping level is different the transparency can take up too much of the texture and make it invisible. Or is there a way to manually create the mip maps in XNA 4.0?

# Answer
Regarding your Mip selection, I am using a custom texture atlas shader. In my case, the following snippet is accurate enough. You do have to provide it your own texture size.. i.e. you need to know the width X height parameters of the texture you want to "mip". In my case, these are just defines.. If you use dds textures, direct x compatible, they should already have mip levels embedded.

```
  #define SUB_TEXTURE_SIZE 128.0
  #define SUB_TEXTURE_MIPCOUNT 8

  float MipLevel( float2 uv )
  {
    float2 dx = ddx( uv * SUB_TEXTURE_SIZE );
    float2 dy = ddy( uv * SUB_TEXTURE_SIZE );
    float d = max( dot( dx, dx ), dot( dy, dy ) );

    // Clamp the value to the max mip level counts
    const float rangeClamp = pow(2.0, (SUB_TEXTURE_MIPCOUNT - 1) * 2.0);
    d = clamp(d, 1.0, rangeClamp);

    float mipLevel = 0.5 * log2(d);
    mipLevel = floor(mipLevel);

    return mipLevel;
  }

```
> 1 votes

# Answer
You do have several alternatives which should be sufficient:

* Use the mipmap lod bias render states, though this is more or less deprecated in modern APIs
* Manually select the mipmap yourself in the shader with the functions like tex2dlod. You could simply set it to 0 and have it always select the highest rest mip (although this will cause some aliasing on-edge and in minification cases)
* Don't upload a full mipmap chain for the image, just create the texture with 1 or only a few (2-3) of the mipmap levels.
> 0 votes

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


title: Unexpected results with D3D9 depth bias

text:
# Question
Title: Unexpected results with D3D9 depth bias
I've run in to some problems with the D3DRS\_DEPTHBIAS render state after converting an older game's D3D8 renderer to D3D9.

D3D9 replaced the old (and poorly supported) D3DRS\_ZBIAS with D3DRS\_DEPTHBIAS, but it doesn't seem possible to get it to work the same way that ZBIAS did. This game renders shadows and other "decals" onto the ground as flat textures, and to avoid the obvious z-fighting issues that would result would set D3DRS\_ZBIAS to 2 when rendering decals in the D3D8 renderer (which I did not write).

The best approximation of the old D3D8 behavior that I've been able to come up with is setting D3DRS\_DEPTHBIAS to -0.00003 when rendering shadows. This works fine for shadows on flat terrain that are relatively close to the camera, but when the camera is far above a shadowed object, the shadow will draw on top of the object itself. This can also happen even on near objects if they are on uneven terrain.

It doesn't seem possible to solve this by manipulating the DEPTHBIAS value alone, as no change fixes it entirely without causing other problems.

Is there any way to solve this? Failing that, is there a more modern technique for rendering decals that could be used? I would much rather avoid lots of rewriting as I'm not very familiar with D3D and didn't write any of the original code, but if that is the only option...

# Answer
> 1 votes
Try using `D3DRS_SLOPESCALEDEPTHBIAS` in addition to `D3DRS_DEPTHBIAS`. A typical value would be -1.0 for the slope-scaled depth bias, and some very small negative value for the constant depth bias. See the MSDN for a little more information on these flags. The slope-scaled depth bias automatically scales the amount of bias based on the polygon's orientation with respect to the screen; this allows you to use a smaller constant bias, which hopefully will avoid causing the problem you mentioned of objects appearing behind their own shadows when too far away.

There are also some alternative approaches to this problem discussed in this article.

# Answer
> 0 votes
It is worth noting that neither option will truly fix every case as there are several problem points with decals, some of which are not 'depth bias' related, that everyone really should be aware of:

The floating point precision of the verts of the meshes can be damaged by transforming them temporarily into world space units before going into viewspace units (which then get fed into the projection matrix). The numerical precision artifact here, is that as the camera translates or rotates, the vertices on the floor and the decal will round to fairly large varying floating point values, and each vertex will do this at a different rate, so the decals will tend to wobble and oscillate which tends to make them to partially into the floor some varying amount depending on the view. This numerical precision problem is fixed by keeping everything in view space units, which means changing all lighting and other computations to be relative to the view (which itself is defined as 0,0,0 at the camera). This problem also occurs with shadowmapping for the same reason, and is harder to fix (but there is more room to cheat with shadowmaps).

Depth Bias and Slope Scale Depth bias are themselves problematic for fixing decals, as they both add a *fixed linear offset* to the projected depth of the polygon. If you are rendering perspective projections the depth is not linear, it is a curve. This fixed offset can be not enough of a delta when the polygon is far away from the camera, and way too much when the polygons are close to the camera. Disabling depth bias entirely and projecting the polygons some fixed world space units away from the surface (depending on the distance to the camera) is much more reliable and won't come back to haunt you months later when someone sticks a big decal on a mesh in some situation that wasn't tuned with the bias numbers you used.

---
Tags: directx
---


# Question
Title: What is the best way to turn image voting into a game?
I'm trying to come up with a design for an image voting site that turns the (potentially boring) task of voting on thousands of images into a game. The goal is to get the user to vote on as many image pairs as possible without them getting bored.

My first thought was to use to the different ip addresses of uploaded images and turn the voting into a world journey for the user. The site opens on a world map and is presented a series of image "battles" where they have to choose the winning image out of the pair. Each world region will have anywhere from 10-100 image pairs that the user will vote on. As they complete the image pairs for a region, they are "flown" to another part of the world to keep the game going.

The goal of the world map approach is to collect the user's opinion on as many image pairs as possible while giving them the sense of: 1- accomplishment (finishing the image pairs of a region) 2- going around the world

I unfortunately ran into a subtle flaw of this approach: Image pair voting will be restricted to particular region...so you can never have an image pair composed of an image from japan against an image from the US.

I was wondering how I could adapt this approach to fix this flaw - ie allow image pairs to be composed of images from all over the world instead of a particular region only?

Or even if you could come with a different design that accomplishes the same goals (collect as many votes as possible while keeping the user motivated and not bored)

Thanks for your time

# Answer
> 1 votes
When generating your image pairs, one of the images will always be from the current region, the second will be from a random region. They are not labeled as such, the region information for the images is hidden from the user. At the end of the voting, the region other than the current region with the most votes is the place the player "travels" to next.

---
Tags: game-design, image, polling
---


# Question
Title: OpenGL Texturing Isn't working: displaying just white
Basically, see the title: for whatever reason, I load a texture into OpenGL, bind it, draw a quad with texture coordinates specified, and the quad remains totally white regardless of what the texture is.

I have made sure that GL\_TEXTURE\_2D is enabled. I have verified (using glGetTexImage) that the Texture has the correct data in it (or, if not the correct data, data that should be visible, as the pixels have different values).

My glTexture2D function is called as follows:

`glTexImage2D(GL_TEXTURE_2D, 0, pixelFormat, this->width, this->height, 0, pixelFormat, GL_UNSIGNED_BYTE, &(pixelData[0]));`

This is where pixel format is either GL\_RGBA or GL\_RGB (according to pixel depth), and pixelData is the array of pixels. I verified that pixelFormat and pixelData and width and height have within them the correct values. Note that pixelData is a std::vector.

I bind the texture as such:

`glActiveTexture(GL_TEXTURE0 + this->multiTexNumber);
 glBindTexture(GL_TEXTURE_2D, this->texID);`

For the purposes of my testing, this-\>multiTexNumber = 0;

Have I done something wrong here? Is the problem elsewhere?

EDIT: via **very** thorough checking, I have ensured that OpenGL doesn't throw any errors. The problem persists.

# Answer
If you're not providing a full mip chain for the texture, ensure that mipmapping is disabled (set a filter mode that doesn't use mipmaps). IIRC, OpenGL may disable texturing if you try to use mipmapping on a texture that doesn't have mips.
> 1 votes

---
Tags: opengl, textures
---


title: Minecraft style XNA game collision?

text:
# Question
Title: Minecraft style XNA game collision?
I've been trying to get this working for ages now, I can detect if there's a solid block at any place on the map and I can check how far something is inside of it, but I don't understand how to fix the collision. I've tried loads of ways and all of them end up by the player getting stuck, glitching around, incorrect responses and I really have no idea how to go about this :/.

```
       int Chnk = Utility.GetChunkFromPosition(origin);
        if (Chnk == -1)
            return;

        Vector3 Pos = Utility.GetCubeVectorFromPosition(origin);

        if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)Pos.Y, (byte)Pos.Z] != 0)
        {
            isInIllegalState = true;
            if (velocity.Y < 0f)
                velocity.Y = 0f;
        }

        while (isInIllegalState)
        {
            if (GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)origin.Y, (byte)Pos.Z] != 0)
                origin.Y = (int)(origin.Y + 1);
            else isInIllegalState = false;
        }

        if (origin.Y < Chunk.YSize - 2 && GlobalWorld.LoadedChunks[Chnk].Blocks[(byte)Pos.X, (byte)(origin.Y + playerHeight.Y), (byte)Pos.Z] != 0)
        {
            velocity.Y = 0f;

            //Acceleration.Y = 0f;

            origin.Y = (int)origin.Y;// -0.5f;
        }

        for (int x = -1; x <= 1; x+=2)
        {
            for (int z = -1; z <= 1; z += 2)
            {
                Vector3 CornerPosition = new Vector3(boundingSize * x, 0, boundingSize * z);
                bool CorrectX = false;
                bool CorrectZ = false;

                Vector3 RoundedOrigin = Utility.RoundVector(origin);
                Vector3 RoundedCorner = Utility.RoundVector(origin + CornerPosition);

                byte BlockAdjacent = Utility.GetCubeFromPosition(origin + CornerPosition);

                if (BlockAdjacent == 0)
                    continue;

                if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z != RoundedOrigin.Z)
                {
                    CorrectX = true;
                    CorrectZ = true;
                }

                if (RoundedCorner.Z != RoundedOrigin.Z && RoundedCorner.X == RoundedOrigin.X)
                    CorrectZ = true;
                if (RoundedCorner.X != RoundedOrigin.X && RoundedCorner.Z == RoundedOrigin.Z)
                    CorrectX = true;

                if (CorrectX && CornerPosition.X > 0)
                {
                    if (origin.X > 0f)
                        origin.X = (int)(origin.X + 1) - boundingSize;
                    else origin.X = (int)origin.X - boundingSize;
                }
                else if (CorrectX && CornerPosition.X < 0)
                {
                    if (origin.X > 0f)
                        origin.X = (int)(origin.X) + boundingSize;
                    else origin.X = (int)(origin.X - 1) + boundingSize;
                }

                if (CorrectZ && CornerPosition.Z > 0)
                {
                    if (origin.Z > 0f)
                        origin.Z = (int)(origin.Z + 1) - boundingSize;
                    else origin.Z = (int)origin.Z - boundingSize;
                }
                else if (CorrectZ && CornerPosition.Z < 0)
                {
                    if (origin.Z > 0f)
                        origin.Z = (int)(origin.Z) + boundingSize;
                    else origin.Z = (int)(origin.Z - 1) + boundingSize;
                }
            }
        }

```

# Answer
If you're still stuck on this issue, I've written a short "guide" on collision for voxel engines.

http://thewebsiteabout.me/all-about-voxel-engines-part-3-view/
> 1 votes

---
Tags: xna, c#, minecraft-modding, voxels
---


# Question
Title: Implementing a Turn-Based Game with Windows API Window Messages
I'm trying to make a 2-player Connect 4 game, but I'm having trouble wrapping my head around some of the concepts related to incorporating event handlers while progressing with the game.

On the one hand, I have my windows:
One is a control window used for entering player information, and has an exit button.
One is the actual game window used for drawing on and interaction with the player.
One is a popup that asks the player a question that they must answer correctly in order to take that turn.

On the other hand, I have my actual game logic. A player's turn could progress as follows:

```
//create question window with question and await an answer (game state != WAITING_FOR_ANSWER)
//question window is destroyed after the question
//if not correct, move onto the next player's turn
//if correct, await their move (by clicking on the board, state != WAITING_FOR_MOVE)
//then check for win/tie
//then perform end-of-game function / change state if needed
//move onto next player's turn (same function)

//all this time, game window redraws when game has started and needs to change

```

Meanwhile, my game window draws and responds to clicks depending on the game state. My general method is:

```
//change state to something like WAITING_FOR_MOVE
//window sees state is now this, and responds to clicks
//window changes state back when move is made
//function continues

```

The problems arise when trying to get all of this running concurrently. If I try as is, the question window for the first player's turn comes up after clicking the "Start Game: button, but then all windows freeze up. I would imagine this is due to the logic not actually ending, as it requires the window to give it a reason to stop.

I tried wrapping the very first `nextTurn()` call (in the "Start Game" button handler) in a new thread, but it causes the same thing to happen, except the control window responds when clicking the exit button.

How should I be dealing with program logic and window event handlers at the same time?

I'm also pretty sure I should be accessing the state differently than just checking it until it's the desired result. Would I need a mutex for this?

# Answer
I don't know where you got the idea of doing it like this, but it doesn't sound very game design like at all. For a simple game like this you shouldn't need multiple windows and multiple threads. Also events aren't commonly used in game development because they break the flow of your game loop.

Anyway why not try something like this:

Build a game loop that can have 3 states like you had before -Waiting for answer -Waiting for move -Turn finalizer

In each of these states the game loop just keeps running at 60fps, there is no waiting whatsoever, the states just influence what is being drawn to the screen and what input is accepted,

Here is a very crude example that should get you started. Keep in mind that you should never wait on something in your game loop, the goal of your game loop is run again as fast as possible. The behavior of your game loop is completely dependent on the game state. Handle your input via polling and change state when certain criteria are met.

```
while(!exiting)
{
    switch(state)
    {
        case GameStates.WaitingForAnswer:
            DrawQuestionWindow();
            AppendInputToPreviousInput();
            if(AnswerIsCorrect)
                state = GamesStates.WaitingForMove;
            break;

        case GameStates.WaitingForMove:
            DrawBoard();
            if(MouseButtonIsDown())
            {
                MakeAMoveWhereTheMouseIs();
                state = GameStates.TurnFinalizer;
            }

        case GameStates.TurnFinalizer:
            time = time + elapsedtime;
            DrawExplosions(time);
            if(time > 5)
            {
                GenerateQuestion();
                state = GameStates.WaitingForAnswer;
            }
    };

    if(MouseIsPressedOverExitButton())
        exiting = true;
}

```
> 3 votes

---
Tags: events, turn-based, winapi
---


# Question
Title: Non-GPU Noise for 2D side-view terrain generation?
I really couldn't find a correct answer while scowering all the forums for Noise Generation.

My goal is simple, I really want to have two distinct layers for my terrain, a white layer representing air, and a black layer representing earth. An algorithm will pick up from there.

Most noise I found generated "Cloudy" textures, where I am looking for something along the lines of:

So far I have worked with Perlin Noise but adjusting my values yields no useful results.

Does anyone have any ideas?

# Answer
> 2 votes
You probably want 1D Perlin noise instead of 2D for this. Treat the noise function as defining the height of the terrain at each column, and fill everything above that height with white and everything below with black.

# Answer
> 1 votes
**Local minima and maxima**

Randomize a set of float numbers from 0 to 1.0 (exclusive), denoting position along the x-axis. Do this once, and call these minima (they sit below the baseline). Do this again, and call these maxima (they sit above the baseline). Push each minimum down by a random amount. Push each maximum up by a random amount. Now merge the two sets into a single set, and sort by increasing x. Then join the points in order of increasing x. You could use lines, or some curve function if you want it more organic. There's your random terrain.

**Sine-wave mashup**

This alternative which might (a) be simpler to implement than Perlin noise, if somewhat more brute-force in nature, and (b) might simultaneously open your eyes as to how simple the 1D Perlin noise solution Nathan's explaining, is.

Consider a sine wave. It roughly approximates what you have in your diagram, except it's too smooth and regular.

You can generate a bunch of random sine waves. By random I mean, with random amplitudes, random frequencies, and random offsets from the origin. Then merge them. Then take only the uppermost (or lowermost) part of the combined wave functions. Then smooth the result. Now you should have some sort of an organic but irregular surface. TBH this is something of an oversimplification, and there are mathematically far better ways to merge/smooth, but you get the general idea.

This is exactly what 1D Perlin noise is. All you're doing is taking a cross-section through the noise plane that Perlin produces. Perlin noise is just a set of overlaid/merged waves which have random frequencies, amplitudes, and offsets (all of which are within user-specified ranges, being the parameters you pass to the Perlin noise function), and which operates in 2 or 3 dimensions.

So you can take either approach, and you'll get something like what you want. I'd still suggest using Perlin though, as there are no question marks there. It's a given that it'll work the way you want.

# Answer
> 0 votes
I wouldn't use noise for that.

Have a look here : http://thegoldenmule.com/blog/?p=80 for 2 different algorithms to create Scorched Earth like terrain like you seem to want.

---
Tags: xna, c#, 2d, terrain
---


# Question
Title: What should deliverables for a school game project be?
I am planning on making a 3D hack-n-slash RPG with Unity for a school project. I have to come up with a project proposal. I am suppose to identify project deliverables.

I cannot think of what "deliverables" would be for this kind of game. I am hoping someone can give me some examples to get me started?

Would they be art work or characters? Content? Story? Core features? Technical requirements? What technology I am using? I am not sure.

# Answer
> 4 votes
I'd suggest you structure each of your milestone deliverables as a simple bulleted list of clearly-demonstrable features your game will have by the end of the milestone. For example, perhaps your first deliverable will involve a game where:

* The player can walk around a static world.
* The player can engage in "combat" with creatures (who "die" when walked into).

Whereas your second might be:

* The player can proceed through character creation (picking a race/gender/class).
* Creatures have health and may require multiple hits to kill.
* Creatures may drop items upon death.
* The player can pick up items by walking over them.

And the third:

* Character creation randomly generates player stats based on class and race.
* The player has health.
* Creatures will approach the player if he or she is close enough and attempt to attack.
* The player can die if his or her health is reduced to 0.
* Players can equip items in their inventory.

And so on. The purpose of a deliverable is almost always to demonstrate to some outside party what progress has been made -- since this is a school project that's almost certainly the case. External parties will not necessarily be intimately familiar with the details of the development between any two successive deliverables, so providing clear and understandable goals makes their job -- evaluating your progress -- easier. They will appreciate that.

It will also help you, because its gives you goals and a plan, and helps you identify rough high-level dependencies, and let you check and measure your own progress. I use techniques very similar to this to schedule blocks of work for teams in my actual, real job making commercial games.

# Answer
> 1 votes
Project deliverables are alpha, beta, gold in essence with milestone dates.

The best way to manage your project is to use scrum development process or the waterfall method of scrum which is a loose variation of scrum. Having a burn down chart, and a to do list so everything is in order will help you out in the long run.

As far as your deliverables, they should focus mainly on the games game mechanics, and dynamics. Aethetics play a big role in the design of the game. Such as evoking emotion, creating engaging storyline with the player, and the visual and auditory sounds that are involved with the design.

**Planning :** Plan your entire game out.

**PRE-Alpha :** The best way to test your game is to make an analog version of it first.

**Alpha :** Playable mechanics such as walking, jumping, hitting. Basic art is in place. The game is playable.

**Beta :** More playable / refined mechanics for walking, jumping, hitting. Sound should be delivered in the beta milestone. Sound shouldn't be finished, but in place. The games mechanics should also be in place. The player can die, respawn, collect, and pickup items. Finalize art, etc.

**Gold :** Finished version of your game. Everything is polished and fixed up. Working, and all very few bugs. The game is pretty much ready to ship.

**Final version :** Everything is polished, fixed, and there are no bugs that are present. You may find bugs later down the road because everyone plays differently. The game is now officially ready to ship.

This is how my school thesis went for four months, Alpha = 1 month, Beta = 1 month, Gold = 1 Month, Final-Version = 1 Month.

---
Tags: project-management, planning
---


# Question
Title: What is a systematic process for choosing a mobile game engine?
I am looking for a systematic process or methodology for choosing a mobile game engine for a mobile game project.

Intuition tells me that it should be similar in principle to choosing any off-the-shelf product (requirements, evaluation, short-list, trial, etc).

Any suggested processes?

# Answer
As you mention it is `similar in principle to choosing any off-the-shelf product (requirements, evaluation, short-list, trial, etc)`.

As to `[a]ny links or perhaps suggested processes?`:

For software in general How to Choose Business Software and How to Choose Software, both offer different styles. The first is a common step-by-step 10 item list with some additional Tips, the second is one man's opinion in 3 paragraphs followed by 2 marketing his own. The second, however, is more closely related to game development because it focuses on productivity exclusively.

As for development specific there is the 15 Most Important Considerations when Choosing a Web Development Framework and Choosing the Right Java Web Development Framework. The first here applies to any framework (except for the question of which JavaScript library is included), which is essentially what a game engine is. The second provides more of a magazine Top 10 ranking process.

Finally, I just found How to Choose a Mobile Game Engine, but it is not yet published.
> 2 votes

---
Tags: methodology
---


# Question
Title: How to lead a moving target from a moving shooter
I saw this question: Predicting enemy position in order to have an object lead its target. My situation is a little different though.

My target moves, and the shooter moves. Also, the shooter's velocity is added to the bullets' velocities, i.e. bullets fired while sliding to the right will have a greater velocity toward the right.

What I'm trying to do is to get the enemy to be able to determine where they need to shoot in order to hit the player. Using the linked SO solution, unless the player and enemy are stationary, the velocity difference will cause a miss. How can I prevent that?

---

Here is the solution presented from the stack overflow answer. It boils down to solving a quadratic equation of the form:

```
a * sqr(x) + b * x + c == 0

```

Note that by `sqr` I mean square, as opposed to square root. Use the following values:

```
a := sqr(target.velocityX) + sqr(target.velocityY) - sqr(projectile_speed)
b := 2 * (target.velocityX * (target.startX - cannon.X)
      + target.velocityY * (target.startY - cannon.Y))
c := sqr(target.startX - cannon.X) + sqr(target.startY - cannon.Y)

```

Now we can look at the discriminant to determine if we have a possible solution.

```
disc := sqr(b) - 4 * a * c

```

If the discriminant is less than 0, forget about hitting your target -- your projectile can never get there in time. Otherwise, look at two candidate solutions:

```
t1 := (-b + sqrt(disc)) / (2 * a)
t2 := (-b - sqrt(disc)) / (2 * a)

```

Note that if disc == 0 then t1 and t2 are equal.

# Answer
> 5 votes
Okay, let's put some sanity into this. I am afraid you are not making it easy at all, your code does not compile, is inconsistent with regards to variable names (`playerVelocityX` becomes `playerXvelocity` after a few lines? what is `xVelocity`?) and is too verbose. It is basically impossible to debug lest you put considerable effort into it.

So, here are the things to fix:

### Bullet speed

The bullet speed must be `30`, period. There is no need for the computations you are doing: the change of the frame of reference is precisely there to avoid the complexity. You only add the enemy's velocity **after** you found a solution, when you go back to the main reference frame.

### Solution validity

You are not checking that the `time` solution is positive.

### Numerous coding errors

You are testing `time1` and `time2` but always using `time1` in the results.

You do `playerXvelocity - yVelocity` which is inconsistent.

You are doing `/ 2 * a` instead of `/ (2.f * a)`. This is the worst error and it's why everything is going wrong.

You compute `shootx` and `shooty` as the final **position** of the bullet, whereas what you are looking for is the **velocity** of the bullet.

### Fixed code

```
float const bulletSpeed = 30.f;
/* Relative player position */
float const dx = playerX - enemyX;
float const dy = playerY - enemyY;
/* Relative player velocity */
float const vx = playerVelocityX - enemyVelocityX;
float const vy = playerVelocityY - enemyVelocityY;

float const a = vx * vx + vy * vy - bulletSpeed * bulletSpeed;
float const b = 2.f * (vx * dx + vy * dy);
float const c = dx * dx + dy * dy;
float const disc = b * b - 4.f * a * c;

shouldShoot = false;

if (disc >= 0.f)
{
    float t0 = (-b - std::sqrt(disc)) / (2.f * a);
    float t1 = (-b + std::sqrt(disc)) / (2.f * a);
    /* If t0 is negative, or t1 is a better solution, use t1 */
    if (t0 < 0.f || (t1 < t0 && t1 >= 0.f))
        t0 = t1;
    if (t0 >= 0.f)
    {
        /* Compute the ship's heading */
        shootx = vx + dx / t0;
        shooty = vy + dy / t0;
        heading = std::atan2(shooty, shootx) * RAD2DEGREE;
        /* Compute the bullet's velocity by adding the enemy's velocity */
        bulletVelocityX = shootx + enemyVelocityX;
        bulletVelocityY = shooty + enemyVelocityY;

        shouldShoot = true;
    }
}

```

# Answer
> 3 votes
Having a moving shooter is identical to having a stationary shooter. Simply subtract the shooters movement vector from the targets movement vector.

```
Target [-5,0]
Shooter [4,1]
Target - Shooter = [-5,0] - [4,1] = [-9,-1]

```

Calculate the firing vector/initial angle, then add the targets movement vector to the bullet like normal.

# Answer
> 3 votes
Here's an example where I devised and implemented a solution to the problem of predictive targeting using a recursive algorithm: http://www.newarteest.com/flash/targeting.html (I had a stationary shooter but the same approach would work for a moving shooter)

I'll have to try out some of the other solutions presented because it seems more efficient to calculate it in one step, but the solution I came up with was to estimate the target position and feed that result back into the algorithm to make a new more accurate estimate, repeating several times.

For the first estimate I "fire" at the target's current position and then use trigonometry to determine where the target will be when the shot reaches the position fired at. Then in the next iteration I "fire" at that new position and determine where the target will be this time. After about a few repeats I get within a pixel of accuracy.

---

because browsers no longer support Flash player, I ported my example to Unity WebGL: https://jhocking.itch.io/moving-target-aiming

The core algorithm of interest from that demo is:

```
var target = missile.position;
for (var i = 0; i < 3; i++) {
    target = CalculateRefinedTarget(target);
}

```

...

```
private Vector3 CalculateRefinedTarget(Vector3 curTarget) {

    // calculate how long the shot takes
    var shotDist = Vector3.Distance(cannon.position, curTarget);
    var time = shotDist / shotSpeed;

    // calculate where the missile will have moved to
    var missileDist = time * missileSpeed;
    var radians = missile.eulerAngles.z * Mathf.PI / 180;
    var dX = missileDist * Mathf.Sin(radians);
    var dY = missileDist * Mathf.Cos(radians);
    var newTarget = missile.position + new Vector3(-dX, dY, 0);

    return newTarget;
}

```

# Answer
> 1 votes
As you are only working with 2D physics (no Z velocity), this problem can be greatly simplified. The easy way to do this is to stop thinking about both source and target moving relative to world co-ordinates and to just think of the target moving relative to the source (and keep the source stationary).

```
Vector TargetInitialPosition = new Vector ( target.X - source.X ,
                                            target.Y - source.Y );
Vector TargetApparentVelocity = new Vector( target.velocityX - source.velocityX ,
                                            target.velocityY - source.velocityY );

```

Normally, a bullet's velocity would be much higher than the shooter's velocity so it is usually assumed that the bullet is independent but there are occasions where this is not true, such as firing out of a helicopter or fighter jet.

Then we need to work out the bullet velocity:

```
// Your directional vector MUST be normalized...
Vector BulletVelocity = new Vector( source.directionX * Bullet::StaticSpeed + source.velocityX ,
                                     source.directionY * Bullet::StaticSpeed + source.velocityY );

```

The problem you're having is that the target has moved by the time the bullet reaches them.

```
TargetPosition = TargetInitialPosition + TargetApparentVelocity * t
BulletPosition = BulletInitialPosition + BulletVelocity * t
               = BulletVelocity * t

```

and solve for TargetPosition == BulletPosition because then the bullet would have hit the target. Now you have three unknowns and only two equations. We can remove 't' by taking the first order derivative:

```
TargetInitialPosition + ( TargetApparentVelocity - BulletVelocity ) * t == 0
dV / dt = TargetApparentVelocity - BulletVelocity

```

Now to hit the target, you'd want `dV/dt == -TargetInitialPosition * k`. The constant has to be the same in the X and Y coordinates and is the number of seconds the bullet will take to hit the target.

```
TargetApparentVelocity.X - BulletVelocity.X == k * -TargetInitialPosition.X
k = ( BulletVelocity.X - TargetApparentVelocity.X ) / TargetInitialPosition.X
----------------------
TargetApparentVelocity.Y - BulletVelocity.Y == k * -TargetInitialPosition.Y
k = ( BulletVelocity.Y - TargetApparentVelocity.Y ) / TargetInitialPosition.Y

```

make them equal:

```
( BulletVelocity.X - TargetApparentVelocity.X ) / TargetInitialPosition.X
= ( BulletVelocity.Y - TargetApparentVelocity.Y ) / TargetInitialPosition.Y

```

or to expand the variables:

```
( source.directionX * Bullet::StaticSpeed + source.velocityX - target.velocityX + source.velocityX ) / ( target.X - source.X )
 == ( source.directionY * Bullet::StaticSpeed + source.velocityY - target.velocityY + source.velocityY ) / ( target.Y - source.Y )

```

Then algebra gives you your final equation:

```
source.directionY = ( target.velocityY * ( source.X - target.X ) - 2 * source.velocityY * ( source.X - target.X ) + ( Bullet::Speed * source.directionX + 2 * source.velocityX - target.velocityX ) * ( source.Y - target.Y ) ) / ( Bullet::Speed * ( source.X - target.X ) )

```

The next part is messy and it's up to you how you want to implement it in your code, but we just substitute this in and normalize the vector.

```
sqrt( source.directionX ^ 2 + source.directionY ^ 2 ) == 1

```

You end up with an equation with just one unknown (source.directionX), and you can solve it for directionX then substitute back in to get directionY.

I haven't tested any of this code and feel free to point out any methematical misstakes I've made, but the theory should be sound :).

Good luck.

# Answer
> 0 votes
This is just a 3D geometry problem.

First you need the relative position and the relative velocity of the shooter and the target:

```
Pos = TargetPos - ShooterPos
Vel = TargetVel - ShooterVel

```

Then you need to solve the equation:

```
Pos + t * Vel = t * FireSpeed * [x , +-sqrt(1-x^2)]

```

For `t` and `x`.

That makes:

```
x = ( PosX + t * VelX ) / ( t * FireSpeed )

( PosY + t * VelY ) / ( t * FireSpeed ) = +-sqrt(1 - (( PosX + t * VelX ) / ( t * FireSpeed ))^2 )
=>
( PosY + t * VelY )^2 / ( t * FireSpeed )^2 = 1 - (( PosX + t * VelX ) / ( t * FireSpeed ))^2
=>
( PosY + t * VelY )^2 + ( PosX + t * VelX )^2 = ( t * FireSpeed )^2
<=>
( Dot(Vel,Vel) - FireSpeed^2 ) * t^2 + 2 * Dot(Vel,Pos) * t + Dot(Pos,Pos) = 0

```

The last of those equations is a simple quadratic equation, which you should solve. For each positive result you insert the result into the equation:

```
FireVector = Vel + Pos / t

```

This should give you every possible fire vector, where `t` is the time the shot will take.

Note that if `FireSpeed` is greater than the magnitude of `Vel` there will be just one solution, but if `FireSpeed` is smaller there may be two solutions or none at all, or in special cases just a single double solution.

Edit: Better do the maths right or this answer won't be much good.

---
Tags: c++, ai, physics, aiming
---


# Question
Title: CCSpriteFrameCache: Frame '%s' not found
I have just started using the Cocos2D library for Android. I am trying to make a walking bear animation.

For that I am using a `CCSpriteFrameCache`, but I'm getting a "frame not found" error in the log.

I have added an `AnimBear.plist` file and an `AnimBear.png` file (combined image of the various movements of the bear) to the assets folder.

My Java code is as per below :

```
CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("AnimBear.plist");
CCSpriteSheet spriteSheet = CCSpriteSheet.spriteSheet("AnimBear.png");

scene.addChild(spriteSheet);

ArrayList<CCSpriteFrame> walkSprites = new ArrayList<CCSpriteFrame>();

for (int i = 1; i <= 8; ++i)
{
    walkSprites.add(CCSpriteFrameCache.sharedSpriteFrameCache().getSpriteFrame("bear" + i + ".png"));
    System.out.println("bear image is added");
}

CCAnimation walkAnimation = CCAnimation.animation("bear", 0.1f, walkSprites);

bear = CCSprite.sprite(walkSprites.get(0));

this.walkAction = CCRepeatForever.action(CCAnimate.action(walkAnimation, false));

bear.runAction(walkAction);

```

Now here are the errors I get:

> 1. walkSprites.get(0) line throws a Null Pointer Exception.
> 2. CCSpriteFrameCache.sharedSpriteFrameCache().getSpriteFrame("bear" + i + ".png") line prints "CCSpriteFrameCache: Frame '%s' not found" in the logcat

Can anybody help me please, what am I doing wrong?

Thanks in advance.

# Answer
I have just updated my code to below and it starts working. Don't know how it starts to work but its working :)

```
CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames(
            "AnimBear.plist");
    CCSpriteSheet spriteSheet = CCSpriteSheet.spriteSheet("AnimBear.png");

```

// scene.addChild(spriteSheet);

```
    ArrayList<CCSpriteFrame> walkSprites = new ArrayList<CCSpriteFrame>();
    for (int i = 1; i <= 8; ++i) {

        walkSprites.add(CCSpriteFrameCache.sharedSpriteFrameCache()
                .spriteFrameByName("bear" + i + ".png"));
        System.out.println("bear image is added");
    }

    CCAnimation walkAnimation = CCAnimation.animation("bear", 0.1f, walkSprites);

    CGSize winSize = CCDirector.sharedDirector().displaySize();
    bear = CCSprite.sprite(walkSprites.get(0));
    bear.setPosition(CGPoint.ccp(winSize.width / 2.0f, winSize.height / 2.0f));

    this.walkAction = CCRepeatForever.action(CCAnimate.action(walkAnimation, false));

```

// bear.runAction(walkAction);

```
    addChild(bear);

```

I have removed "scene.addChild(spriteSheet);" line from the code.

Anybody can use it if want.
> 0 votes

# Answer
1. You use `walkSprites.get(0)` but you never set it, as your loop goes from 1 to 8.
2. I suspect that the `getSpriteFrame` method is more expecting some kind of id defined in your `AnimBear.plist` rather than a file name.
> 0 votes

---
Tags: java, android, sprites, cocos2d
---


# Question
Title: What would cause my graphics to stop updating when the mouse is moving?
I'm learning metro development with c++, DirectX, win8 CP, vs11 beta. I've come across some unexpected behavior:

Running the tutorial series ( Direct3D Tutorial Sample 1 ), and any sample or app for that matter, If I'm watching motion on the screen such as the cube slowly rotating, and I move the mouse, the object stops updating/rotating until I stop moving the mouse.

Here is a very short video of what I mean: http://www.screencast.com/t/cEHkVUaRcw

It even does this with the shooting sample game, which is very mouse intensive. It makes all the motion very jumpy.

I believe it has something to do with the system. I can interrupt the dispatcher from processing messages and it stops manifesting this behavior so it feels like the computer is so busy processing messages that it can't keep up with the rest of the updating. But this problem only started recently so I do not believe it is a problem with my computer's processing power.

Has anyone else experienced this and know how to resolve it or does anybody have an idea into why this is going on?

Here is the game loop code that MS ships with the sample.

```
while (!m_windowClosed)
{
    timer->Update();
    CoreWindow::GetForCurrentThread()->Dispatcher->ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent);
    m_renderer->Update(timer->Total, timer->Delta);
    m_renderer->Render();
    m_renderer->Present(); // This call is synchronized to the display frame rate.
}

```

Thank you.

# Answer
> 1 votes
I finally found the reason for this behavior. I have a password manager app that loads at startup and is designed to automatically input username/password for my various websites.

When, in a metro app (or at least the DirectX ones), if the window core dispatcher is flagged to ProcessAllIfPresent, it spends time each frame loading and unloading one of the dlls associated with the password manager program.

Once I went to the task manager startup tab and disabled that password management app and closed it down, the behavior went away. Starting it back up brings the behavior right back.

I found it by monitoring the output window while running my DirectX app. I didn't notice it until I discovered "Simulator Debugger" mode where the output window was visible while running the app.

# Answer
> 0 votes
My guess would be the window's callback function, or that ProcessEvents function, has some code for handling mouse movement. When this callback gets messages, your "user" code will be halted while the message is being processed. Mouse movement could be a huge number of messages, hence completely stopping your application from updating.

I personally haven't seen this with simple mouse movement, but sooner or later (dragging the window around, for example) you would likely have encountered this. Edit: well, in a metro style app you might not be doing too much dragging of windows.

If you run your update/render loop in a separate thread from the message processing, it will be unaffected by the callback processing messages. You will need some form of synchronization though if you want to call device or devicecontext methods in reaction to some messages, as D3D doesn't take kindly to being called from multiple threads at once. (resizing your frame buffer after receiving a WM\_SIZE message indicating the window has been moved or resized, for example)

# Answer
> 0 votes
Message processing should be very quick. What you need is a profiler to find out why it isn't.

Profile both the stationary mouse case and the rapidly moving mouse case and compare the two profiles to find out what's taking so long.

# Answer
> 0 votes
I saw this happen with another game project. The mouse messages were being immediately dispatched into a crappy UI library (libRocket). High- resolution gaming mice could generate hundreds of mouse events per frame, and the UI processing simply couldn't keep up.

The solution was to simply set a flag that the mouse had moved and then -- after the event loop -- signal to the UI library that the mouse moved and polling the OS for the current mouse position.

The gaming mice can be pretty ridiculous since they are geared for specs that make no technical sense, but many "l337 gamers" really have no idea how games or computers work and spend tons of money buying low-latency hardware that no game can even take advantage of. (even if you turn off vsync, for instance, the physics that drives all game logic is often fixed time step with only interpolation for high-fps graphics playback.)

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


# Question
Title: Can a texture's UV coordinates be animated (scrolled) when part of a SpriteSheet?
Alright so my question is about texture manipulation in Flash `Stage3D` / `Context3D` using AGAL for the shader language. But I'm pretty sure this could be applicable in other situations involving GPU programming.

So the goal is, if I wish to have a "scrolling" animation on a certain tile (like a tile of water), can I still have that texture packed along with all the rest of my sprite assets? Or does it have to be alone to avoid bleeding nearby assets?

From what I can understand, when the FragmentShader ***samples*** the portion of the texture offsetted during a scroll animation, any coordinates outside the desired texture will reveal incorrect nearby textures.

Some example to clarify:

* Fluid motion (***lava, water waves, acid bubbles***);
* Background motion (***cloud, trees, houses***);
* Directional indicators (***lines on a conveyor belt, race-circuit dash regions***);

Do I need to use some extra operations to wrap the texture if it tries to sample beyond a certain point? How could those constraints be defined / transferred to the **FragmentShader**?

**\- UPDATE -**

To clarify, I would like to scroll only on 1 single tile that would be part of a **SpriteSheet / TextureAtlas** (meaning, mixed with other existing sprites part of a game / project).

Imagine you had something like this (but better artwork, of course):

So a 256 x 256 Texture with a "Wavy Water" tile in the top-left corner (128 x 128 in dimensions).

How would you write a shader that can scroll through **ONLY** the water portion to give a sense of motion without running over the adjacent textures (ex: faces and cars).

How would you handle situations where the Quad is much larger than the texture and could repeat many times as well in combination to being able to scroll it?

# Answer
> 0 votes
Here is the idea & explanation behind how I created the tile scrolling UVs:

Making Scrollable Tiles with UV Offsets in Stage3D and AGAL

Basically, it involves creating a VertexBuffer filled with Vertex-Constant IDs to refer to when the vertex-shader executes and passes data to the fragment-shader. Depending how you set it up, there can be limitations as to how many tiles are scrolling in one draw pass, but should still be more than enough for most tile scrolling games / applications.

# Answer
> 1 votes
As you've asked me, here's my short OpenGL answer. Might not be fully optimized, just sketching something for you now.

Lets assume you have your texture:

```
class Texture
{
    Int2 size;
}

```

And you have your quad:

```
class Quad
{
    Float3[4] vertices;
    Int2[4] iuvs;
    Float2[4] uvs;
    Texture texture;
}

```

Float 3 is:

```
class Float3
{
    float x, y, z;
}

```

Float 2 is:

```
class Float2
{
    float u,v;
}

```

Int2 is: class Int2 { int w, h; }

Lets throw up some theory of what we'll do.

As you know, in UV coordinates, 0 mean the the beginning of a coordinate, 1 mean the final.

So, 0.5, 0.5 will take half of your texture and stretch it on your quad. 1.0, 1.0 will take your full texture and stretch it on your quad.

Assume our texture size is 800x50. And our quad is positioned at 0,0 and its size is 50x50.
So vertices 1 = (0,0,0)
vertice 2 = (50,0,0)
vertice 3 = (50,50,0)
vertice 4 = (0,50,0)

That should be nothing new to you.

And we want the quad to take the relative part of the texture. So lets set the iuv to 50x50

quad.iuvs = Int2(50, 50);

The iuvs i'm just wanting to store it.

Lets make the uvs of the quad take the texture size of the actual quad. So divide to reach the exact size. uv 1 is 0 / 800, 0 / 50 -\> (0, 0)
uv 2 is 50 / 800, 0 / 50 -\> (0.0625, 0)
uv 3 is 50 / 800, 50 / 50 -\> (0.0625, 1)
uv 4 is 0 / 800, 50 / 50 -\> (0, 1)

That give us a function!

```
Quad::SetUV()
{
    for(int i = 0; i < 4; i++)
    {
        uvs[i] = Float2(iuv[i].w / texture.size.w, iuv[i].h / texture.size.h);
    }
}

```

Easy enough to make your quad get the first 50x50 of the texture :D

Now comes the tricky part!

As you can see, the texture width is much higher than the quad width. So lets see what we can do.

## Scroll through an entire texture

On your quad, just call every frame

```
ScrollW()
{
    if(iuv[1].w >= texture.size.w)
    {
        iuv[0] = Int2(0, 0);
        iuv[1] = Int2(vertices[2].x, 0);
        iuv[2] = Int2(vertices[2].x, vertices[2].y);
        iuv[3] = Int2(0, vertices[2].y);
    }
    else
    {
        foreach(Int2 i in iuv)
        {
            i.w++;
        }
    }
    setUV();
}

```

Done! If the uv is covering a valid area of the texture, scroll right. If its alread on the final of the texture, go to start!

Now should be easy to implement others, as scroll as tiles of fixed size, etc.

---
Tags: flash, textures, shaders, gpu, spritesheet
---


# Question
Title: How can I store a set of concrete components and implement "GetComponent<T>()?"
I would like an abstract class, AbstractComponentAggregate, which has many AbstractComponents. Users of my framework will create their components by extending AbstractComponent and appending the component to this AbstractComponentAggregate.

I would like to know if there is an elegant way to have AbstractComponentAggregate to store a dictionary of the concrete classes that extend AbstractComponents. Note, that I want to store many *concrete* classes, each of which is an AbstractComponent. This is different than storing a list of AbstractComponents.

Thus, you can invoke a method on AbstractComponentAggregate, such as:

AbstractComponentAggregate.GetComponent(), which returns type T. T is the concrete class, and we ensure T is of type AbstractComponent.

Something similar to this is done in Unity3d, and I would like to emulate this.

# Answer
> I would like to know if there is an elegant way to have AbstractComponentAggregate to store a dictionary of the concrete classes that extend AbstractComponents. Note, that I want to store many concrete classes, each of which is an AbstractComponent. This is different than storing a list of AbstractComponents.

Assuming the type of your dictionary key is `K`, then `Dictionary<K, AbstractComponent>` will allow you to store instances of concrete AbstractComponent subclasses (such as `FooComponent` and `BarComponent`):

```
var items = new Dictionary<K, AbstractComponent>();
items[K0] = new FooComponent();
items[K1] = new BarComponent();

```

`GetComponent` can look something like:

```
public T GetComponent<T>() {
   // I'm assuming T's type is the dictionary key here.
   AbstractComponent result;
   if(!items.TryGetValue( typeof(T), out result ) ) {
       // Fail here, perhaps with an exception?
   }

   return (T)result;
}

```

This would raise an `InvalidCastException` if the `AbstractComponent` wasn't really an instance of the concrete class `T`. You could use `GetType()` on the result variable and compare the types directly if you wanted to raise a more user-friendly exception.

The code sample assumes you're talking about C#, but the concepts in general are transferable.
> 4 votes

# Answer
Here you go. It's a primitive version of the Implementation I used in Duality which is more or less inspired by Unity.

```
public sealed class GameObject
{
    private Dictionary<Type,Component> compMap = new Dictionary<Type,Component>();

    public T GetComponent<T>() where T : Component
    {
        return GetComponent(typeof(T)) as T;
    }
    public Component GetComponent(Type t)
    {
        Component result;
        if (this.compMap.TryGetValue(t, out result))
            return result;
        else
            return null;
    }

    public T AddComponent<T>() where T : Component, new()
    {
        if (this.compMap.ContainsKey(typeof(T))) return this.compMap[typeof(T)] as T;
        T newComp = new T();
        return this.AddComponent<T>(newComp);
    }
    public Component AddComponent(Type t)
    {
        if (!typeof(Component).IsAssignableFrom(t)) return null;
        if (this.compMap.ContainsKey(t)) return this.compMap[t];
        Component newComp = Activator.CreateInstance(t, true) as Component;
        return this.AddComponent<Component>(newComp);
    }
    public T AddComponent<T>(T newComp) where T : Component
    {
        Type cType = newComp.GetType();
        if (this.compMap.ContainsKey(cType)) return this.compMap[cType] as T;

        this.compMap.Add(cType, newComp);

        return newComp;
    }
    public T RemoveComponent<T>() where T : Component
    {
        return this.RemoveComponent(typeof(T)) as T;
    }
    public Component RemoveComponent(Type t)
    {
        Component cmp = this.GetComponent(t);
        if (cmp != null) this.RemoveComponent(cmp);
        return cmp;
    }
    public void RemoveComponent(Component cmp)
    {
        this.compMap.Remove(cmp.GetType());
    }
    public void ClearComponents()
    {
        this.compMap.Clear();
    }
}

```

Hope this helps.
> 2 votes

---
Tags: architecture, unity, component-based
---


title: JBox2D - how to get vertex positions?

text:
# Question
Title: JBox2D - how to get vertex positions?
I've created a triangle for jbox2d...

```
public void createTri(){

    PolygonDef shape = new PolygonDef();

    shape.density = 2.0f;

    shape.friction = 0.8f;
    shape.restitution = 0.3f;
    shape.addVertex( new Vec2(35/RATE,35/RATE) );
    shape.addVertex( new Vec2(65/RATE,35/RATE) );
    shape.addVertex( new Vec2(45/RATE,55/RATE) );

    BodyDef bodyDef = new BodyDef();
    bodyDef.position.set(50/RATE, 50/RATE);
    bodyT= world.createBody(bodyDef);
    bodyT.createShape(shape);
    bodyT.setMassFromShapes();
}

```

... but when drawing it on canvas, how to I get position of all the vertexes?

with bodyT.getPosition().x and .y I can get only the center spot.

Thanks!

# Answer
I don't know about JBox2D but in the actual Box2D lib there is PolygonShape.GetVertex()

```
  //Returns a Vec2 (the coordinates) of a vertex given its index
  const b2Vec2& GetVertex(int32 index) const;

```

So according to your code, I think calling shape.GetVertex(1) returns the second vertex you added.
> 1 votes

---
Tags: java, box2d, jbox2d
---


title: Logic to path finding checking

text:
# Question
Title: Logic to path finding checking
I'm a little stuck on the logic to how i use my path finder efficiently in my game.

This is basically how the game works:

```
Building generates goods "Factory" > AI transports goods to "Warehouse" on path tiles >
  Warehouse receives goods > AI goes back to Factory.

```

Now im wondering how I use my path finder efficiently so its checking the "Factory" is connected to a warehouse by path.

So heres my logic im wondering if it can be improved:

```
User places factory down > game checks path.

Result 1: No path found> Keep checking every frame..

Result 2: Path found > Store path stop rechecking every frame.

```

The two problems i have is: Well checking every frame is going to hurt the game's performance, secondly if I stop rechecking - it won't know when a faster route may become available or unavailable =/

Is my logic correct or is there a better method?

# Answer
If you want to avoid checking every frame, instead check every time something changes (e.g. whenever a new factory/warehouse/path tile/etc is placed). These times are the only times that the paths might need to be updated anyway, since these are the only times that a different route may become available or an old one be closed.

**EDIT**

If you find re-calculating *all* paths each time a change is made is too slow, then there are ways of speeding that up too. For example, if you add a new factory you'll at a minimum need to calculate the paths starting from that point to your warehouses. If you find that these paths cross any existing paths, that's a clue that those paths might need updating too. I'm not sure on specifics, that probably depends a little on your particular game.

However, it seems to me that you are probably undertaking a bit of premature optimisation. It's usually best to just do things the easy way first, and only worry about these kind of optimisations when they are actually needed. Otherwise, you can waste a lot of effort producing code that is way more "clever" than it needs to be, and which is often much harder to understand (and hence maintain) than the simple approach.
> 3 votes

# Answer
Well, you always can reduce checking frequency by some amount. If immediate path detection isn't requred, you can perform checking say once in a second, thus reducing load by your default fps.
> 0 votes

# Answer
Here's a great introduction to A\* pathfinding. http://theory.stanford.edu/~amitp/GameProgramming/

Ideas:

* Delaying to check on events, ie: road tile destruction, or road creation.
* Path on intervals. Once a second may even be more than needed.
* test it : you may find it runs fast enough, even non-optimized.
* Partial steps: You can break the search into steps. Find 1/2 the distance. move there. pathfind the rest, once he is at that location.
> 0 votes

---
Tags: path-finding, logic
---


# Question
Title: What is the Relative Rarity of Blocks Generated in Minecraft?
I was watching a tutorial from last year that was discussing how to create blocks that would be generated with the world. I have lost the link to the video, but the basic issue I'm having here is simple. In the video the presenter showed the **ChunkProviderGeneate.java** file in which there were multiple lines of code such as this for each of the available types of block (dirt, sand, various ores, etc):

```
for(int i=0; i < 30; i++){
        int randPosX = chunkX + random.nextInt(16);
        int randPosY = random.nextInt(128);
        int randPosZ = chunkZ = random.nextInt(16);
        (new WorldGenMinable(oreUranium.blockID, 16)).generate(world, random, randPosX, randPosY, randPosZ);
    }

```

Unfortunately, the code appears to be updated and I don't know where it is. If it was I'd be able to answer a rather basic question. **Exactly what is the approximate ratio of each block being generated in relation to each other?** Or better yet, where can I find the code that determines this?

# Answer
> 2 votes
The Minecraft Wiki article on Ore includes a chart of Ore density by Y-height. Looking at the noise in the graph I'd say the source is from empirical measurement rather than reverse engineering the code. This only covers ore; it doesn't cover relative density of gravel vs rock, etc.

If you want to look at the actual Minecraft code, you may find the Minecraft Coder Pack useful. It contains tools to decompile and deobfuscate the live Minecraft code. Their javadoc includes a ChunkProviderGenerate class still, so you could start with the code they generate for that class. MCP also includes tools to help you build your mod in a way that's compatible with current Minecraft releases. I have no idea what the license issues are around decompiling Minecraft code in this way.

---
Tags: maps, level-design, minecraft-modding
---