# Question
Title: How to deal with arbitrarily large images in 2D games?
**Question**

When you have a 2D game that uses really large images (larger than your hardware can support), what do you do? Maybe there's some interesting solution to this problem that never occured to me before.

I'm basically working on a sort of graphic adventure game maker. My target audience are people with little to no game development (and programming) experience. If you were working with such an application, wouldn't you prefer for it to handle the problem internally rather than telling you to "go split your images"?

**Context**

It's well known that graphic cards impose a set of restrictions on the size of the textures they can use. For instance, when working with XNA you're restricted to a maximum texture size of 2048 or 4096 pixels depending on which profile you choose.

Usually this doesn't pose much a problem in 2D games because most of them have levels that can be constructed from smaller individual pieces (e.g. tiles or transformed sprites).

But think about a few classic point'n'click graphic adventure games (e.g. Monkey Island). Rooms in graphic adventure games are usually designed as a whole, with little or no repeatable sections, just like a painter working on a landscape. Or perhaps a game like Final Fantasy 7 which uses large pre-rendered backgrounds.

Some of these rooms can get pretty large, frequently spanning three or more screens of width. Now if we consider these backgrounds in the context of a modern high definition game, they will easily exceed the maximum supported texture size.

Now, the obvious solution to this is to split the background into smaller sections that fit within the requirements and draw them side by side. But should you (or your artist) have to be the one splitting all of your textures?

If you're working with a high level API, shouldn't it perhaps be prepared to deal with this situation and do the splitting and assembling of the textures internally (either as a pre-process such as XNA's Content Pipeline or at runtime)?

**Edit**

Here's what I was thinking, from a XNA implementation point of view.

My 2D engine only requires a very small subset of Texture2D's functionality. I can actually reduce it down to this interface:

```
public interface ITexture
{
    int Height { get; }
    int Width { get; }
    void Draw(SpriteBatch spriteBatch, Vector2 position, Rectangle? source, Color  color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth);
}

```

The only external method I use that relies on Texture2D is SpriteBatch.Draw() so I could create a bridge between them by adding an extension method:

```
    public static void Draw(this SpriteBatch spriteBatch, ITexture texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
    {
        texture.Draw(spriteBatch, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth);
    }

```

This would allow me to use an ITexture interchangibly whenever I used a Texture2D before.

Then I could create two different implementations of ITexture e.g. RegularTexture and LargeTexture, where RegularTexture would simply wrap a regular Texture2D.

On the other hand, LargeTexture would keep a List of Texture2D's each corresponding to one of the splitted pieces of the full image. The most important part is that calling Draw() on the LargeTexture should be able to apply all the transformations and draw all the pieces as if they were just one contiguous image.

Finally, to make the entire process transparent, I'd create an unified texture loader class that would act as a Factory Method. It would take the path of the texture as a parameter and return a ITexture which would be either a RegularTexture or a LargeTexture depending on the image size exceeding the limit or not. But the user didn't need to know which one it was.

A bit overkill or does it sound okay?

# Answer
I think you are on the right track. You have to split the images to smaller pieces. Since you making a game maker you can't use the XNA's Content pipeline. Unless your maker is more like an Engine that will still require the developers to use Visual Studio. So you need to build your own routines that will do the splitting. You should even consider streaming the pieces a bit before that become visizble so that you still don't put limit of how much video memory the players should have.

There are some tricks you can do specifically for adventure games. I imagine like all classic adventure games you will have few layers of these textures so that ... your character can walk behind the tree or the building...

If you want these layers to have paralaxing effect then when you splitting your tiles just skip all the translucent once. Here you need to think of the size of the tiles. Smaller tiles will add managing overhead and draw calls, but will be less data where larger tiles will be more GPU friendly but will have a lot of translucency.

If you don't have paralaxing effect then instead of covering the whole scene with 2-4 giant images that have 32bits depth you can create just one 32 bits depth. And you can have a stenciling or depth layer that will be only 8 bits per pixel.

I know this sound like hard to manage assets by non game developers but it actually doesn't have to be. For example if you have a street with 3 trees and the player goes behind 2 of them and in front of the third tree and the rest of the background... Just make the scene layout the way you want in your editor and then in a build step from your game maker you can bake these giant images (well small tiles of a big image).

About how the classic games were doing it. I'm not sure they probably did simmilar tricks but you have to remember that at the time the screen were 320x240 the games were with 16 colors which when using palattelized textures allows you to encode 2 pixels in single byte. But this is not how the current architectures work so :D

Good Luck
> 5 votes

# Answer
Cut them up so they're no longer arbitrarily large, like you say. There is no magic. Those old 2D games either did that or they were rendered in software, in which case there were no hardware restrictions beyond RAM size. Of note is that many of those 2D games really didn't have huge backgrounds, they just scrolled slowly so they felt huge.

What you're looking to do in your graphic adventure game maker is pre-process those big images during some kind of "build" or "integrate" step before the game is packaged up to run.

If you want to use an existing API and library instead of writing your own I'd suggest that you convert those big images to tiles during that "build" and use a 2D tile engine, of which there are many.

If you want to use 3D techniques of your own you may still want to split into tiles and use a well known and well designed 2D API to write your own 3D library for that, in this way you're guaranteed to at least be starting with a good API design and less design required on your part.
> 2 votes

# Answer
If you're familiar with how a quadtree looks in visual practice, I have used a method that cuts detailed large images into smaller images relatively similar to what a proof/visualization of a quadtree looks like. However mine were made that way to cut up areas specifically that could be encoded or compressed differently based on the color. You could use this method and do what I described, as it is also useful.

At run time cutting them would require more memory temporarily and cause load times to be slowed down. I would say though it depends on whether you care more about physical storage or the load time of a users game made with your editor.

**Load/Run Time:** The way that I would go about the loading is just cutting it up into proportionally sized pieces. Account for one pixel on the right most piece if it's odd number of pixels though, no one likes their images being cut, especially inexperienced users who might just not know that it's not entirely up to them. Make them half the width OR half the height (or 3rds, 4ths whatever) the reason not into squares or 4 sections (2 rows 2 columns) is because it would make tiling memory smaller since you wouldn't be worrying about both x and y at the same time (and depending on how many images are that large, it could be pretty important)

**Before Hand/Automatically:** In this case I like the idea of giving the user the choice of storing it in one image or storing it as separate pieces (one image should be default). Storing the image as a .gif would work great. The image would be in one file, and rather than each frame being an animation it would be more like a compressed archive of all the same image (which is essentially what a .gif is anyway). It would allow for ease of physical file transportation, ease of loading:

1. It's a single file
2. All of the files would have almost identical formatting
3. You could easily choose when AND if to cut it up into individual textures
4. It may be easier to access the individual images if they're already in a single loaded .gif since it wouldn't require as much of a mess of image files in memory

Oh and if you use the .gif method, you should change the file extension to something else (.gif -\> .kittens) for the sake of less confusion when your .gif animates like it's a broken file. (don't worry about legality of that, .gif is an open format)
> 1 votes

# Answer
This is going to sound obvious, but, why not just split your room into smaller pieces? Pick an arbitrary size that won't bump heads against any graphics cards (like 1024x1024, or maybe larger) and just break your rooms into multiple pieces.

I know that this avoids the problem, and honestly, this is a very interesting problem to solve. Anyway, this is kind of a trivial solution, which may work some of the time for you.
> 0 votes

---
Tags: xna, c#, 2d, graphics, textures
---


title: c# xna move Image using two Vectors?

text:
# Question
Title: c# xna move Image using two Vectors?
initially image placed (0,0)th position and where ever i touch that is end position.

Now i got Start Position(0,0) and End Position(200,200).

i want to move start to end vector using angle.

If anyone now the ans please tell me.

# Answer
You need to find the delta between your two vectors and just move the sprite along that new vector.

```
Vector2 startPos = new Vector2(0,0);
Vector2 endPos = new Vector2(100,200);

Vector2 delta = endPos - startPos;

//see if he is at the target. Very rarely will it be Vector2.Zero, so subtract 3 to get you close. If you don't do this your sprite can bounce.
if ((delta.X > -3 && delta.X < 3)
  && (delta.Y > -3 && delta.Y < 3))
{
    sprite.Moving= false;
}

if(sprite.Moving)
{
    delta.Normalize() //you want to normalize the vector. Otherwise he will move faster diagnoally

    sprite.Position += delta *5f;  //5f is a random speed I chose. The higher this number, the faster he will move
}

```
> 1 votes

---
Tags: xna, path-finding, windows-phone-7, angles
---


title: Help with fleet combat strategy game AI

text:
# Question
Title: Help with fleet combat strategy game AI
can you tell me how to implement a game AI like the sea battle Ai in NAPOLEON:total war.

I want to finish a small game,which the ship can occupy the island to produce more ships and my fleet can battle with the others. can you give me an example,or what should i learn to finish it. Thank you~

# Answer
This article could help you: http://www.gamasutra.com/view/feature/1535/designing\_ai\_algorithms\_for\_.php
> 0 votes

---
Tags: algorithm, ai
---


# Question
Title: What technology does Starcraft 2 use render its maps?
I've got a map that is being procedurally generated at run-time and I'm currently investigating methods of rendering this map. I've taken an interest in the look of Starcraft 2 and I'd like some advise on what methods it employs to achieve it. Secondarily, I'd like to see any tutorials, articles, or even source code examples if possible.

There are a couple of main things I'd like to get some advise on, but please also feel free to suggest anything else that could help me.

1. Snappable Tilesets - A typical starcraft map seems to consist of a tileset of models that one can snap together to create the cliffs, ramps and other elevated terrain. What methods do they employ to make them look so natural? What I mean is, its very hard to spot repetition.
2. Terrain Textures - The terrain textures are so varied and even dynamic (Zerg creep). What methods are used to do this?

Thanks.

# Answer
I think part of it may just be that Blizzard has an amazing number of texture artists. But let's rephrase the question a bit:

> I have a limited budget and want to make a realtime strategy game without obviously tiling textures. How can I accomplish that?

Good question! Here's a few big tools that I'd use:

1) **A reasonably large set of interchangeable tiles**. Say you're going with a 64x64 texture size on your grid: make eight 64x64 textures, any of which can tile with any others, and you've got a nice-looking tilebased game with a lot of variation!

2) **Decals or megatexturing**. Take your repeated texture and a small number of "smudge" or "dirt" or "scuff" overlay textures. Splatter a few of those overlays on your textures. These can be rendered in realtime, in which case they're decals, or baked into a ginormous texture, in which case it's called megatexturing. In either case you can probably do it semi-randomly, and you'll get a lot of variation with only a few applied overlays.

3) **Cicada tiles**. Check out this for more detail on how this works. In summary, it's a way to take a small number of partially-transparent obviously-tiling backgrounds and use it to generate a far-less-obviously-tiling background.

4) **Texture splatting**. I've saved this one for last because it's not really about avoiding tiling on a single texture, it's really about combining multiple textures seamlessly. However, if you can manage to eke out a few extra textures in your budget, this can be a critical tool - in fact, I'd say if you're *not* using this, you're probably doing something wrong. This won't help with large obviously-tiled sections of a single texture type, but this is what you'll use to make your various textures look good next to each other.
> 23 votes

---
Tags: textures, terrain, procedural
---


title: Create apk from libgdx project

text:
# Question
Title: Create apk from libgdx project
What is the basic procedure to create the signed apk for my libGDX project? I am new to libGDX so provide some guidance.

I am talking about deploying apk to the Android market. I have to ask this question because my Galaxy SX2 display only blank screen.

# Answer
> 2 votes
If you mean the APK for debugging on Android, I wouldn't worry. Once you have your project setup, plugging your phone in will make Eclipse automatically upload and run the APK on your phone.

The Android project in your workspace will generate the APK in \bin. In my case, I had a `game-core` project and an `android-specific` project, and my APK shows up in `\android-specific\bin`.

**Edit:** since you mentioned deploying your app to the store, you need to sign it. Detailed instructions here here on their wiki:

> * Right click your Android project and select "Export"
> * Select "Android -\> Export Android Application"
> * Make sure the project you want to export is your project, select next
> * Select or create your keystore. If you are new to Android development, a keystore is used to sign your applications and is required for putting your application on the market. More information is available at: http://developer.android.com/tools/publishing/app-signing.html
> * Select your alias to sign with and enter the password. If you don't have an alias or want to create a new alias, select create new key and select next.
> * Now select the destination of where you want your app being exported to. This will export an .apk file in the selected directory capable of being uploaded to Google Play (formerly Android Market) and alternative app stores.
> * Select finish and your .apk will be built!

---
Tags: libgdx
---


# Question
Title: How do I create a "wormhole" effect in C# and DirectX
I am trying to create an effect called wormhole effect. I am using a shader file but I am not getting the exact effect. Does anyone have any idea or any smple shader file which can help me?

The effect looks something like the effect named "Wormhole" at found here (bottom right).

The shader file I am trying to improve is based on "Ripple" effect but I am not able to get that much smooth effect.

```
/// <class>RippleTransitionEffect</class>

/// <description>A transition effect </description>
/// <summary>The amount(%) of the transition from first texture to the second texture. </summary>
/// <minValue>0</minValue>
/// <maxValue>1</maxValue>
/// <defaultValue>0</defaultValue>
float Progress : register(C0);

sampler input : register(s0);

texture Texture;
sampler Texture2 = sampler_state
{
    texture = <Texture>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = mirror;
    AddressV = mirror;
};

float4 Ripple(float2 uv,float progress)
{
  float radius = progress *  0.75;
  float FuzzyAmount = 0.001;
  float2 CenterPoint = float2(0.5,0.5);
  float fromCenter = length((uv - CenterPoint) / float2(0.75, 1));
  float distFromCircle = fromCenter - radius;

  float frequency = 10;
  float speed = 1;
  float amplitude = 0.005;

  float wave = cos(frequency * distFromCircle - speed * progress) + 2;
  float offset1 = progress * wave * amplitude;
  float offset2 = (1.0 - progress) * wave * amplitude;
  float2 normToUV = (uv - CenterPoint) / distFromCircle;

  float2 newUV1 = CenterPoint + normToUV * (distFromCircle + offset1);
  float2 newUV2 = CenterPoint + normToUV * (distFromCircle + offset2);

  float4 c1 = tex2D(Texture2, newUV1);
  float4 c2 = tex2D(input, newUV2);

  float p = saturate((distFromCircle + FuzzyAmount) / (1.0 * FuzzyAmount));
  return lerp(c1, c2, p );
}

float4 main(float2 tex: TEXCOORD) : COlOR
{
  return Ripple(tex, Progress);
}

technique TransformTexture {
  pass P0     {
    PixelShader  = compile ps_2_0 main();
  }
}

```

# Answer
This shader snippet is just a hint on how I would do it, it's not a complete copy-paste-done! solution.

```
float4 Wormhole(float2 uv, float progress)
{
    float rad = 0.708 * progress; // radius from center of the uv texture square
    float swell = 0.1; // swell region magnitude
    float2 CPoint(0.5, 0.5); // center point
    float dist = length(uv - CPoint);
    float2 uvOrig = uv;
    float2 uvNew = uv;
    float alpha = 0; // blend factor between the 2 textures
    if (dist < rad) // show the new texture - this expands from center outwards
    {
        alpha = 1; //when inside, show the new texture colour
    }
    if (dist > rad && dist < rad + swell)
    {
        float lambda = smoothstep(rad, rad+swell, dist); // factor in [0,1]
        alpha = 1 - lambda; // modified blend factor
        float2 vec = uvOrig - CPoint;
        float2 dir = normalize(vec);
        uvOrig = CPoint + ((1-lambda) * rad + lambda * (rad+swell)) * dir;
    }
    if (dist >= rad + swell)
        alpha = 0; // show the new texture only
    float4 c1 = tex2D(Texture2, uvNew);
    float4 c2 = tex2D(input, uvOrig);
    return lerp(c2,c1,alpha);
}

```

---

What does it do? Starting from the center, it should modify a linear interpolation factor based on the texture coordinates of that fragment. If the fragment is "inside" the wormhole, it shows the new texture. If the fragment is outside, but not too far (swell area), it show a blended color between the original "swelled" image and the new image. The fragments that are further away maintain the original texture color. That's how I would write a very simple wormhole shader.
> 2 votes

---
Tags: directx
---


# Question
Title: Most efficient language for rewriting a tile-based board game as a video game?
I've been working on a hex-based board game. Every time I make changes, especially changes that require redesigning the map, it takes a good chunk of time and money. It might be more efficient to write it as a video game, at least for designing it and showing off mock-ups. I've always wanted to learn a programming language anyways, so this gives me a good excuse.

Things that are important:

* Hex grid movement, obviously
* Hot-seat or online play - it's a multiplayer board game, thus a multiplayer video game
* Keep track of what you might call "touchdowns" at a specific location, as well as HP and movement speed

AI would be unnecessary, so would sound effects or a matchmaking server. I just want to be able to show this to people.

Languages I've thought about learning before:

* Flash, because it's ubiquitous
* C seems to be an industry standard for video games
* Javascript, because it seems to be the more powerful successor to flash
* Python, because geeks always geek out about how awesome it is

If one of those languages would work well for my purposes, awesome! If there's a more efficient language to learn for this particular application though, I'm open to that.

# Answer
> Things that are important:
>
> Hex grid movement, obviously Hot-seat or online play - it's a multiplayer board game, thus a multiplayer video game Keep track of what you might call "touchdowns" at a specific location, as well as HP and movement speed AI would be unnecessary, so would sound effects or a matchmaking server. I just want to be able to show this to people.

None of these really factor into what language you might choose.

> Flash, because it's ubiquitous.

This is true. There's also a lot work that's recently gone into making it easy to make Flash games (see Flixel and Flashpunk as examples).

> Java, because it seems to be the more powerful successor to flash.

"Successor" is a strange term to use here. Java applets ultimately lost to Flash, which is subsequently becoming less cool in comparison to pure javascript.

> C# seems to be an industry standard for video games.

"Industry standard" is a strange term to use here. When you're talking about large console and PC games ("AAA" games), C++ is actually the indsutry standard. If you're talking about Unity games, or tools development, or XNA, then C# is the standard. C# is a great language. However, the reasons I find it great are because of the advanced programming features it offers over Java. This may not be as useful to you.

I'm going to argue against using Unity for a couple of reasons:

1. You need to purchase a tool to help you make 2D games.
2. Learning to program with Unity's programming model will leave you with gaps in knowledge about how to structure a program from the top level. It revolves around writing scripts to create components that are then attached to objects. You are shielded from the main loop, which is an important concept to grasp in game programming. Unity's awesome and I love it, but I wouldn't recommend learning to program with it.

> Python, because geeks always geek out about how awesome it is.

Python is wonderful (so is Ruby). You can get a lot done quickly, and making a basic 2D game with pygame is very straightforward. However, you run into problems if you want to distribute the game. There are tools, py2exe and py2app, to help you distribute, but I've never had either work 100% reliably.

If you don't intend to be able to distribute your game, then Python is a great way to go. Check out Learn Python the Hard Way and Invent Your Own Computer Games with Python. If you'd like to be able to have people easily download your game for playtesting or to just be able to set it up on a computer other than your own, I'd recommend Flash. C# and Java are nice, but if your primary goal is not to make a *computer* game you may find it more efficient to use Flash or Python.

Both Flash and Python can do online play, but there may be more readymade tools and libraries available for enabling online multiplayer in Flash games. Be aware that this is not a trivial problem to solve.
> 8 votes

# Answer
Making changes to a video game will be neither faster nor cheaper (if you assign any value to time) than the same changes made to a board game.

Design changes are much, much faster and easier to make for physical games (board, card, etc) than for video games. So much so that those of us who work on video games professionally will usually try to prototype using boards or cards whenever we can, simply because that's so much faster and more efficient for working out what designs work and what designs don't.

If you want to learn a programming language and make a video game, that's great. It's a tremendously broadening experience and you may find it to be uniquely challenging and rewarding, the way that I and many others do. I can't recommend it highly enough.

But it will **not** be faster and cheaper.

So if fast and cheap is your goal, my advice is to stick with the physical boards for prototyping.
> 3 votes

# Answer
If you just want to have easy editing and testing, I'd suggest Unity with C#. You can create your board either by hand or code and see and test it simply by pressing play in the editor. Unity is easy to learn and lots of tutorials around.
> 2 votes

# Answer
I wouldn't start from the programming language, but rather from the engine and then find a language that support it. Unity, as suggested, is a good option, but if you're just looking for a mock-up maybe a 2d engine might be simpler and more up your aisle. Seems like this question might help you.

And even if you wan to begin from languages, I'd go with c#, maybe Java. They're both strongly object-oriented and so very suitable for modular construction.
> 2 votes

# Answer
JavaScript has many flaws, but it has many advantages for what you're trying to do:

1. There's plenty of excellent documentation resources.
2. There's plenty of very good libraries.
3. Also plenty of tools (Chrome's debugger, FireBug, WebDeveloper extension, ...)
4. It's cross platform and works in the browser, obviously.
5. Supports 3D with recent browsers
6. You can see the result of what you do immediately, and share it just as easily.
7. If you want to make a networked game, it's easy with node.js
> 0 votes

---
Tags: architecture, software-engineering, homebrew
---


# Question
Title: How to make something rotate a certain amount over an exact amount of time
I'm trying to make a plane rotate down a certain amount and 180 degrees horizontally over 2 seconds.

Basically I want it to take the plane 1 second to rotate to a horizontal-facing angle, then take the other second to rotate 180 degrees around to face the other direction.

The formula I'm currently using is:

```
    //If you're rotating, lower the speed and rotate the plane.
    if (rotate == 1 && rotationPhase > 0) {
        //If in phase 0, figure out which phase you need too go to.
        if (angle > 90 && rotationPhase == 1) {
            //Rotation phase 2 = rotating down
            rotationPhase = 2;
            rotationAngleTime = angle - 90;
        }
        else if (rotationPhase == 1) {
            //Rotation phase 3 = rotating up
            rotationPhase = 3;
            rotationAngleTime = 90 - angle;
        }

        //After phase 0, if in phase 1 begin rotating down, if in phase 2 begin rotating up.
        if (angle > 90 && rotationPhase == 2) {
            transform.Rotate(0, 0, -rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle -= rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }
        else if (rotationPhase == 3) {
            transform.Rotate(0, 0, rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }

        //After you have rotated to horizontal in phase 1/2, rotate around to face the other direction.
        if (rotationPhase == 4) {
            transform.Rotate(rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)), 0, 0);
            rotationAngle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (rotationAngle > 179) {
                rotationAngle = 0;
                rotationPhase = 0;
                rotationAngleTime = 0;
            }
        }
    }

```

I've tried many different things, but I can't figure out what to do.

EDIT: This seems to be a problem with Time.deltaTime. I can get the plane to rotate correctly, but for some reason it's not rotating over the right amount of time. I have a timer being subtracted by Time.deltaTime, and this animation happening, and the animation always finishes about half a second before the timer runs out.

# Answer
EDIT: This makes the animation run properly, but it's still not running at the correct amount of time.

I figured out how to fix the problem myself, the solution was:

```
//If you're rotating, lower the speed and rotate the plane.
    if (rotate == 1 && rotationPhase > 0) {
        //If in phase 0, figure out which phase you need too go to.
        if (angle > 90 && rotationPhase == 1) {
            //Rotation phase 2 = rotating down
            rotationPhase = 2;
            rotationAngleTime = angle - 90;
        }
        else if (rotationPhase == 1) {
            //Rotation phase 3 = rotating up
            rotationPhase = 3;
            rotationAngleTime = 90 - angle;
        }

        //After phase 0, if in phase 1 begin rotating down, if in phase 2 begin rotating up.
        if (angle > 90 && rotationPhase == 2) {
            transform.Rotate(0, 0, -rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle -= rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }
        else if (rotationPhase == 3) {
            transform.Rotate(0, 0, rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)));
            angle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (angle > 89 && angle < 91) {
                angle = 90;
                rotationPhase = 4;
                rotationAngleTime = 180;
            }
        }

        //After you have rotated to horizontal in phase 1/2, rotate around to face the other direction.
        if (rotationPhase == 4) {
            transform.Rotate(rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2)), 0, 0);
            rotationAngle += rotationAngleTime * (Time.deltaTime * (rotationSpeed / 2));
            if (rotationAngle > 179) {
                rotationAngle = 0;
                rotationPhase = 0;
                rotationAngleTime = 0;
            }
        }
    }

```
> 0 votes

# Answer
Use the line:

```
transform.Rotate(Vector3.up, horizontalAngle*Time.deltaTime);

```

to carry out the horizontal rotation over 1 second. Then use the line:

```
transform.Rotate(Vector3.right, verticalAngle*Time.deltaTime);

```

to carry out the second phase of your rotation. You can keep track of which rotation you're supposed to be applying using a method similar to the one you posted (the `rotationPhase` variable), but I would recommend using an `enum` for readability:

```
enum RotationPhase { Horizontal, Vertical };
public RotationPhase currentPhase = RotationPhase.Horizontal;

```

Finally, if you want to create a smoother rotation, you can look into the `Vector3.SmoothDamp` function; the documentation is here. In order to use this method you will first need to calculate the forward vectors of the plane as a result of each rotation. That vector becomes you're "target" vector. Then you can check if you've completed the rotation by checking the angle between the current vector and the target vector:

```
transform.forward = Vector3.SmoothDamp(transform.forward, target, ref vel, 1.0f, /*maxSpeed*/);
if(Vector3.Angle(transform.forward, target) < 1.0f) {
    // move on to next phase of rotation
}

```

Note that you would need to set up a variable to store the current velocity of the operation (`vel` in my example).
> 2 votes

# Answer
To get how much we need to rotate per ms assuming the timedelta is in ms also.

```
total_ticks = 1000 * seconds
rotation_per_tick = angle / total_ticks

```

In update we rotate until elapsed time is up

```
if (total_ticks != 0) {
    if (total_ticks > Time.deltaTime) {
        transform.Rotate(rotation_per_tick * Time.deltaTime)
        total_ticks -= Time.deltaTime
    } else {
        transform.Rotate(rotation_per_tick * total_ticks)
    }
}

```
> 1 votes

# Answer
I strongly suggest looking at Itween, which is free, and has the ability to in a single line, do a "rotate x by 180 degrees taking 2 seconds, before calling procedure y". Performance is good even for mobile.

An example might be:

```
Vector3 customRotation = new Vector3(0f,0.5f,0f);
iTween.RotateBy(myGameObject, customRotation, 2f)

```

Noting that the rotation is normalized, so 1.0f == 360 degrees.

iTween also has an alternative syntax that opens up a span of additional options for this kind of rotation, for example adding easing curves or the possibility of a callback when the routine completes.

```
Vector3 customRotation = new Vector3(0f,0.5f,0f);
iTween.RotateBy(myGameObject, iTween.Hash("Amount",customRotation,"EaseType",iTween.EaseType.EaseOutCubic,"OnComplete","RunThisMethodNext");

```
> 1 votes

---
Tags: c#, unity, rotation
---


# Question
Title: Detecting if line crosses rectangle in python. Need speed boost
I am currently writing a top down man vs robot shooter. The game works now, but if I have a decent sized level it runs slowly when you are being chased by robots. While just roaming around it can go at full 60 fps, but with the robots on your tail it slows down immensely.

I have traced the source of the problem to the part of the code where the robots decide whether or not their sight of the player is obstructed by a wall. This code works by seeing if the line segment formed by the center of the robot and the center of the player intersects a wall.

I have written this algorithm to see if a line segment goes through a rect:

```
for wall in wall_rects:

    #is wall between the robot and player:
    if man.rect.centerx < wall.rect.centerx < self.rect.centerx or\
    man.rect.centerx > wall.rect.centerx > self.rect.centerx or\
    man.rect.centery < wall.rect.centery < self.rect.centery or\
    man.rect.centery > wall.rect.centery > self.rect.centery:
        r = [] #are the corners above or below the line between the man and robot
        r.append((self.rect.centerx-man.rect.centerx)*(wall.rect.top-man.rect.centery)\
          - (self.rect.centery-man.rect.centery)*(wall.rect.left-man.rect.centerx))
        r.append((self.rect.centerx-man.rect.centerx)*(wall.rect.top-man.rect.centery)\
          - (self.rect.centery-man.rect.centery)*(wall.rect.right-man.rect.centerx))
        r.append((self.rect.centerx-man.rect.centerx)*(wall.rect.bottom-man.rect.centery)\
          - (self.rect.centery-man.rect.centery)*(wall.rect.left-man.rect.centerx))
        r.append((self.rect.centerx-man.rect.centerx)*(wall.rect.bottom-man.rect.centery)\
          - (self.rect.centery-man.rect.centery)*(wall.rect.right-man.rect.centerx))
        if not(max(r) < 0 or min(r) > 0):
            #if all of the corners are not on the same
            #side then the line does go through the wall
            break
    else: #IT SEES YOU! >:D

```

however it is not near fast enough to check all 450 some walls there are in my test level. My difficulty is either making it faster or having it find out which walls are worth checking for sight-line blockage. I tried checking the distance between the wall and robot to see if it is closer to the robot than the man, which slowed it down more.

Any suggestions?

**EDIT:**
I forgot to mention that in this game, while the walls are placed on a grid with 25X25 pixel squares, you are free to move any distance in any direction, and so are the robots, but it looks like the suggestions below will still likely help.

# Answer
> 1 votes
You can reduce the number of walls you have to check by using a spatial hash (or spatial partition). It's a data structure that answers the question, “what objects are in this region?” In your case the objects are walls. You'll only have to check the regions that the line goes through instead of all walls. A grid is one form of spatial hash but there are others too.

This article has at the end a section on intersecting a line with a spatial hash. As nihohit mentions, you can use a line drawing algorithm.

However, the next question is, are you doing this for each robot? If you are, you're going through all the walls multiple times. Since the player's location is the same each time you can use a smarter algorithm. Instead of looking at each enemy and asking whether the player is visible, ask once, which enemies are visible from the player.

The roguelike community has collected some resources about the field of view problem.

# Answer
> 0 votes
it seems you have some kind of 2d grid going there - maybe Bresenham's line algorithm will solve the problem, when run on the grid.

---
Tags: collision-detection, python, optimization, pygame, line-of-sight
---


# Question
Title: How can I orient a circle relative to the position of a 3D object?
How can I orient a circle that has a position to a 3D object? If I have a 3D object which is a hemisphere, I would like to let the circle be underneath that hemi-sphere and whenever the hemisphere moves, the circle move with the same angle and position, and underneath it.

In other words, I would like to attach a 2D circle to a hemisphere and parallel to it.

# Answer
You need to have an orientation defined for your object/entity. This is usually an unit vector in 3D, **v**=*(vx,vy,vz)*. If you have an object oriented bounding box, then you can use that to determine where the "bottom" part of your object is. If not, just consider a "safety" distance/radius from the center of your object. Say this distance is *d*. Then one can simply find where the circle's center is by using the object's center, the **v** direction and the *d* distance:

```
 CircleCenter = ObjectCenter - d * v

```

**How to draw** the circle? It might seem like a difficult task. In 2D, that's trivial: **circle(x,y,r) = (r*cos(u) +x, r*sin(u) + y)**, where *u between \[0, 360\] degs*.

In 3D you can draw it in the xOy plane, via its parametric equation: **circle(0,0,0,r) = (r*cos(u), r*sin(u), 0)**

What to do next? Rotate the circle in such a way that its local Z(up) axis points in the same direction as the **v** vector. How? Find the rotation that aligns Z with **v**:

```
 w = cross((0,0,1), v)
 circle = RodriguesRotation(w, angle(v,(0,0,1)) * (r*cos(u), r*sin(u),0) + CircleCenter

```

The RodriguesRotation is the general rotation matrix against a *w* axis by an angle *theta*. In the picture below, the black arrow is the orientation, the red circle with red orientation arrows is what your circle should look like, and the crimson line is the *d* distance offset from the object's center.
> 1 votes

---
Tags: opengl
---


# Question
Title: How to remaster a retro game's graphics?
I want to remake an old game, which graphics is pretty old (1980s game), and I want to make a "HD version" of it. Of course, the game will have an "old graphics" setting, but I want to remaster the old sprites, tiles. How can I do it? Is there any program to it, or the whole graphics should be redrawn?

# Answer
> 3 votes
There do exist some pretty impressive methods for scaling up pixel art, it's not bullet proof, but some of it could at least prove to save some time in the process of a manual retouch: http://en.wikipedia.org/wiki/Image\_scaling

Do remember, as long as you don't have a computer made from pure scifitanium none of them are going to add anything beyond what already was in the picture, up-scaled figures may seem oddly detail lacking.

---
Tags: 2d, graphics, textures, tiles, art
---


# Question
Title: How can I tweak this A* search pathfinding algorithm to handle different terrain movement values?
I'm creating a 2D map-based action game with similar interaction design as Diablo II. In other words, the player clicks around a map to move their player. I just finished player movement and am moving on to pathfinding.

In the game, enemies should charge the player's character. There are also five different terrain types that give different movement bonuses. I want the AI to take advantage of these terrain bonuses as they try to reach the player.

I was told to check out the A\* search algorithm (http://en.wikipedia.org/wiki/A\*\_search\_algorithm). I'm doing this game in HTML5 and JavaScript, and found a version in JavaScript: http://www.briangrinstead.com/blog/astar-search-algorithm-in-javascript I'm trying to figure out how to tweak it though.

Below are my ideas about what I need to change. What else do I need to worry about?

* When I create a graph, I will need to initialize the 2D array I pass in passed on with a traversal of a map that corresponds to the different terrain types.
* in graph.js: "GraphNodeType" definition needs to be modified to handle the 5 terrain types. There will be no walls.
* in astar.js: The *g* and *h* scoring will need to be modified. How should I do this?
* in astar.js: isWall() should probably be removed. My game doesn't have walls.
* in astar.js: I'm not sure what this is. I think it indicates a node that isn't valid to be processed. When would this happen, though?
* At a high level, how do I change this algorithm from "oh, is there a wall there?" to "will this terrain get me to the player faster than the terrain around me?"

Because of time, I'm also debating reusing my Bresenham algorithm for the enemies. Unfortunately, the different terrain movement bonuses won't be used by the AI, which will make the game suck. :/ I'd really like to have this in for the prototype, but I'm not a developer by trade nor am I a computer scientist. :D

If you know of any code that does what I'm looking for, please share!

Sanity check tips for this are also appreciated.

# Answer
You need to pay attention to a very specific line in the algorithm:

```
// g score is the shortest distance from start to current node, we need to check if
//   the path we have arrived at this neighbor is the shortest one we have seen yet
var gScore = currentNode.g + 1; // 1 is the distance from a node to it's neighbor

```

This is the cost of that particular node. You would want to modify it to something like

```
var gScore = currentNode.g + currentNode.cost

```

This will cause the path to avoid expensive terrain and prefer cheap terrain; it is your responsibility to make 'currentNode.cost' return something appropriate for your terrain. It is the fact that not all terrain has a cost of 1 that you are paying attention to... some terrain is cheaper than others. There are other considerations, but this specific point in the code should be the focus of your attention.
> 7 votes

# Answer
This is exactly the sort of thing A\* is for. All you need to do is assign the vertices between the nodes costs based on the terrain types. (It looks like your examples uses a graph where all vertices have a cost of 1.)
> 2 votes

# Answer
This implementation is a little specific to the on/off right now. As Myrddin Emrys says, you will need to modify the g score based on the cost (rather than just by 1). There was a discussion about this over here: https://github.com/bgrins/javascript-astar/issues/3.

I'd love to get this solution ported back to the main library if you get it working!
> 0 votes

---
Tags: javascript, ai, html5
---


# Question
Title: What are the tessellation factors Direct3D11?
I don't quite understand the documentation but if I was to tessellate a mesh using 3 control points in Direct3D11 with the "tri" domain am I right in thinking that

SV\_TessFactor is how many times to split up each edge

and

SV\_InsideTessFactor is how many points inside the triangle to create?

# Answer
> 1 votes
Yes, that's approximately what it does. I'm not sure if these values are the *exact* vertex counts to create, but at least, higher tess factors lead to higher vertex counts. The reason there are separate factors for each edge is so you can match edges from one patch to the next, to avoid cracking.

Here is a video showing the tess factors being smoothly increased on a cube. You can see the effect of fractional tess factors in this video too (how the mesh smoothly and continuously changes from one tess level to the next, rather than popping). It does not show separate edge vs inside tess factors, though.

---
Tags: directx11, tessellation
---


# Question
Title: Help understand GLSL directional light on iOS (left handed coord system)
I now have changed from GLKBaseEffect to a own shader implementation. I have a shader management, which compiles and applies a shader to the right time and does some shader setup like lights. Please have a look at my vertex shader code. Now, light direction should be provided in eye space, but I think there is something I don't get right.

After I setup my view with camera I save a lightMatrix to transform the light from global space to eye space.

My modelview and projection setup:

```
- (void)setupViewWithWidth:(int)width height:(int)height camera:(N3DCamera *)aCamera {

    aCamera.aspect = (float)width / (float)height;
    float aspect = aCamera.aspect;
    float far = aCamera.far;
    float near = aCamera.near;
    float vFOV = aCamera.fieldOfView;

    float top = near * tanf(M_PI * vFOV / 360.0f);
    float bottom = -top;
    float right = aspect * top;
    float left = -right;

    // projection
    GLKMatrixStackLoadMatrix4(projectionStack, GLKMatrix4MakeFrustum(left, right, bottom, top, near, far));

    // identity modelview
    GLKMatrixStackLoadMatrix4(modelviewStack, GLKMatrix4Identity);

    // switch to left handed coord system (forward = z+)
    GLKMatrixStackMultiplyMatrix4(modelviewStack, GLKMatrix4MakeScale(1, 1, -1));

    // transform camera
    GLKMatrixStackMultiplyMatrix4(modelviewStack, GLKMatrix4MakeWithMatrix3(GLKMatrix3Transpose(aCamera.orientation)));
    GLKMatrixStackTranslate(modelviewStack, -aCamera.position.x, -aCamera.position.y, -aCamera.position.z);
}

- (GLKMatrix4)modelviewMatrix {
    return GLKMatrixStackGetMatrix4(modelviewStack);
}

- (GLKMatrix4)projectionMatrix {
    return GLKMatrixStackGetMatrix4(projectionStack);
}

- (GLKMatrix4)modelviewProjectionMatrix {
    return GLKMatrix4Multiply([self projectionMatrix], [self modelviewMatrix]);
}

- (GLKMatrix3)normalMatrix {
    return GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3([self modelviewProjectionMatrix]), NULL);
}

```

After that, I save the lightMatrix like this:

```
[self.renderer setupViewWithWidth:view.drawableWidth height:view.drawableHeight camera:self.camera];
self.lightMatrix = [self.renderer modelviewProjectionMatrix];

```

And just before I render a 3d entity of the scene graph, I setup the light config for its shader with the lightMatrix like this:

```
- (N3DLight)transformedLight:(N3DLight)light transformation:(GLKMatrix4)matrix {
    N3DLight transformedLight = N3DLightMakeDisabled();
    if (N3DLightIsDirectional(light)) {
        GLKVector3 direction = GLKVector3MakeWithArray(GLKMatrix4MultiplyVector4(matrix, light.position).v);
        direction = GLKVector3Negate(direction);    // HACK -> TODO: get lightMatrix right!
        transformedLight = N3DLightMakeDirectional(direction, light.diffuse, light.specular);
    } else {
        ...
    }
    return transformedLight;
}

```

You see the line, where I **negate** the direction!? I can't explain why I need to do that, but if I do, the lights are correct as far as I can tell.

**Please help me, to get rid of the hack.**

I'am scared that this has something to do, with my switch to left handed coord system.

My vertex shader looks like this:

```
attribute highp     vec4    inPosition;
attribute lowp      vec4    inNormal;
...

uniform highp   mat4    MVP;
uniform highp   mat4    MV;
uniform lowp    mat3    N;

uniform lowp    vec4    constantColor;
uniform lowp    vec4    ambient;
uniform lowp    vec4    light0Position;
uniform lowp    vec4    light0Diffuse;
uniform lowp    vec4    light0Specular;

varying lowp    vec4    vColor;
varying lowp    vec3    vTexCoord0;

vec4 calcDirectional(vec3 dir, vec4 diffuse, vec4 specular, vec3 normal) {
    float NdotL = max(dot(normal, dir), 0.0);
    return NdotL * diffuse;
}

...

vec4 calcLight(vec4 pos, vec4 diffuse, vec4 specular, vec3 normal) {
    if (pos.w == 0.0) {             // Directional Light
        return calcDirectional(normalize(pos.xyz), diffuse, specular, normal);
    } else {
        ...
    }
}

void main(void) {

    // position
    highp vec4 position = MVP * inPosition;
    gl_Position = position;

    // normal
    lowp vec3 normal = inNormal.xyz / inNormal.w;
    normal = N * normal;
    normal = normalize(normal);

    // colors
    vColor = constantColor * ambient;

    // add lights
    vColor += calcLight(light0Position, light0Diffuse, light0Specular, normal);

    ...
}

```

# Answer
> 1 votes
I found the answer by myself. My engine represents the light direction, as the direction from the light source to the target surface. **BUT**, the shader needs the direction towards the light source and hence I have to negate the direction vector before passing to the shader.

---
Tags: shaders, glsl, lighting, gpu
---


title: Intersect of vector and triangle side

text:
# Question
Title: Intersect of vector and triangle side
I'm trying to create a triangular touch surface for iOS where the user can drag around a point inside this triangle. Using information from this page, it is easy to figure out if the dragged point is inside or outside the triangle. However, I want to clip the point to the triangle edges if the user drags outside the triangle.

This is easy for side **AB** and side **AC**, because I just have to set vectors u or v to zero respectively if the user's finger drags outside of these edges. However, I'm not sure how to find point p, on side BC. I need to find this point of intersection if the user drags their finger outside of edge **BC**.

# Answer
All points on edge BC have the property that |u| + |v| = 1. Reducing the magnitude of the longer vector so that this property is true will get you your intersection point. In your picture this would mean reducing the magnitude of v by 0.245764829343853. This only works if your line from A to the finger crosses BC.
> 2 votes

# Answer
Assuming you have coordinates for A, B, and C (which we'll call Ax, Ay, etc.), and D=u+v, the intersection point is:

```
X = ((Bx - Cx) (Ax * Dy - Ay * Dx) - (Bx * Cy - By * Cx) (Ax - Dx))/((By - Cy) (Ax - Dx) - (Bx - Cx) (Ay - Dy))

Y = ((By - Cy) (Ax * Dy - Ay * Dx) - (Bx * Cy - By * Cx) (Ay - Dy))/((By - Cy) (Ax - Dx) - (Bx - Cx) (Ay - Dy))

```

See also Wikipedia's article on Line-line intersection.
> 1 votes

---
Tags: geometry
---


# Question
Title: How do I efficiently manage the pixels, on the screen?
I've been looking for a way to efficiently manage the pixels on a screen, but so far all I've found is along the lines of `SetPixel()`, in Windows, and drawing a rectangle 1px by 1px, in OpenGL. Both of these methods seem to be too slow, since I'm looking for a way to constantly update the pixels on the screen at at least 30 FPS.

I need a way to do this, so I can make a non-polygon based graphics engine. I'm sure this is possible, since OpenGL and DirectX can do it, but I have a suspicion I'm going to need direct access to the video memory. I just need some direction to work in, since I'm not really sure where to start. This is primarily to see if I can do it, since it seems like a good challenge.

How do I efficiently manage the pixels, on the screen?

# Answer
> 3 votes
What you're running into is that the overhead of calling a Windows API function (SetPixel) for every pixel is huge. Assuming you don't want to use hardware graphics capabilities at all (entirely-software renderer), what you really need to do is compose the frame yourself in your own buffer in application memory - which is really fast since there's no API sitting between you and the memory - and then pass that buffer off to the operating system to display, once per frame.

There's probably no need for OpenGL/DirectX here, as you can likely do it fast enough with the Windows GDI, using SetDIBitsToDevice (which blits pixel data in memory directly to a GDI device context).

Another option is to use SDL, a library that handles all the details of shipping the frame buffer off to the operating system for you. It can use GDI or DirectX on Windows, and supports other platforms as well. It also helps sort out sound, input, etc. so you may find it well worth using.

# Answer
> 1 votes
What you want to do is have a dynamic texture in the graphics card that you update very frame, then draw to the screen. Something like:

1. Declare the texture, using appropriate hints to tell the graphics driver it's dynamic (i.e. `D3DUSAGE_DYNAMIC` or `D3D11_USAGE_DYNAMIC`).
2. Manipulate your pixels using a data buffer stored in RAM.
3. When it's time to render, copy the buffer data from RAM into your texture.
4. Draw a rectangle that covers the entire screen with your texture.

There are optimizations for this--I'm pretty sure there's a way to get around copying the ENTIRE texture every time you change a pixel--but this'll get you started. If you aren't doing anything else with graphics card, this will be fine for performance.

edit: Misunderstood the question. Obviously you'd need to copy data to and from the back buffer every frame, which is obviously inefficient. You might be able to get ~30fps out of it though.

# Answer
> 0 votes
(I encourage others with more historical knowledge to correct anything that may be inaccurate herein.)

The sad truth is you are not going to get the acceleration you want (not under Windows, anyway) without modern, massively parallel GPU technology (in the form of pixel shaders specifically). The last high speed frame-buffer rendering under Microsoft OSes, prior to the advent of consumer-level GPUs, was seen with the demise of the VGA high performance modes such as Mode X and Mode 13h under DOS, modes which allowed the rapid rendering of all high-end PC games in the early-to-mid 90's (Doom, Magic Carpet, Dungeon Keeper, the C&C games and so on ad nauseum). It was the innovative memory-access models in these modes that benefited non-parallelised performance; the low resolutions and consequently comparatively low iteration also certainly contributed (as compared with today high resolutions and highly parallelised GPUs developed to deal with this). Because these modes are no longer supported under Windows, you simply won't get the same sort of performance in the same way as those old games did.

There are some high performance (and not exactly cheap) solutions such as Pixomatic, which may interest you. I am not sure how they are constructed, given that eg. Pixomatic runs under Windows, but I can guarantee you they are highly specialist solutions that are built using extensive knowledge of old school VGA rendering, and more generally the subtle ins and outs of x86 architecture.

In conclusion -- You really should be writing a special-purpose pixel shader, unless is there some very good reason not to do so.

---
Tags: graphics, pixel
---


title: Staggered Isometric Map In Javascript

text:
# Question
Title: Staggered Isometric Map In Javascript
I'm trying to create a staggered isometric map in Javascript.

```
    var x, y, row, column, top, left,
        width = window.innerWidth, height = window.innerHeight,
        tile = {width: 64, height: 32};

    row = Math.ceil(width / tile.width); // how many rows will be in map
    column = Math.ceil(height / tile.height); // how many columns will be in map

    for (x=0 ; x<row ; x++){
        for (y=0 ; y<column ; y++){
            top = y * tile.height - (y % 2 == 0 ? 0 : tile.height / 2);
            left = x * tile.width - (y % 2 == 0 ? 0 : tile.width / 2);

            $('<div />').addClass('tile').css({
                width: tile.width,
                height: tile.height,
                top: top,
                left: left
            }).appendTo('body');
        }
    }

```

My formula doesn't work for vertical axis. It creates something like this. http://postimage.org/image/ekfnlbgoh/

How can I make it work? I need it to be something like this. http://legendofmazzeroth.wikidot.com/staggered-isometric-maps

---

Here is the latest code:

```
    row = Math.ceil(height / (tile.height / 2));
    column = Math.ceil(width / tile.width);

    for (y=0 ; y<=row ; y++){
        for (x=0 ; x<=column ; x++){
            top = y * (tile.height / 2) - (tile.height / 2);
            left = x * tile.width - (y % 2 == 0 ? 0 : tile.width / 2) - (tile.height / 2);

            $('<div />').addClass('tile').css({
                width: tile.width,
                height: tile.height,
                top: top,
                left: left
            }).appendTo('body');
        }
    }

```

By the way, thanks to you that column/row mistake has been fixed.

# Answer
> 6 votes
First, You've got your rows and columns backwards:

```
row = Math.ceil(height / tile.height); //number of rows
column = Math.ceil(width / tile.width); //number of columns

```

Then, there's a couple different ways to cycle through the tiles, depending on how you want the spaces to be indexed (if this is merely for background purposes, then it's not that important, but possibly if you need to keep track of where on the board all the other game entities are).

The closest way to what you're doing would be to always have the left variable be offset by 1/2 the width, then alternate the top offset based on the modulus (and watch those x/y values that were turned around because of the row/columns being backwards):

```
for (y=0 ; y<row ; y++){
    for (x=0 ; x<column ; x++){
        left = x * tile.width - tile.width / 2;
        top = y * tile.height - (y % 2 == 0 ? 0 : tile.height / 2);

        $('<div />').addClass('tile').css({
            width: tile.width,
            height: tile.height,
            top: top,
            left: left
        }).appendTo('body');
    }
}

```

Hope that helps.

---
Tags: javascript, html5, isometric, tilemap
---


# Question
Title: Why am I seeing elapsed game time differ from total game time in XNA?
I was trying three different ways of using `ElapsedGameTime` and `TotalGameTime`, because I want an exact match, so everything is updated/drawn accordingly.

As I was experimenting, I learned that the very first update, `ElapsedGameTime` and `TotalGameTime` are both 0.

Second update, `ElapsedGameTime` is 0.0166667, which is correct (60 updates per second). But `TotalGameTime` is 0, I don't understand why.

So, if I start to add from the **third** update (`time += gameTime.ElapsedTime`), `ElapsedGameTime` is equal to `TotalGameTime`, otherwise there will be always a 0.0166667 difference.

Can someone explain that to me?

**UPDATED: code**

```
    using System;
using System.Collections.Generic;
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 System.Diagnostics;

namespace TestTime
{
    class TimeTest2
    {
        TimeSpan totalTimeElapsed;
        TimeSpan frequency = TimeSpan.FromSeconds(5.5f);

        int times = 0;
        int timesCheckpoint = 1;

        public void load()
        {

        }

        public void initialize()
        {
            totalTimeElapsed = TimeSpan.Zero;
        }

        public void update(GameTime gameTime)
        {
            times++;
            String debug = "";
            TimeSpan zero = TimeSpan.Zero;

            if( times > 2 )
            {
                totalTimeElapsed += gameTime.ElapsedGameTime;
            }

            if( totalTimeElapsed != gameTime.TotalGameTime )
            {
                debug += " Diff time:"+times+" ["+totalTimeElapsed.ToString() + " != " + gameTime.TotalGameTime.ToString() + "]";
            }

            TimeSpan checkpoint = TimeSpan.FromSeconds(5.5f*timesCheckpoint);
            if( gameTime.TotalGameTime >= checkpoint )
            {
                debug += "5.5f MARK ";
                timesCheckpoint++;
            }

            if( !debug.Equals("") )
            {
                addDebug(debug + "  -" + gameTime.TotalGameTime.ToString());
                addDebug("");
            }
        }

        public void draw()
        {

        }

        public void addDebug(string str)
        {
            Debug.WriteLine(str);
        }
    }
}

```

# Answer
Looks like a little bug, or a precisely correct behaviour, from which point you want to look at it. See, the `Update` method is called **twice** before first call to `Draw`, first time being outside of a main game loop.

`TotalGameTime` is updated in the moment between end of the `Update` and beginning of the `Draw`, *inside the game loop*. `ElapsedGameTime` on the other hand is updated after start of the main loop and before `Update`. Both of them are initialized to `0` before call to the first `Update`.

If you read the description of a `ElapsedGameTime` is says:

> The amount of elapsed game time **since the last update**.

At the first frame *inside the game loop* it is a *second* `Update` call. So `ElapsedGameTime` shows time elapsed since first `Update` call.

OTOH, `TotalGameTime` says:

> The amount of game time **since the start of the game**.

This is a more vague, but it looks like game can't be considered started, until it entered a main loop and begins drawing itself. Thus `TotalGameTime` updates itself first time after *second* call to `Update`. Hence the difference you observe.
> 7 votes

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


title: Random Vector within a cone

text:
# Question
Title: Random Vector within a cone
I'm looking to create a random vector within a cone given the radius (base).

It feels like I've been traversing through many pages on the internet and still I'm no further forward to getting an answer.

I was thinking I could get a point within the base of the cone and have it point towards the apex (then just use the inverse of that for my animation) but this seems like an incredibly long winded approach.

# Answer
Given the discussion in the comments, this comes down to finding a random point on a circle. For instance, if we find a point (x,y) at random within a circle of radius 1, then the vector (.05\*x, .05\*y, 1) will be a roughly-random vector within the cone of angle arctan(.05) (or approximately 2.9 degrees) about the z axis.

There are several different methods of finding a random point on a sphere, but the most straightforward by far is what's known as the *rejection method* : find a point at random within the square of radius 1 and then reject it (that is, find another random point) if that point is outside the unit circle. Assuming that rand() returns a random number between 0 and 1.0, then the pseudocode for doing this would look something like:

```
do {
  x = 2.0*rand()-1.0;
  y = 2.0*rand()-1.0;
} while ( x*x+y*y > 1.0 );
// (x,y) is now randomly distributed within the unit circle

```

Since the area of the square is 4 and the area of the circle is π, the probability that the point will be inside the circle is π/4 and the average number of times you'll execute the do loop is 4/π, or approximately 1.27 times for each random point within the circle; there's a less than 1% chance that you'll need more than 3 iterations of the loop to find a point within the circle. This uniform point in the circle can then be translated into a nearly-uniform vector in a spread about the z-axis by means of the method I listed above; in particular, if the maximum angle from the z axis is theta (so the cone's width is 2\*theta), then pseudocode for using the random point would look something like:

```
r = tan(theta);
Vector v(r*x, r*y, 1);
v.Normalize();

```

Note that this won't give a precisely uniform *angular* spread, because the surface of a sphere isn't flat - points near the center of the cone will be generated slightly less often than they 'should' be, compared to points at the fringes. But for small angles theta this gives a pretty good approximation, and it should certainly be good enough for most random-animation purposes.
> 8 votes

# Answer
I solved this by calculating the vector in spherical coordinates, converting back into cartesian and then hitting it with a rotation matrix to get it aligned with the direction of the emitter. Essentially this:

```
theta = random(0, emission_angle);
phi = random(0, 2*pi);

vec3 temp(cos(phi)*sin(theta), sin(phi)*sin(theta), cos(theta));

return to_world_space_mat3 * temp;

```

This works for all emission angles up to 180 degrees which is nice for spherical emitters and the like, and (from sight only, not sure about mathematically) seems to be fairly well distributed.
> 2 votes

# Answer
Coincidentally I had to do the very same thing not that long ago :)

Here's the solution I came up with, assuming you have the cone angle, and the unit vector describing which direction it's facing.

* First, generate a random unit vector.
* Project this vector onto the 'plane' with the cone's direction vector as a normal. I put plane in quotes because to truly define a plane, you also need a point. However, this works for the purposes of this method. The formula, by the way, is:

`projectedVector = randomVector - (coneDirection*(dot(coneDirection,randomVector));`
* This vector is now perpedicular to the cone's direction, and can be taken as an axis around which to rotate the cone.
* Generate a random angle, `theta`, between 0 and the cone's maximum angle.
* Set up a rotation matrix for `theta` degrees around the axis `projectedVector`.
* Rotate the cone's direction using that matrix.

I would like to note that I don't know if this yields uniform distribution randomness, but it worked well for me.
> 1 votes

---
Tags: c++, mathematics
---


title: How do I make the viewport move?

text:
# Question
Title: How do I make the viewport move?
I'm working with a game in C# XNA and I want to draw a texture and a position in the middle of the screen. The thing is that I want the viewport to move around and not the player. So for example: If I push right I want the viewport to move right and keep the player in the middle of the screen.

Since `GraphicsDevice.Viewport.X` and `Y` are not variables, I have no idea how to do this.

# Answer
the best way would be to integrate a camera class there are many tutorials for that

i assume you will be using it for a 2d game...so :

http://adambruenderman.wordpress.com/2011/04/05/create-a-2d-camera-in-xna-gs-4-0/

http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation
> 3 votes

# Answer
Now I know how to do it :)

In `SpriteBatch.Begin()` you type:

```
spriteBatch.Begin(SpriteSortMode.Texture,
    null,null,null,null,null,
    Matrix.CreateTranslation(X,Y,0));

```

Since it is a 2D game I'm working on the Z axis is 0.

X and Y are where you want your camera to be, so for my example I can type:

```
Player_position.X - drawOffSet
Player_position.Y - drawOffSet

```

But thanks for the help anyway
> 2 votes

# Answer
if you want to move your viewport you only have to do:

```
GraphicsDevice.Viewport = new Viewport(X,Y,WIDTH, HEIGHT);

```

but I'm not sure that it is what you need... usually is used to work with a camera, so the viewport is fixed and you change the camera... like if you were watching tv...

the tv, (your viewport), is fixed..., but the camera is what you moves to show other parts of the film's world.
> 1 votes

# Answer
I haven't worked with xna in a while now, but aren't you supposed to update the camera coordinates and update the viewport with the camera?
> -2 votes

---
Tags: xna, graphics
---


# Question
Title: Is there a way to use the facebook sdk with libgdx?
I have tried to use the facebook sdk in libgdx with callbacks, but it never enters the authetication listeners, so the user never is logged in, it permits the authorization for the facebook app but it never implements the authentication interfaces :(

Is there a way to use it?

```
public MyFbClass()
{
    facebook = new Facebook(APPID);
    mAsyncRunner = new AsyncFacebookRunner(facebook);
    SessionStore.restore(facebook, this);

    FB.init(this, 0, facebook, this.permissions);
}

///Method for init the permissions and my listener for authetication
public void init(final Activity activity, final Facebook fb,final String[] permissions)
    {
        mActivity = activity;
            this.fb = fb;
        mPermissions = permissions;
        mHandler = new Handler();
        async = new AsyncFacebookRunner(mFb);

        params = new Bundle();

        SessionEvents.addAuthListener(auth);

    }

///I call the authetication process, I call it with a callback from libgdx
public void facebookAction()
    {
        // TODO Auto-generated method stub
        fb.authenticate();
    }

///It only allow the app permission, it doesnt register the events
public void authenticate()
    {
        if (mFb.isSessionValid())
        {
            SessionEvents.onLogoutBegin();
            AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFb);
            asyncRunner.logout(getContext(), new LogoutRequestListener());
            //SessionStore.save(this.mFb, getContext());
        }
        else
        {
            mFb.authorize(mActivity, mPermissions,0 , new DialogListener());

        }
    }

public class SessionListener implements AuthListener, LogoutListener
    {

        @Override
        public void onAuthSucceed()
        {
            SessionStore.save(mFb, getContext());
        }

        @Override
        public void onAuthFail(String error) {
        }

        @Override
        public void onLogoutBegin() {
        }

        @Override
        public void onLogoutFinish() {
            SessionStore.clear(getContext());
        }
    }

DialogListener() {

            @Override
            public void onComplete(Bundle values)
            {
                SessionEvents.onLoginSuccess();
            }

            @Override
            public void onFacebookError(FacebookError error)
            {
                SessionEvents.onLoginError(error.getMessage());
            }

            @Override
            public void onError(DialogError error)
            {
                SessionEvents.onLoginError(error.getMessage());
            }

            @Override
            public void onCancel()
            {
                SessionEvents.onLoginError("Action Canceled");
            }
}

```

# Answer
It might not be you. Facebook connect was down worldwide for a couple hours around the time of your post. See http://news.ycombinator.com/item?id=3866353 (or http://developers.facebook.com/bugs/367587563282522)
> 2 votes

---
Tags: libgdx, facebook
---


title: Save game state information

text:
# Question
Title: Save game state information
I'm working on my first game, and are looking into the option to save a number of game state settings.

One of the things I want to save is the high scores, this will contain a list of the 10 players that scored the highest.

I have been looking into this for a while, and was wondering what the best way for this is.

While being ingame I will have a list of high scores comprised of Player, Score, Level. This of course needs to be updated each time the score has been beaten, but it also needs to be saved somewhere where it won't be reset the whole time.

I would think this kind of information should be saved into a file (either xml or comma separated values).

The problem I'm facing is what to do on the initial set up (I would like to have some fake values in the high scores table), however if I add that to the file how do I know that the scores in there are the initial set up ones, or the real ones? Once the player has a endgame for the first time, these fake scores should not being shown anymore.

However the player can also reset the scores, and at that point I would like to have the fake scores shown again.

So my question is what is the best way of setting this up? Do I keep 2 files, one with the real scores, other with fake ones? or do I keep the fake ones in a list inside the game and when the file with high scores can't be found I use that list?

# Answer
> 2 votes
Usual logic for such situations is some thing like (pseudocode):

```
// at game init
if(file_not_found)
  scores_list = create_default()
else
  scores_list = load_from_file()

// use scores in the game

// at shutdown
save_scores_file()

```

where `create_default()` will create initial scores file. It can be empty, zero\_scored or some predefined fake scores, whatever.

---
Tags: xna, leaderboards
---


# Question
Title: Why is it that there are invalid "dt" values in physics simulations?
I'm utilising some of NeHe's spring code, and after getting some pretty weird results I eventually realised the source of my error - my "dt" value in my Update function; the value that everything is multiplied against to speed up/slow down the calculations, hopefully based on frame rate. For example:

```
public void Update(GameTime gt) {
   float dt = gt.ElapsedGameTime.Milliseconds / 160.0f;
   velocity += (force / mass) * dt;
   position += velocity * dt;
}

```

160.0f seems to work pretty well for the player's update function, but for my spring simulation I need a value of about 3000, or I end up with my springs located at (NaN,NaN) pretty much instantly.

Why do bad values for this cause everything to go so crazy? I thought it would just slow down or speed up my simulation but it seems to cause some weird cascading failure.

Edit: Sorry, forgot to link to NeHe's post on this: http://nehe.gamedev.net/tutorial/introduction\_to\_physical\_simulations/18005/

# Answer
> 3 votes
When you do `position += velocity * dt` you use the new value of `velocity` while a more accurate calculation should be using the **average** value for the whole elapsed frame duration. See this article I wrote about how this affects trajectory computation.

In your specific case, if `force` is a constant, using Verlet integration will give you the exact trajectory whatever the framerate. If Verlet integration is still not enough, because for instance you introduce friction, you can use a higher order integration method such as 4th order Runge-Kutta.

# Answer
> 1 votes
Well, that's Explicit Euler Integration, the easiest and dumbest integrator ever. It's prone to explode your simulation if Dt is either variable or large. What you could do is to switch to another one:

Verlet/Velocity Verlet

Midpoint Euler http://en.wikipedia.org/wiki/Semi-implicit\_Euler\_method

Implicit Euler http://www.physics.udel.edu/~jim/Ordinary%20Differential%20Equations/The%20Implicit%20Euler%20Method.pdf

Predictor Corrector methods

Runge Kutta.

Why use them (another gamedev post) These are a bit better, but not as easy to implement. You also might want to look at adaptive timestep methods.. which are quite related to your problem (e.g. variable frame-rate might induce jittery simulations).

# Answer
> 1 votes
I think you are using `gt.ElapsedGameTime.Milliseconds` then you should be using `gt.ElapsedGameTime.TotalMilliseconds`. Not sure if that have some influence here, but it's a potential bug.

To increase precision (if that is the problem) you could switch to ElapsedGameTime.Ticks which is 100-ns intervals, and to double for fp intermediate calculations and see if it helps.

# Answer
> 0 votes
I believe that your timestep should be calulcated as:

```
float dt = gt.ElapsedGameTime.Milliseconds / 1000.0f;

```

Since you want dt to be the delta time in seconds (so a dt of 1.0 would mean that 1 second passed).

If that doesn't work, then it's likely that the timer you are using to calculate ElapsedGameTime isn't accurate enough (a common problem with millisecond timers on Windows, which has a resolution of 16ms).

If the value of gt.ElapsedGameTime.Milliseconds is constantly 0 or 16 then you need a more precise timer.

---
Tags: xna, physics
---


# Question
Title: Camera Rotation (for mouse look) with LookAt does not work as expected (Local/Global)
My code for rotating my 3D fps camera isn't working as expected.
I expect that the X-axis does rotate with the Y-axis, but it ain't so.

I made some pictures to explain it better, I think its doing global rotation instead of local rotation.
But I searched in the internet and used code for local rotation and it was still the same result.

Image

1. Normal Position
2. Rotated on Y-Axis
3. Rotated on X-Axis (how it is)
4. Rotated on X-Axis (how it should be)

And this is my rotating code: X-Axis

```
float sx = sinf(x);
float cx = cosf(x);

up.y = up.y*cx - up.z*sx;
up.z = up.y*sx + up.z*cx;

center.y = center.y*cx - center.z*sx;
center.z = center.y*sx + center.z*cx;

```

Y-Axis

```
Math::Vector3f f = Normalise(center - eye);

float sy = sinf(y);
float cy = cosf(y);

center.z = eye.z + f.z*cy - f.x*sy;
center.x = eye.x + f.z*sy + f.x*cy;

```

It doesn't matter with which order I rotate, still the same.

# Answer
> 0 votes
Hmm, when you update a point, e.g. your center, you destroy the information! Here's a snippet to illustrate my point:

```
 NewCenter.y = center.y * cx - center.z * sx;
 NewCenter.z = center.y * sx + center.z * cx;
 center = NewCenter;

```

The problem is that in your first snippet, the `center.y` component got "dirty" before it could be used in your `center.z` computation. It's simple matrix-vector multiplication.

**UPDATE**

If one wishes to devise a transformation chain in which the x axis moves together with the y axis, then this is achievable through the following set of transformations:

If the point to be transformed is *(x,y,z)*, then it has to undergo a series of frame transformations: from *F2* to *F1* you have a rotation against the x by an angle *alpha*, then from *F1* to *F0* = world system, you have a rotation against the y axis by an angle *beta*. Chaining the transforms together, you should get the final position of your point in the world system.

You can see it as a double rotation joint system, the camera being attached to the x axis, which is in term attached to the y joint.

---
Tags: c++, opengl, mathematics, camera, rotation
---


title: Rotating points on a circle

text:
# Question
Title: Rotating points on a circle
I have drawn a 2D circle in X,Y,Z. I wanted to draw something on specific vertices of that circle and I managed to do it. When I wanted to move the circle, I wanted the vertices to get the updated position, so I created another array of vertices and calculated the new vertex positions.

Now I want to rotate the circle, and while rotating it, the vertices should get the new orientation. How can I do this?

```
void creature::drawCircle(Vec3f Pos,float radius, int segments )
{

    // automatically determine the number of segments from the circumference
    if( segments <= 0 ) {
        segments = (int)math<double>::floor( radius * M_PI * 2 );
    }
    if( segments < 2 ) segments = 2;

    GLfloat *verts = new float[(segments+2)*3];
    GLfloat *vertsNew = new float[(segments+2)*3];
    verts[0] = 0;
    verts[1] = 0;
    verts[2] = 0;
    vertsNew[0] = 0;
    vertsNew[1] = 0;
    vertsNew[2] = 0;

    //Create circle
    for( int s = 0; s <= segments; s++ ) {
        float t = s / (float)segments * 2.0f * 3.14159f;
        verts[(s+1)*3+0] = math<float>::cos( t ) * radius;
        verts[(s+1)*3+1] = math<float>::sin( t ) * radius;
        verts[(s+1)*3+2] = 0;
    }

    //Transform points
    for( int s = 0; s <= segments; s++ ) {
    ci::Vec3f  m_newCirclePos;
        m_newCirclePos.x = verts[(s+1)*3+0];
        m_newCirclePos.y = verts[(s+1)*3+1];
        m_newCirclePos.z = verts[(s+1)*3+2];
        m_newCirclePos += ci::Vec3f(Pos);

        vertsNew[(s+1)*3+0] = m_newCirclePos.x;
        vertsNew[(s+1)*3+1] = m_newCirclePos.y;
        vertsNew[(s+1)*3+2] = 0;

    }

    // Attach tentacles on specific vertices
    for (int i=0; i<m_tentacle.size(); i++)
    {
        m_tentacle[i]->m_Nodes[0].x = vertsNew[(i+1)*3+0];
        m_tentacle[i]->m_Nodes[0].y = vertsNew[(i+1)*3+1];
        m_tentacle[i]->m_Nodes[0].z = vertsNew[(i+1)*3+2];
        m_tentacle[i]->enforceConstraints(Vec2f(0,0),0,0,0,0);
    }
    glPointSize(10);
    glEnableClientState( GL_VERTEX_ARRAY );
    glVertexPointer( 3, GL_FLOAT, 0, vertsNew );
    glDrawArrays( GL_POINTS, 0, segments + 2 );
    glDisableClientState( GL_VERTEX_ARRAY );
    delete [] verts;
    delete [] vertsNew;
}

```

# Answer
To do this you should be using a scene graph. Basically, the objects you want to attach to the circle can be seen as child objects and should therefore inherit their position and orientation from their parent, the circle.

Also, you should really be putting the circle into a vertex buffer and leaving it there. You shouldn't reconstruct the vertex buffer every time you want to draw it, just transform the existing one using a transformation matrix.
> 5 votes

---
Tags: c++, opengl, 3d, mathematics
---


# Question
Title: XNA ContentManager.Load causes string allocation
I was running the Visual Studio memory profiler on a project and noticed that an enormous amount of strings were being instantiated. It turns out that `ContentManager.Load` appears to create a new string instance each time it's called. This might not be a big deal on a PC, but on other platforms like the Xbox, it quickly forces a garbage collection.

Maybe I'm just a bit naive, but I assumed that `ContentManager` would manage my game content, given the name and all. This led to calling the Load method every time I needed a texture (like during `Draw`), but it seems like this approach apparently can't work since the `Load` method will allocate strings, even if it's not allocating extra memory for already-loaded textures.

Is there a good solution to this? The obvious answer seems to be to maintain my own references to the textures and not call `Load` if they've already been loaded...but that seems like precisely what the `ContentManager` should be doing.

# Answer
Your solution to the problem is correct - hold your own references.

In my games I take it a step further with `class Asset<T>`. Basically:

* The `Asset<T>` type can exist in a not-yet-loaded state (a public field).
    + `Asset<T>` has some helper methods that make skipping unloaded assets easier.
* `Asset<T>` objects are allocated by a class that implements `AssetManager<T>` (one implementation for each content type I care about). `AssetManager<T>` doesn't care about whether or not it's re-allocating duplicates. It is thread-safe.
* `AssetManager` keeps track of already allocated objects and delegates calls to the various `AssetManager<T>` implementations. It is thread-safe. It is a `static` class (*yeah, yeah, I know it shouldn't be*).
* When the `GraphicsDevice` is ready I spin up a secondary thread that goes and loads content from `Asset<T>` objects that are not yet loaded (basically just pop off a queue and load).
* The `AssetManager` has a `DoneLoading` property that checks if the load queue is empty.
* One implementation even had asset groups. This was used to e.g. keep universal assets in memory between levels.

The raw interface of these types would be:

```
public class Asset : IDisposable
{
  internal void Load(ContentManager mgr); // Call loader and assign it to Asset then set IsLoaded to true.
}

public class Asset<T> : Asset
{
  public string Name { get; } // Optional, I took it out for release builds.
  public T Asset { get; } // Throws exception if not loaded.
  public bool IsLoaded { get; }

  public Asset(Func<ContentManager, T> loader); // Store loader in a private field.
  public bool Use(Action<T> usage)
  {
    if (IsLoaded) { usage(Asset); return true; }
    return false;
  }
  /* E.g.
    foo.Use(tex =>
    {
      spriteBatch.Draw(tex, ...);
    });
  */
}

public class AssetManager<T>
{
  public Asset<T> Allocate(string name);
}

public static class AssetManager
{
  public static bool DoneLoading { get { return _notYetLoaded.Count == 0; } }
  private static Queue<Asset> _notYetLoaded;
  public static Asset<T> Get<T>(string name);
}

```

Advantages of this system:

* You can ask for content before the `GraphicsDevice` is ready and they will be loaded when it is.
* Load screens 'know' when to progress onto the game by simply checking the `DoneLoading` property on the `AssetManager`.
* `ContentManager` is only asked for resources once - you won't get the string allocation problem.
* You can animate your load screens.
* By using `Asset<T>.Use` correctly assets would automagically appear in your game at runtime (e.g. if they are loaded inside the actual game state).

With this system I saw no significant problems with grabbing assets when graphical objects were constructed (and storing them in fields), but grabbing them each frame is just wasteful and lazy.

Also be careful about your ordering when it comes to adding and loading assets. You should always add the assets to the dictionary before they are loaded - this fixes cyclic dependency problems.
> 9 votes

# Answer
ContentManager is for **loading** content, not keeping a reference to it\*. Your "solution" as you call it is actually the way it **should** be done.

A good rule of thumb is *only call `ContentManager.Load<T>()` when you **need** to load the content into memory*. Once it is there keep your own reference to it.

Oh, and don't forget to call `ContentManager.Unload()` when you are done with everything in that scene.

Yes, internally it will do that, that is more for shared resources than anything else
> 4 votes

---
Tags: xna, c#, xna-content-pipeline
---


# Question
Title: How do I implement a racing clock that shows elapsed time?
I'm wanting to make a old school timer like the picture below. How would I go about doing this in VD? I have tried it doing it with code bellow. The problem with this is that it starts with just seconds only adds the minutes section when you reach 1 minute.

```
Dim StartTime As DateTime
Dim PlayTime As TimeSpan

 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    StartTime = Now()
    End Sub

  Private Sub tmrCountUp_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrCountUp.Tick

    PlayTime = Now() - StartTime

    lblTime.Text = PlayTime.Hours & PlayTime.Minutes & PlayTime.Seconds

    lblTime.Text = lblTime.Text + 1
End Sub

```

# Answer
> 1 votes
You can format using this: http://msdn.microsoft.com/en-us/library/6t7dwaa5.aspx or use string formatting (string.padleft I think)

---
Tags: software-engineering, game-mechanics
---


# Question
Title: Storing server information for an MMORPG
I wanted to get some professional feedback(I hope) on which is the fastest way to store/retrieve/update/delete information for an MMORPG with the server coded in C++. For characters, monsters, items, objects, etc. What do games like *World of Warcraft*, and *Lord of The Rings*, and *Star Wars* use? Do they use linked-lists (stl, or a custom one)? Do they use vectors, arrays. Should I store them with vectors to make life easier? Should I come up with my own clever ways to quickly and efficiently retrieve/change/update massive amount of data?

I was reading on the web and it seems like linked-lists are the way to go. What are your thoughts? If one were to use either of the mentioned ways to store data, should it be broken down to even smaller sub-categories? For example, if I were to use linked-lists. Would I make linked-lists for items like `weapon_on_ground`, `weapon_owned`, `armor_on_ground`, `armor_owned`, `belt_on_ground`, `belt_owned`, etc. And do that for each type of linked-list and try and make each linked-list as small as possible? As I could see a potential problem having lets say 100k items in the world, and having to sift through them each time a player drops one, or causes it to be changed/updated/deleted.

I am in the middle of porting a project I was working on to a IOCP server. Before I was just storing all data into linked-lists called: `player_info`, `items`, `monsters`, `objects`, etc. But I fear that it might not be a smart idea, and maybe there are better ways of storing information on a server that I know of.

I hope I can get some great replies.

EDIT: The "project"(as in, it may or may not get finished) is going to be a 2D dungeon crawler MMO, with a lot of monsters, items, and NPCS. Lets say itll be a old school classic 2d rpg but MMO style.

# Answer
> Do they use linked-lists (stl, or a custom one)? Do they use vectors, arrays.

Of course they use them (hard to imagine C++ program without some kind of array/map/list-like container). However, it doesn't mean they use those data structures to store data on server. Let's put things into perspective. Let's say there is 1 million of people bombarding server with requests at once. Of course, they all do it asynchronously. Using stl or trying to "reinvent your own wheel from scratch" in this situation will be suicide (thread safety). A safe guess is that data is stored within database and most of server logic revolves around interacting with that database.

Anyway, if you want to make a MMORPG (not a very good idea, IMO) and didn't do your homework, you need to investigate existing software. There are couple of opensource MMORPGs that come with source code (ryzom, planeshift, few others). So you can download the source code and read it. I expect that unless game is trivial, it'll take month or two to get overall idea of "how engine works" even for a skilled programmer.

For non-opensource games, there is "private server software" floating around. Some of it might be even legal. You could attempt to get it, install it and see what it uses.

> he "project"(as in, it may or may not get finished) is going to be a 2D dungeon crawler MMO, with a lot of monsters, items, and NPCS. Lets say itll be a old school classic 2d rpg but MMO style.

You need to investigate MUDs. They implement what you're asking for, although they normally do it using ASCII graphics (not much of a difference, though).
> 2 votes

# Answer
Not really knowing how the "pro" games do it, I'd say the *fastest* way to do it is to use a rapid-development language such as python, on the server, keep the database in memory (because it won't be THAT big, after all), and persist it with the language's built-in serialisation.

After all, the MOST IMPORTANT thing to optimise, is developer time.

NB: the Python "Twisted" framework was actually developed to write a MMO server. This does not mean that you should use it though.
> 1 votes

# Answer
A linked list is a fairly low level data structure. The type of software you're writing doesn't really affect the choice of data structures at this level. Generally speaking you use whatever data structures are provided by your language, with custom-made ones where necessary. (If you need to ask which structure to use, without a clear idea of why the default ones aren't sufficient, then you don't need a custom structure yet.)

C++ provides several useful default structures, eg. `std::list`, `std::vector`, and `std::map`. Most game developers, if they are using standard C++ rather than 3rd party frameworks, stick to using `std::vector` until they see a need for something else, because it is close to a traditional array and efficient for most tasks.

If you don't understand C++ well enough to make these decisions, then you would be better off staying with node.js. It's more important that you are able to tackle the high level problems such as getting players connected, saving data to disk, and implementing the game rules.
> 1 votes

---
Tags: c++, server
---


# Question
Title: How can I get my game to show up in the Games Explorer on Windows?
I want to create an installer for a game which allows for an icon to be put in the Games Explorer for Vista and Windows 7.

I have created the GDF, then built the script for project and obtained the .h, .gdf and .rc files. But I can't compile (using Visual Studio 2010) the .rc file into an executable to be used after that in order to create the installer. I get the following error after I set the executable path:

> "Could not load file or assembly'Microsoft.VisualStudio.HpcDebugger.Impl, Version 10.0.0.0, Culture=neutral, PublickKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified."

Any ideas what I'm doing wrong?

# Answer
Your issue is not related to inserting a link in the Games Explorer. It's likely a install error. This issue has been reported to Microsoft, and received some attention, but wasn't followed up on. Microsoft has a recommendation for solving this issue:

> The file that is reported as missing should have been installed into the correct location when Visual Studio installed. Please try one of the following actions:

As for the question, George Duckett likely provided the most important link already. Which contains step-by-step instructions for getting your game to show up in the windows games explorer.
> 1 votes

---
Tags: windows, deployment
---


# Question
Title: Optimized algorithm for line-sphere intersection in GLSL
Well, hello then!

I need to find intersection between line and sphere in GLSL. Right now my solution is based on Paul Bourke's page and was ported to GLSL this way:

```
// The line passes through p1 and p2:
vec3 p1 = (...);
vec3 p2 = (...);

// Sphere center is p3, radius is r:
vec3 p3 = (...);
float r = ...;

float x1 = p1.x; float y1 = p1.y; float z1 = p1.z;
float x2 = p2.x; float y2 = p2.y; float z2 = p2.z;
float x3 = p3.x; float y3 = p3.y; float z3 = p3.z;

float dx = x2 - x1;
float dy = y2 - y1;
float dz = z2 - z1;

float a = dx*dx + dy*dy + dz*dz;
float b = 2.0 * (dx * (x1 - x3) + dy * (y1 - y3) + dz * (z1 - z3));
float c = x3*x3 + y3*y3 + z3*z3 + x1*x1 + y1*y1 + z1*z1 - 2.0 * (x3*x1 + y3*y1 + z3*z1) - r*r;

float test = b*b - 4.0*a*c;

if (test >= 0.0) {
  // Hit (according to Treebeard, "a fine hit").
  float u = (-b - sqrt(test)) / (2.0 * a);
  vec3 hitp = p1 + u * (p2 - p1);
  // Now use hitp.
}

```

It works perfectly! But it seems slow... I'm new at GLSL. You can answer this questions in two ways:

1. Tell me there is no solution, showing some proof or strong evidence.
2. Tell me about GLSL features (vector APIs, primitive operations) that makes the above algorithm faster, showing some example.

Thanks a lot!

# Answer
There is no need for these separate `x1`, `x2` etc. variables. You can compute `a`, `b` and `c` in fewer instructions using vector operations:

```
vec3 d = p2 - p1;

float a = dot(d, d);
float b = 2.0 * dot(d, p1 - p3);
float c = dot(p3, p3) + dot(p1, p1) - 2.0 * dot(p3, p1) - r*r;

```

It is possible the compiler will notice this, but there is no reason to make it harder than it already is to optimise GLSL compilation.
> 6 votes

---
Tags: opengl, mathematics, performance, raycasting
---


# Question
Title: Writing to multiple RenderTarget2D's from HLSL shader
I need to write to two render targets: one for colour and another for depth+normal (for post-processing). I have a problem, though. Both targets seem to be getting the value output by COLOR0, while the second should logically be getting the value from COLOR1. What did I do wrong?

RT Initialization:

```
renderTarget = new RenderTarget2D(device, gameResolution.Width, gameResolution.Height, false, graphics.PreferredBackBufferFormat, DepthFormat.Depth24);
extraTarget = new RenderTarget2D(device, gameResolution.Width, gameResolution.Height, false, SurfaceFormat.Color, DepthFormat.None);

```

Using RTs:

```
Device.SetRenderTargets(new RenderTargetBinding(renderTarget), new RenderTargetBinding(extraTarget));

```

Relevant HLSL:

```
struct Pixel
{
    float4 Color : COLOR0;
    float4 Extra : COLOR1;
};

Pixel PS(Middle input)
{
    Pixel output;

    // perform other shader code

    output.Color = float4(totalDiffuse * matDiffuseColor * color.rgb + totalSpecular * matSpecularColor, color.a);
    output.Extra = float4(input.Position.z / input.Position.w, clippedNormal);

    return output;
}

```

# Answer
Try to set your render targets directly:

```
Device.SetRenderTargets(renderTarget, extraTarget);

```
> 0 votes

---
Tags: xna, hlsl, post-processing, rendertargets
---


# Question
Title: Good book/resource recommendation for HTML5 mobile game development?
**The problem**: I am taking an existing, 5 year old, html based MMORTS game and "HTML5-ing" it, "AJAX-ing" it and most importantly, optimizing for mobile devices like iPhone, android etc. For these devices, the application will be packaged as a downloadable app that is a wrapper for a browser which actually shows the game..

**The Question** Looking for a good book, or books, or in-depth articles that would help me learn:

1. what tools I have in iOS, andriod applications for optimizing an html based game. things like caching of images, etc
2. what kind of connectivity, or interactivity I can expect between the html/javascript pages and the wrapper - can I play sounds in the wrapper by triggering them from javascript? etc
3. tip and tricks to optimize html/html5 & Javascript application to run well on mobile devices
4. ETC :)

Any recommendations would be greatly appreciated!!

# Answer
> 1 votes
I've not read or purchased it but this book (and the Impact framework) seem to be getting some positive feedback.

Introducing HTML5 Game Development - By Jesse Freeman http://shop.oreilly.com/product/0636920022633.do

# Answer
> 1 votes
I will share some of my findings if anyone is interested:

HTML5 mobile app development video - great intro to general html5 mobile dev. Basic but good start http://my.safaribooksonline.com/video/web-development/mobile/9781449397388

---
Tags: html5, mobile, books
---