# Question
Title: Collision Detection problems for vertically moving platforms
**Background**

My game is a static screen (ie, no scrolling) 2d platformer and my CD routine is split into 2 - after vertical movements, (ie, gravity etc) I check for collisions, and if they are detected, correct the sprite positions vertically. Then after horizonal movements do the same thing, correcting any overlaps in the horizontal direction.

My CD code iterates through all the tile coordinates, and when it find a collision, it corrects the position, then exits and checks no more until the next game tic.

This works perfectly for static tiles, however, I've introduced platforms which are comprised of 3 horizontal tiles and which move up and down (ie, like an elevator).

**The problem**

The problem occurs if my character is standing 'over the edge' of a static block and then the elevator is moving up from under him - what I'm after is for the platform to 'catch' his over-hanging side and take him with it if you see what I mean. However, what happens is that he gets shoved to the side. I know why this is, but I'm not sure of the best way to correct it.

I think it happens because gravity is applied, pushing him into the static block, then the elevator move up so he is now embedded in 2 blocks. The vertical CD routine detects the first overlap (say with the static block), corrects it and then moves onto the rest of the game logic (but now he is still embedded in the platform) - then it eventually gets to the horizontal collision detection which moves him out of the collision horizontally. Please see my diagrams below, I hope these make it clearer.

**Possible solution**

Basically, I guess what I need is for the CD routine to carry on checking once it's corrected the first collision, but this would be so wasteful and 99% of the time it only needs to check one collision. I thought about simply making it check through the tile coordinates twice, but like I say, this seems inefficient. However, I'm trying to keep things as simple as possible and this seems the simplest solution.

**Diagrams**

Would appreciate any suggestions for how best to get around this........

# Answer
You shouldn't go through all tiles. Go through all characters instead, and do the collision checks and correction against blocks in there. Moving blocks shouldn't be considered blocks, but rather a character that moves, and pushes other characters.

Do the static block collision AFTER the characters moves and collided and got pushed.
> 4 votes

---
Tags: 2d, collision-detection, collision-resolution, platform, moving-platforms
---


# Question
Title: Separate loops for logic (tps) and rendering (fps)
I'm converting a game that was using a very basic game loop that executed update/render methods 20 times per second to lwjgl. I'm using the fps loop examples in their wiki, but have found that while this is great for rendering, it's not where I should be running game element movement logic.

What I'd like to do is use this logic for rendering only (variable fps), but also have a loop that calls game update logic 20 times per second.

I'm still somewhat new to java, but it seems to me like the best way to do this is to have two loops. One runs the rendering code ~60 fps, and one runs the game logic at 20 tps.

A few sites recommend multiplying all game element movement values by the fps delta, but I'd rather not have to remember to always multiply movement values by this, and I'd like to have an `update()` and `render()` method to keep logic separate.

Is this an acceptable way of handling this?

# Answer
> 7 votes
Yes it is. Many games have a slow logic loop (~10/s) and a fast render loop (~60/s). Turns out most games don't need to update that often. Also by decoupling logic and rendering, you won't see a frame rate drop when the game hits a particularly difficult logic tick. I could go over it, but just read this article:

http://entropyinteractive.com/2011/02/game-engine-design-the-game-loop/

Its definitely the go-to article about game loops.

# Answer
> 3 votes
Ok, so I will do the short answers before the long answer/explanation.

> I'd like to have an update() and render() method to keep logic separate.
>
> Is this an acceptable way of handling this?

Yes. Very much yes. As a professional Developer (sadly not for games) I can say that if you have a block of code that does a specific function (i.e. update game logic or draw frames) or have a block of code that is called a lot in the codebase (not at run time) making a method that is dedicated to the task is a very good idea. Try to name it something that describes what it is it does too. This makes the code MUCH more readable. It also makes debugging easier since if you know that the collision is an issue and you have the method `detectCollision()` you know that the issue MUST be in that method.

> A few sites recommend multiplying all game element movement values by the fps delta, \>but I'd rather not have to remember to always multiply movement values by this

What you could do is have a global static variable in your game client and call it whenever you need to adjust values by it. Granted this means you would still have to remember to include it in your calculations, but you wouldn't have to remember to always hard code in a value. Not hard coding a value and instead using a descriptive variable is a better practice anyways since you can change the value once and not worry about finding the hard coded value again if it ever needs to be updated.

---

Explaining Delta:

Have you ever played a game where either due to lag or tweeking setting in the console you just start running really REALLY fast and it becomes super hard to control and next thing you know your character is dead? Well depending on the machine running the game, bandwidth (if playing on the internet), and time on the game loop this changed "setting" might be the way your game will always play on someone's machine.

If you make it so that the frame is redrawn a minimum number of times so this is prevented most of the time. Think about it like this: if there is another process on the computer that is making your game loop run slowly and you don't have a bottom cap on the framerate, then its possible for the frame rate to drop to 0 fps for a little bit, which is no good. ESPECIALLY if you are skipping the draw step when the update takes to long. This implies that the player is in fact moving in the game, but it may not update to reflect that change in position.

Speaking from experience, a bottom cap on a game helps the player know that the game is still running and not just frozen. It can also help when testing out the game as once it is successfully implemented where your program is bottle-necking and slowing down. It's difficult to know if a movement/ability is causing problems if you can't see the results.

The purpose of delta time is actually to sync up different machines. Suppose the player is at point A and wants to get to point B in 5 seconds real time. If on a mid range computer, delta may be a negligently small number, but on a great machine or a low end machine delta may be really high or really low respectively. The point being that the result of the Update step is it appears identical to the player.

i.e.: For the following suppose the distance between A and B is 20 units and the default move "speed" is .1. NOTE: using arbitrary values for tps.

High end machine: suppose the update speed is 120 tps. well the player is going to get to point B in no time flat.

Mid range: update speed: 60. tps it will take this machine 2x the real world time to get to point B than the high end machine.

Low end: update speed: 20 tps. this machine will take 3x longer than the mid range machine.

Now what if we use a delta move so our default move "speed" is .1 x delta? NOTE: `delta = realWorldTime/updateSpeed`

If the game loop is running fast and you update your calculations by this new value then the distance the player will travel on the high end machine between updates is extremely small and the distance on the low end machine will be very large. The end result of which is the player seeing the character move at the same real world speed.

If you want to see a real world example of what this is like (assuming you are on a mid range computer) load up any 3D MMO and put the settings on minimum. Then notice the framerate and start running around, get a good feel of the graphics and try to understand the distance the character actually moves inbetween each frame. Now turn the settings to max and do the same thing. You may note that your framerate has dropped (unless you're running a beast of a machine) but your character still runs at the same speed in real world time. This is the result of using delta.

Hope this helps :D

---
Tags: java
---


# Question
Title: How to smoothly change the target of smooth follow without camera glitch?
I am trying to change the target of the smooth follow at runtime, but there is a glitch in the camera since the targets are different sizes. I tried using lerp and smooth damp both gave the same result. How do I overcome the jerk in camera motion?

# Answer
From the sound of it the error is probably not due to the size of the targets (as that would not modify their position, only their volume). Try using a larger time scale with smoothdamp, perhaps only used during a change over period between targets.

Another option would be to use slerp instead during the switch over; to get the slower acceleration. Without seeing your actual code, it is difficult to see the exact problems (and unfortunately I am not in front of my development machine at this precise time).

Side note: What you MAY want to program in is a "springy-ness" factor into the camera tracking code. I'd look into implementing this, and that code would probably solve your problem (as this sounds like a "camera snap" issue, rather than a "glitch" per say).
> 1 votes

---
Tags: unity, camera, lerp
---


# Question
Title: D3D11 Deferred Context CommandList Reset
a rather quick question, I am starting on implementing rendering with deferred context into my game engine, and came across a heavy memory leak when recording command lists on my deferred contexts. Because every frame I would go like this: DeferredContext\[THREAD\]-\>FinishCommandList( 0,&commandLists\[THREAD\] ), it would eat up RAM, so I Release them every time, like:

```
if(commandLists[THREAD]){
 commandLists[THREAD]->Release();
 commandLists[THREAD] = NULL;
}

```

I previously only released objects when they wouldn't be used any more, so I thought there would be a more optimized way of handling this? (Like mapping dynamic \*ID3D11Buffers for example?)

# Answer
> 3 votes
According to this NVIDIA presentation, the deferred context is supposed to reset itself upon `FinishCommandList`. It should not be necessary (nor is it advisable) to release and recreate the deferred contexts every frame. You *do* need to release the `ID3D11CommandLists` each frame after executing them, though.

---
Tags: directx11, deferred-rendering
---


# Question
Title: Items failing to cast as Image Items in GLEED2D
When I try to cast an Item as an ImageItem in fails to convert and returns null, hence skipping the code I want to use to extract the texture data. I have already down cast my Item to an ImageItem, and set my TextureItem to public, so I am struggling to see the solution.

Any advice would be greatly appreciated.

Game 1 (Main Class)

ImageItem Downcast

```
    public class ImageItem : Item
    {
        public Texture2D Texture;

        public List<Color[]> itemTextureDataList = new List<Color[]>();
        public List<Rectangle> itemRectangleList = new List<Rectangle>();
    }

```

Assign level textures color data to array

```
        foreach (Layer layer in level.Layers)
        {
            foreach (Item item in layer.Items)
            {
                ImageItem imageItem = item as ImageItem;

                if (imageItem != null)
                {
                    Texture2D texture = imageItem.Texture;

                    imageItemList[iImageItemNum].itemTextureDataList[0] = new Color[imageItem.Texture.Width * imageItem.Texture.Height];
                    imageItem.Texture.GetData(imageItemList[iImageItemNum].itemTextureDataList[0]);
                    iImageItemNum++;
                }
            }
        }

```

Create a rectangle for every level texture

```
        foreach (Layer layer in level.Layers)
        {
            foreach (Item item in layer.Items)
            {
                ImageItem imageItem = item as ImageItem;
                if (imageItem != null)
                {
                    imageItemList[iImageRectNum].itemRectangleList[0] = new Rectangle((int)imageItem.Position.X, (int)imageItem.Position.Y, imageItem.Texture.Width, imageItem.Texture.Height);
                    iImageRectNum++;
                }
            }
        }

```

Level Class

```
    public partial class TextureItem : Item

        {
            /// <summary>
            /// The item's rotation in radians.
            /// </summary>
            public float Rotation;

            /// <summary>
            /// The item's scale vector.
            /// </summary>
            public Vector2 Scale;

            /// <summary>
            /// The color to tint the item's texture with (use white for no tint).
            /// </summary>
            public Color TintColor;

            /// <summary>
            /// If true, the texture is flipped horizontally when drawn.
            /// </summary>
            public bool FlipHorizontally;

            /// <summary>
            /// If true, the texture is flipped vertically when drawn.
            /// </summary>
            public bool FlipVertically;

            /// <summary>
            /// The path to the texture's filename (including the extension) relative to ContentRootFolder.
            /// </summary>
            public String texture_filename;

            /// <summary>
            /// The texture_filename without extension. For using in Content.Load<Texture2D>().
            /// </summary>
            public String asset_name;

            /// <summary>
            /// The XNA texture to be drawn. Can be loaded either from file (using "texture_filename")
            /// or via the Content Pipeline (using "asset_name") - then you must ensure that the texture
            /// exists as an asset in your project.
            /// Loading is done in the Item's load() method.
            /// </summary>
            public Texture2D texture;

            /// <summary>
            /// The item's origin relative to the upper left corner of the texture. Usually the middle of the texture.
            /// Used for placing and rotating the texture when drawn.
            /// </summary>
            public Vector2 Origin;

            public TextureItem()
            {
            }

            /// <summary>
            /// Called by Level.FromFile(filename) on each Item after the deserialization process.
            /// Loads all assets needed by the TextureItem, especially the Texture2D.
            /// You must provide your own implementation. However, you can rely on all public fields being
            /// filled by the level deserialization process.
            /// </summary>
            public override void load(ContentManager cm)
            {
                //throw new NotImplementedException();

                //TODO: provide your own implementation of how a TextureItem loads its assets
                //for example:
                //this.texture = Texture2D.FromFile(<GraphicsDevice>, texture_filename);
                //or by using the Content Pipeline:
                this.texture = cm.Load<Texture2D>(asset_name);

            }

```

# Answer
Imagine that you are a manufacturer of flanges. You have a great deal of flanges in your possession, more than you can reasonably store in your own garage, so you've purchased a warehouse in which to store your inventory.

One day you receive a large order that must be fulfilled with all haste, so you go to your warehouse manager, Carl the Compiler (whose epithet is a matter of some mystery), and ask him to assist you in doing so.

"What kind of flanges do you need?" Carl asks you.

"It doesn't matter," you say, "the customer just wants 100 flanges."

It just so happens that Carl is sitting on top of a large pile of boxes, each of which is clearly marked as containing a *frobnosticating flange*. Carl points out that it is trivially provable that all frobnosticating flanges are flanges, and orders that the entire mountain of boxes be immediately shipped to the customer.

This is *upcasting*.

The next day you receive another order, but this time the client is more specific: rather than requiring any kind of flange, he needs 100 *defenestrating flanges*. You return to Carl to ask for his assistance.

Unfortunately, it seems that the marketing department has decided to relabel all of the packages in the warehouse. Rather than each box being clearly labeled, they now simply read 'FLANGE' in a tasteful humanist font.

You inform Carl of the new order for defenestrating flanges.

"That could be a bit of a problem," he says. "Ever since marketing relabeled all of the boxes, I have no idea what kind of flange is inside any of them."

You pick one of the boxes at random and hand it to Carl and ask, '`box is DefenestratingFlange`?'

He opens the box and pulls out the frobnosticating flange inside. '`false`,' he replies.

Fortunately, you suddenly remember that you had specifically set aside 100 defenestrating flanges earlier that week, hiding them away in a unused room so that nobody else would take them. You go to the room and, lo and behold, the boxes are still there, though they—like all the rest—have been 'updated' with the new labels.

You carry these boxes out to Carl and tell him to ship them to the customer with all haste.

"But I can't verify that these are defenestrating flanges," he objects.

"That's fine," you tell him, "I have special knowledge that they are. I'm the boss, and you can trust me to know what I'm talking about, so just do it."

Carl accepts this and does as you ask.

This is *downcasting*.

You then realize that you've misplaced one of the boxes, leaving you one flange short of the 100 that were ordered. To rectify this, you retrieve a random box from the warehouse—not bothering to check what's actually inside—and throw it in with the rest.

'`InvalidCastException`,' Carl complains.

You open the box. There's a frobnosticating flange inside.

Well, nobody's right all the time.
> 3 votes

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


# Question
Title: Auto-tiling with Yoshi's Island style tiles
I'm creating a 2D platformer and I'd like to implement an auto-tiling system. Normally, this wouldn't be particularly difficult. However, I'd like to have tiles like in Yoshi's Island, where the graphics extend past the actual collidable tile's boundaries.

Consider this image:

Although the eggs and the Piranha Plant are clearly resting on the ground, the flower tiles continue behind them, out of the collidable tile.

I know that it would be simple to do by hand, but extremely time consuming. Using an auto-tiling algorithm would save me a lot of time and boredom, but I'm not sure where to start.

# Answer
The easiest way is to have your tiles set as passable or not passable and simply set the top tiles on some types to passable. Like the grass. And some as not passable, like the crystal.

Not a big answer, I guess, but why make this over-complicated.
> 1 votes

---
Tags: graphics, tiles, platformer, automation
---


# Question
Title: How to place an object so that it does not overlap the objects in my scene?
In my game, the user has to click at a point to place an object (mesh). I can cast a ray and find the horizontal point where the object can be translated and then attached to rootNode to display it. However, the problem is that if the user click too near to another object/scene\_wall the object to be placed, runs into it. How can I prevent that?

# Answer
You should be able to get by with a simple collision check before placing the object. The basic steps of which you'll find below:

1. Before placing the object, perform a collision check with a physics body representation of the mesh you're placing (either a bounding sphere, bounding cube or more accurate shape).
2. If this collision check collides with the scene, move the target position far enough away from the collision that it will no longer collide. Do the collision check again with the new target position.
3. If the new target position also has a collision, you're probably in a location that's too small to fit the object you want to place. Notify the user and perhaps draw an outline of the object to show how it doesn't fit.
> 1 votes

---
Tags: collision-detection, raycasting, bounding-boxes, jmonkeyengine
---


title: Is there still a market for 2D games?

text:
# Question
Title: Is there still a market for 2D games?
Do 2D games still sell well? Assume it has nice visuals and good game-play.

I want to make games and want to start with 2D, but I am a bit hesitant, I have more than 8 years experience with 3D applications like Maya and other software, but not games. I'd like to know if it's worth the time investment to make 2D games.

# Answer
> 5 votes
Yes they do.

A few years ago a little game called Marvel vs. Capcom 3 came out which sold really well and it had downloadable content that had to be paid for. Also, there is a HUGE fanbase of fight games (think Tekken, Mortal Kombat, Street-Fighter, etc) that all love 2D. There are 3D fighters (Soul Calibur and Dead or Alive plus others) that provide whole different mechanics.

Then there are indie games. Check out "Thomas Was Alone", "Rogue Legacy", "Super Meat Boy", and "Don't Starve" just to name a few. Basically take a look at almost any game that has ever been in a "Humble Indie Bundle" (NOTE: they do have non indie bundles as well)

Then there are casual games like anything made by Zynga.

If you do a bit of research you will find that what makes a game "successful" and "revenue generating" isn't whether it's 3D or 2D, it's whether it's a good game with good, unique game-play elements.

That being said, in my opinion if you're out to make a game to make money, chances are you won't. Great games are made as a labor or love. I HIGHLY recommend watching "Indie Game: The Movie" and you will see both successes and failures. And you also see "Fez", which you should check out what happened to that game AFTER you watch the movie.

# Answer
> 2 votes
Now in 2018, there is quite a retro-gaming boom going on. There are some quite well selling games which use 2d graphics. Among the recently leaked number of the top most owned games on Steam are titles like:

* Terraria (13 Million)
* Brawlhalla (8.6 Million)
* The Binding of Isaac (7.1 Million)
* Castle Crashers (5.5 Million)
* Stardew Valley (4.9 Million)
* Starbound (4.3 Million)
* Undertale (3.5 Million)
* LIMBO (3.2 Million)
* ...and many more 2d titles.

Sure, the 2d games are still a small fraction of that list. *Most* of the best selling games are still AAA titles with state-of-the-art 3d graphics. But the considerable number of 2d games which do great or at least reasonably well compared to their budget proves that 2d games can again be commercially successful.

My personal favorite example as a 90s SEGA kid: Sonic Mania sold more copies than Sonic Generations.

But do not think that this is an easy way to get rich. What you see here is strongly influenced by survivorship bias. What you don't see is the flood of low quality 2d games which come out *every day* and barely bring in the license fees for the software used to make them. Most are estimated to lose money (See the talk Let's Be Realistic: A Deep Dive into How Games Are Selling on Steam from GDC 2018 for an in-depth analysis). So if you want to make some money in the game industry on a low budget, you need to create a game which plays good, looks good and most of all you need to do some good marketing for it.

---
Tags: 2d, revenue
---


title: HLSL's Tex2D for GLSL?

text:
# Question
Title: HLSL's Tex2D for GLSL?
I am trying to port a HLSL shader to GLSL. I'm just not quite sure how to convert this line:

```
  outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(-4.0 * pxSz.x * blurSize,0)).a * 0.05;

```

It's mostly the Tex2D I'm having trouble with. In GLSL, it seems to work differently.

I'm porting a horizontal blur

```
 texture al_tex;
   sampler2D s = sampler_state {
      texture = <al_tex>;
   };

   int tWidth;
   int tHeight;
   float blurSize = 5.0;
   float4 ps_main(VS_OUTPUT Input) : COLOR0
   {
      float2 pxSz = float2(1.0 / tWidth,1.0 / tHeight);
      float4 outC = 0;
      float outA = 0;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(-4.0 * pxSz.x * blurSize,0)).a * 0.05;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(-3.0 * pxSz.x * blurSize,0)).a * 0.09;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(-2.0 * pxSz.x * blurSize,0)).a * 0.12;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(-pxSz.x * blurSize,0)).a * 0.15;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(0,0)).a * 0.16;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(pxSz.x * blurSize,0)).a * 0.15;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(2.0 * pxSz.x * blurSize,0)).a * 0.12;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(3.0 * pxSz.x * blurSize,0)).a * 0.09;
      outA += Input.Color.a * tex2D(s, Input.TexCoord.xy + float2(4.0 * pxSz.x * blurSize,0)).a * 0.05;

     outC.a = outA;

      return outC;
   }

```

Thanks

# Answer
Use `texture2D (...)` on older versions of OpenGL (before OpenGL 3.0) and `texture (...)` on newer versions.

Newer versions of GLSL (1.3+, which corresponds to OpenGL 3.0) are nice about this, they automatically determine the texture overload based on sampler type and texture coordinates you use. So you don't have to do `textureCube (...)`, `texture3D (...)`, etc.

Also, use proper texel centers when porting from D3D9. You don't need a half-texel offset in OpenGL or Direct3D 10.
> 2 votes

# Answer
The GLSL function you're looking for is called texture.
> 0 votes

---
Tags: shaders, glsl, hlsl
---


# Question
Title: First Mobile Indie Game - Monetization Model. Ad based or in app purchases?
We are a team of 3 (1 graphics designer, 2 developers). We're almost done with our first Android based indie game. Which monetization model will be suitable for us? We don't want to disturb users with a lot of ads (at this point we're thinking to put only banner ads) also, if we go with in app purchases, can we also keep ads as well? or is it a better practice to follow one model at a time? How much will it affect the user experience?

# Answer
Like other comments have said, its entirely a personnel decision. That being said, I would like to point out a few things:

If you decide to have ads, be careful with your buisness model you represent to the player. If you're charging to get the game (not releasing a free version) people may be a bit turned off that you're still showing them ads. That being said, ads on a free version of the game are golden. Several games out there have a free version that has ads that offers a paid version that doesn't.

As someone who gets almost exclusively free mobile games and frequently reads web comics, I honestly don't mind looking at ads for sites and games I enjoy if I know that this is how the developers make their money.

With microtransactions (in game purchases) its also important to understand if this works with your game model. Are there things you CAN sell to the player? Extra Lives, Experience/stat boosts, extra items, vanity items etc. If your game doesn't have anything like that then you might not have anything to really sell with microtransactions. You can also have these same items out there for an in game currency. (Check out how Guild Wars 2 does gems or Jetpack Joyride does its shop if you need examples) A common practice is to offer it for a somewhat ridiculously large number of in game credits or for a small real world amount (like $1 or $2).

It is possible to have both ads AND microtransactions HOWEVER I highly advise being very careful when doing this. You don't want to make the player feel like the entire game is a grab at their money, this will turn anybody off. It is very doable but just be mindful of what the player may think when they see these things. If you're not sure of what the player will think, download a few games for yourself and try to find good and bad examples (I have a feeling you already have a few of these on your mobile device) If you do decide this though, I highly suggest making a version that is ad free that is a paid version.

Ultimately it comes down to what game are you making and what kind of business decisions you want to make. This is entirely up to you. Coming on here and asking "What are some pros and cons?" is fine, but truth be told there is no golden ultimate answer here. (unless your game is named "golden ultimate answer")

---

**EDIT**: I just thought of something else.

Any team that makes the ads as a part of the game gets major props in my mind. I'm not talking about "Do so many surveys and you can get a free *_*!!!" I mean a pop up ad occurs and when you close it the character (if the game is an RPG) says something, like "Bloody ads, mess up my aim" or "Hey, that might be cool." if the player clicked on it. It may be too late for your team to do this since you said you're almost done (congratulations by the way), but it would be fun to see anyways. PLUS this gives added immersion since you would be making the character experience the same thing as the player. (Think something like in the Never Ending Story)
> 4 votes

# Answer
Being a gamer , what annoys most is too much ads . Avoid placing ads as much as you can if you want a successful game. Focus more , more and more on game-play . If game-play is awesome , anything is tolerated. People dont mind in-game purchases but keep in mind that these purchases should not in any case affect the actual game play , they should be more like customizations etc . Hope it works out for you guy :) Best of luck
> 0 votes

# Answer
Being a gamer myself,I would prefer IAP, but it wouldnt be as profitable as Ads As everyone here said, it's up to you, but if you choose Ads, make sure they are subtle and don't spoil your games example: You dont want an Ad where a user might touch it by mistake and ruin their gameplay :)
> 0 votes

---
Tags: android, monetization
---


# Question
Title: render sprites with a transparent background (XNA)
For my game I want to make a map of the world. Per country I made a file with the border of the country and the rest of background is transparent. This way all my files have the same width and height. My problem is that XNA only renders the first image and it does it in an alphabetical order. For example: if I change the name of the first sprite so it isn't first in alphabetical order, it just renders the first sprite.

The sprites are loaded in a sortedlist and each key is the name of the continent + the name of the country. And I loop through this list to render each sprite.

Code to load the files:

```
protected override void LoadContent()
    {
        DirectoryInfo objDirectory = new DirectoryInfo(Game.Content.RootDirectory + "/Regions");
        FileInfo[] objFiles = objDirectory.GetFiles("*.*");

        objSpritebatch = new SpriteBatch(Game.GraphicsDevice);

        foreach (FileInfo File in objFiles)
        {
            string[] FileName = File.Name.Split("_".ToCharArray());
            string strContinent = FileName[1] + "/" + FileName[2].Substring(0, FileName[2].Length - 4);
            lstBorders.Add(strContinent, Game.Content.Load<Texture2D>("Regions\\" + Path.GetFileNameWithoutExtension(objFiles[0].Name)));
        }

        base.LoadContent();
    }

```

Code to render the files:

```
public override void Draw(GameTime gameTime)
    {
        objSpritebatch.Begin(SpriteSortMode.Texture, BlendState.AlphaBlend);

        foreach(KeyValuePair<string, Texture2D> Border in lstBorders)
        {
            objSpritebatch.Draw(Border.Value, new Rectangle(0, 0, 800, 400), Color.White);
        }

        objSpritebatch.End();

        base.Draw(gameTime);
    }

```

I allready did some research and hoped it would be fixed by using those parameters in the begin command but it didn't help. I hope I gave you all the code you need.

# Answer
You are drawing all sprites in the same postition and same size, if textures don't have alpha channel you will only see one of them.

Test this to draw a grid with 8 columns:

```
    var size = 100;
    var width = 8;
    var n=0;
    foreach(KeyValuePair<string, Texture2D> Border in lstBorders)
    {
        var x = (n % width)*size;
        var y = (n/width) * size;
        objSpritebatch.Draw(Border.Value, new Rectangle(x, y, size, size), Color.White);
        n++;
    }

```

If you can see all, them you have a problem with the alpha channel of your textures. Sometimes the alpha channel is stored as a key color. You can enable an option in the texture processor of the image to manage this situation. Going to Texture/Properties/ContentProcessor/Color Key Enabled

And related to order, if you use a SortedList to store sprites, it will be orderer by the key, your key is the name of the file, so it's ordered alphabetically by texture name, if you want other order, change your key or the file names.

You can use a file name format like "Continent\00-Europe.jpg" to give the desired order.
> 3 votes

---
Tags: xna, c#, xna-4.0, transparency
---


# Question
Title: Shooting many bullets toward the mouse position
I try to shoot a bullet toward the mouse position by this code.

```
float deltaX = mousePosition.x - (aircraft.getPosition().x + aircraft.getLocalBounds().width / 2);
float deltaY = mousePosition.y - (aircraft.getPosition().y + aircraft.getLocalBounds().height / 2);
float angleRadian = (float)(std::atan2(deltaY, deltaX));
float angleDegree = (float)(angleRadian * 180 / PI);

```

It works fine with one bullet but when I add another one bullet to shoot together I use this code to specify start shooting point of each bullets.

```
sf::Vector2f offset1(aircraft.getPosition());
offset1.x += -10;//start shooting point first bullet.

sf::Vector2f offset2(aircraft.getPosition());
offset2.x += 10;//start shooting point second bullet.

```

this is a picture of this problem.

When I rotate aircraft to picture 2 the bullets are not the same as the first picture.

How can I solve this problem?

# Answer
This is rather easy using the buit-in transforms:

```
float hoffset = ...; // This is the horizontal offset for the gun

sf::Transform rotation;
rotation.rotate(angle); // This is essentially the ship's rotation

// This will get you the offsets relative to the ship's position
sf::Vector2f bulletOffsetLeft(rotation.transformPoint(-hoffset, 0.f));
sf::Vector2f bulletOffsetRight(rotation.transformPoint(hoffset, 0.f));

```
> 3 votes

# Answer
This seems rather straightforward, you need to consider the ships rotation, lets assume that picture 1 is the 0° rotation, then your offsets would be;

```
sf::Vector2f offset1(aircraft.getPosition());
offset1.x += 10 * sin(deg2rad(aircraft.getRotation()+180));
offset1.y += 10 * cos(deg2rad(aircraft.getRotation()+180);

sf::Vector2f offset2(aircraft.getPosition());
offset2.x += 10 * sin(deg2rad(aircraft.getRotation()));
offset2.y += 10 * cos(deg2rad(aircraft.getRotation()));

```

with deg2rad being

```
inline double deg2rad( double degrees){
    return degrees * pi / 360;
}

```

where you get `pi` from is up to you, either use `M_PI` by using `#define _USE_MATH_DEFINES` before including `<cmath>` or just use a `#define PI 3.141592653589793238462643383279502884` in your code.
> 1 votes

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


title: Xna menu navigation with controller

text:
# Question
Title: Xna menu navigation with controller
I have a menu that you can navigate with the keyboard, but I also want it so you can navigate it with the controller thumb sticks. But my problem is that if you push down or up on the thumb sticks it will just fly through the menu. To fix problem if it was a keyboard you would just do: `prevKeyState.IsKeyUp(Keys.Down)`. So I was wondering if there anything like this for the controller thumb sticks?

I'm not sure if I'm doing something wrong but it still flies through the menu.

```
 private enum GamePadStates
    {
        None,
        GoingDown,
        GoingUp
    }

    GamePadStates CurrentGamePad, PreviousGamePad = GamePadStates.None;
     public void Update(GameTime gameTime)
    {
        keyState = Keyboard.GetState();
        gamePadState = GamePad.GetState(PlayerIndex.One);
        PreviousGamePad = CurrentGamePad;

        if (gamePadState.ThumbSticks.Left.Y > 0.1)
            CurrentGamePad = GamePadStates.GoingUp;
        else if (gamePadState.ThumbSticks.Left.Y < -0.1)
            CurrentGamePad = GamePadStates.GoingDown;
        else
            CurrentGamePad = GamePadStates.None;

        if (keyState.IsKeyDown(Keys.Down) && prevKeyState.IsKeyUp(Keys.Down) ||
             CurrentGamePad == GamePadStates.GoingDown && PreviousGamePad != GamePadStates.GoingUp)
        {
            if (selected < (buttonList.Count - 1))
            {
                selected++;
            }
        }

        if (keyState.IsKeyDown(Keys.Up) && prevKeyState.IsKeyUp(Keys.Up) ||
            CurrentGamePad == GamePadStates.GoingUp && PreviousGamePad != GamePadStates.GoingDown)
        {
            if (selected > 0)
            {
                selected--;
            }
        }

```

# Answer
> 2 votes
You can do it in a similar way to keyboard, storing the state by yourself:

```
   enum States {None, GoingDown, GoingUp }

   States Current, Previous;

   void Update()
   {
           Previous = Current;

           if (thumbStiscks.Y>0.5 || keyState.IsKeyDown(Keys.Up))
               State = States.GoingUp;
           else if (thumbSticks.Y<-0.5f || keyState.IskeyDown(Keys.Down))
               State = States.GoingDown;
           else State = States.None;

           if ( Current == States.GoingDown  && Previous != States.GoingDown)
                && selected < (buttonList.Count - 1)) {
             selected++;
           }
           else if ( Current == States.GoingUp && Previous != States.GoingUp)
                     && selected >0) {
             selected--;
          }
   }

```

---
Tags: xna, c#, controllers, menu
---


title: OpenGL FBO not being drawn to

text:
# Question
Title: OpenGL FBO not being drawn to
In my project I'm trying to implement a deferred rendering system, problem is, I can't seem to get a second FBO to work.

**UPDATE 1**

Here is the FBO initialization code:

```
/// G-Buffer FBO
GLuint gBufferFBO;
glGenFramebuffers(1, &gBufferFBO);
glBindFramebuffer(GL_FRAMEBUFFER, gBufferFBO);

GLuint depthStencilTex;
glGenTextures(1, &depthStencilTex);
glBindTexture(GL_TEXTURE_2D, depthStencilTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, 1024, 768, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencilTex, 0);

GLuint colorTex;
glGenTextures(1, &colorTex);
glBindTexture(GL_TEXTURE_2D, colorTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorTex, 0);

GLuint lightAccTex;
glGenTextures(1, &lightAccTex);
glBindTexture(GL_TEXTURE_2D, lightAccTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, lightAccTex, 0);

GLuint viewNormTex;
glGenTextures(1, &viewNormTex);
glBindTexture(GL_TEXTURE_2D, viewNormTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, viewNormTex, 0);

GLenum DrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glDrawBuffers(2, DrawBuffers);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

if((g_RenderManager->CheckFBO()))
    return 1337; // Returns if there is an error
/// End G-Buffer FBO

/// Light Pass FBO

GLuint lightPassFBO;
glGenFramebuffers(1, &lightPassFBO);
glBindFramebuffer(GL_FRAMEBUFFER, lightPassFBO);

GLuint LPdepthStencilTex;
glGenTextures(1, &LPdepthStencilTex);
glBindTexture(GL_TEXTURE_2D, LPdepthStencilTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, 1024, 768, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, LPdepthStencilTex, 0);

GLuint LPcolorTex;
glGenTextures(1, &LPcolorTex);
glBindTexture(GL_TEXTURE_2D, LPcolorTex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1024, 768, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, LPcolorTex, 0);

GLenum LPDrawBuffers[] = { GL_COLOR_ATTACHMENT0 };
glDrawBuffers(1, LPDrawBuffers);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

if((g_RenderManager->CheckFBO()))
    return 1337; // Returns if there is an error
/// End Color Pass FBO

```

Here is my code that draws to the FBOs:

```
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gBufferFBO);
glViewport(0, 0, 1024, 768);
glDrawBuffers(2, DrawBuffers);  // GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

// Here I draw my geometry to the G-Buffer.

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, lightPassFBO);
glViewport(0, 0, 1024, 768);
glDrawBuffers(1, LPDrawBuffers); // GL_COLOR_ATTACHMENT0
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

// Here I draw light volumes.

glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
glViewport(0, 0, 1024, 768);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT );

glBindFramebuffer(GL_READ_FRAMEBUFFER, lightPassFBO);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glBlitFramebuffer(0, 0, 1024, 768, 0, 0, 1024, 768, GL_COLOR_BUFFER_BIT,     GL_NEAREST);

```

Rendering to the `gBufferFBO` works fine, but when I try to render out different geometry with a different shader in `lightPassFBO`, nothing is rendered. Using either `glBlitFreambuffer` or just rendering to a quad, it still will not render.

And I clear each buffer before use, so that can't be the problem.

When looking in gDEbugger, it draws to my first buffer, but not my second.

Here is gDEbugger showing the first batch of geometry being successfully drawn into the first buffer:

And here is gDEbugger showing that a different batch of geometry is not being drawn into the second buffer!:

If it's worth anything, this is my shader code:

G-Buffer vertex shader

```
#version 330 core

smooth out vec2 vVaryingTexCoords;
smooth out vec3 vVaryingNormals;

uniform mat4 MV;
uniform mat4 MVP;

layout(location = 0) in vec3 vPos;
layout(location = 1) in vec2 vTexCoords;
layout(location = 2) in vec3 vNormals;

void main()
{
    vVaryingTexCoords = vTexCoords;
    vVaryingNormals = normalize(vec3(vec4(vNormals, 0.0) * MV));
    gl_Position = vec4(vPos, 1.0) * MVP ;
}

```

And my fragment shader (passes out color, spec power and normals)

```
#version 330 core

in vec3 vVaryingNormals;
in vec2 vVaryingTexCoords;

uniform sampler2D vTexTest;
uniform float Shininess;
uniform vec3 vColoration;

void main()
{
    vec3 normals = normalize(vVaryingNormals);

    gl_FragData[0].rgb = vColoration;
    gl_FragData[0].rgb *= texture(vTexTest, vVaryingTexCoords).xyz;
    gl_FragData[0].a = Shininess;

    gl_FragData[1].r = normals.x;
    gl_FragData[1].g = normals.y;
    gl_FragData[1].b = normals.z;
}

```

And my shader which **should** draw light volumes to my second buffer:

```
#version 330 core

uniform mat4 MVP;

layout(location = 0) in vec3 vPos;
layout(location = 1) in vec2 vTexCoords;
layout(location = 2) in vec3 vNormals;

void main()
{
    vec2 vVaryingTexCoords = vTexCoords;
    vec3 vVaryingNormals = vNormals;
    gl_Position = vec4(vPos, 1.0) * MVP;
}

```

fragment shader:

```
#version 330 core

void main()
{
    gl_FragData[0] = vec4(1.0,1.0,1.0,1.0);
}

```

**UPDATE 2**

My uniforms are created at load time. I have a class that looks for uniforms in a shader, and stores them to a map: the key is the uniform name, and the second value contains a `GLuint` handle. I use `glGetUniformLocation()` after creating a shader program, attaching shaders and linking it. I also do it after loading textures, so samplers will have a valid values.

Here is an example of loading my shader:

```
this->m_ShaderList[shaderName] = new CShaderProg(shaderName, true); // This just calls to glCreateProgram() and returns the handle
this->m_ShaderList[shaderName]->AttachShader(ShaderManager::CShader(*this->m_ptrMan->GetShaderSource(sVert), true));
this->m_ShaderList[shaderName]->AttachShader(ShaderManager::CShader(*this->m_ptrMan->GetShaderSource(sFrag), true));
this->m_ShaderList[shaderName]->LinkProgram();

...

// Then I check through each shader attached, adding uniform locations, if they don't exist
// If not found, add to list
if(it == this->m_UniformList.end()) {
    GLint tmpint = 1; // this is just a dummy value. Initialising to -1 or 0 makes glGetUniformLocation() return -1
    this->m_UniformList[VSdata[i+2]] = glGetUniformLocation(tmpint, VSdata[i+2].c_str());
}

```

I changed the code in the shaders to use `layout(location = n)` as I don't do any attribute binding (I never have). I use VAO/VBO for my geometry and pass in the values to my shaders using `glEnableVertexAttribArray()` and `glDrawElements()`.

Something to note, using the G-Buffer shader on my second FBO results in geometry being rendered.

Sorry for such a lengthy post, but I've been having this problem for a few weeks now, and I just want to get to the bottom of why FBOs work for everyone else but me. The only other time I have found someone with this problem is here, but it was never answered.

# Answer
> 3 votes
Turns out my problem was with the uniform locations.

I wasn't querying the uniform location when using a different shader and I was only querying an abritray value (value of `GLuint(1)`), not an actual program, which is why my first shader created (which I used on my first FBO) worked and my second shader created(which I use on my second FBO) didn't work.

Now I know that uniforms are only valid across **one** shader, not multiple ones.

Thanks @Andon M. Coleman!

---
Tags: c++, opengl, glsl, frame-buffer
---


# Question
Title: Gameplay-affecting LOD in a multiplayer UDK environment
There is an idea of developing a proof-of-concept multiplayer environmental exploration game that has *varying levels of level of detail* in terms of not just how objects are represented, but *what objects are presented to each player, depending on the assigned parameters to each player present in the world* governed by certain skill-sets. After the initial discussion, it was decided to to give Unreal Development Kit a try for building this concept project. We know that in all major engines LOD settings can affect meshes and textures just fine, but normally it's bound to graphics settings for the whole game.

**Example of the implementation:** Player A focuses on imagery and and thus sees the world in higher level of detail - there are better textures and better meshes visible, whilst player B focuses on audio clues and thus is enabled to hear more sounds that are triggered by various events.\*

Is it possible to implement such a mechanism in a multiplayer Unreal Engine 3 environment?

Since I'm relatively new to both game development and UDK's capabilities, it would be greatly appreciated if I could get advice on any possible show-stoppers for this idea. Thank you.

# Answer
UDK doesn't have anything built in that does exactly what you say. However, it's certainly possible since you can conditionally play/display sounds/meshes. For example, using Kismet, the conditionals are pretty simple.

It'll certainly be a lot of work, though it's unclear from your requirements if that's a "showstopper". There's nothing that's technically impossible with what you're suggesting.
> 1 votes

---
Tags: udk, level-of-detail
---


# Question
Title: CryENGINE: Remove the default gun and put another thing?
I'm using CryEngine for a game that I'm working on for a while but it is not an FPS (it's a Sandbox) then I would remove the gun and put another thing (example: a shovel)

# Answer
> 1 votes
Yes, it's possible to do this. You can follow the documentation found under First Person Weapons. The definition of such an item would be created using information found in the Weapon System documentation. Overall, the steps are as follows:

1. Model a weapon/shovel through 3dsmax/maya.
2. Make animations for the item through 3dsmax/maya.
3. Export the item and animations using the CryEnigne 3 exporter.
4. Make a xml file for your tool.

---
Tags: cryengine
---


# Question
Title: Rotate a 3D object in Unity3D on button click
There is a 3D character in my application developed using Unity3D. Now I want to rotate this 3D character when the user press the rotation button. I tried several ways, but didn't work. How can I rotate a character when the player presses the rotation button?

# Answer
> 2 votes
Two basic steps here, detecting when a button is pressed, and rotating the object. Both are pretty simple.

Create a new script, or insert the following into your existing script that is attached to the object you want to manipulate:

```
float angle = 10;
Vector3 axis = new Vector3(0,1,0);
float anglePerUpdate = 2f;

void OnGUI () {

    //Create a new Button at location 0,0, with a size of 100, 20.
    //The text in the button will read "Rotate Once"
    if(GUI.Button(new Rect(0,0,100,20), "Rotate Once")) {
        //if button is pressed, perform the following
        //rotate the object to a specified angle rotating around the axis specified
        this.transform.rotation = Quaternion.AngleAxis(angle, axis);
    }

    //create another button below "Rotate Once".
    //this is a  RepeatButton that will continue to perform its action every update
    if(GUI.RepeatButton(new Rect(0,25,100,20), "Rotate Continuous")) {
        //if button is pressed, perform the following
        //rotate the object at a specified speed, around the specified axis
        //take the existing rotation and add a little bit to it
        this.transform.rotation =
            this.transform.rotation * Quaternion.AngleAxis(anglePerUpdate, axis);
    }
}

```

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


# Question
Title: Creating a card dangling affect using 2d sprites
I'm working on a 2d card game for iOS and using Cocos2d. When a player picks up a card and drags it I would like to make it appear that the card is lifted off the table and dangling just below their finger. So when they move their figure the card is slightly delayed an looks like its being dragged in a fluid animation. When the player stops moving the card sort of bounces or sways for a second.

I've been trying to find someplace that does this but I can't come up with anything so I'm wondering is it even possible in a 2d environment? How would I go about doing this, answers can be abstract, i.e. not cocos2d.

Thanks,

# Answer
When a card is selected, give it a target position. Then calculate a velocity proportional to the distance from where the card currently is and where it is going (i.e. the position of the finger). Then move the card by that velocity. By virtue of this system, the card will zoom across the screen and slow down as it approaches the finger.

The above should get you started, and can then be extended with concepts of forces, deceleration and so on, which will let your cards "bounce" and "sway".

Google "motion tweening" or "easing equations" for concrete examples of the math.

http://www.gizma.com/easing/ is a phenomenal source.
> 1 votes

---
Tags: 2d, animation
---


title: Changing background music smoothly

text:
# Question
Title: Changing background music smoothly
I've got five sounds now for a game I'm working on currently. In the game, you can fight against other civilizations in big battles, but you can also settle on planets in peace.

Some of the songs are more violent, while others are quite peaceful. The question is: what is the best practice for changing between the songs. Is it better if I just look "is it peaceful or not" when the old song ends and then play a new one or should I do that every single frame and change the songs immediately.

The first alternative would sometimes play silent songs in battles (because the song started before the battle and isn't finished yet) and the second one would switch between to different-fast songs properly at the wrong moments so the player would hear a cut.

So I'd like to know what is more natural for the player or if there is a different possibility.

PS: The songs are between 300 and 500 seconds long.

# Answer
There are actually some fairly standard approaches for designing music playback in a game. When designing a music playback system, problems you face involve creating smooth transitions, ensuring there is enough variety, and creating a sense of interactivity with the music. Your question title, "changing background music smoothly" tells me your main concern is transitions so that's what I'll primarily be addressing for each method.

## Method 1: Layers and Stems

One approach for creating smooth music playback systems in games, what Patrick Hughes called the "AAA way", is to build your music up in layers (also sometimes called stems) such that there's no single definitive version of the track. Instead, you might have a single base track running consistently, with melodic, rhythmic, harmonic variations that get played over it.

You usually (credit again to Patrick Hughes) build these around common motif that runs through each element layer in a piece of music, or even througout all music in the game. A good example of a non-melodic motif is Martin O'Donnell's use of the Phrygian scale in Halo games (http://www.1up.com/features/music-halo-reach). Normally, each of these component music tracks are aligned to be playing in sync on a timeline with each other. Although it is possible to create music layers that do not necessarily depend on a consistent tempo and synchronized timeline, or can work well in multiple tempo and timeline contexts.

Because each layer is designed to work together, it's entirely possible to have a single layered music track that just plays throughout the entire game, making slight transitions between layers within itself to signify game state changes.

## Method 2: Branching

You say you have music tracks already produced, so this implies you've already got a specific direction in mind: branching music. With branching music, your primary concern is the transition between music tracks that have been specified to play at particular sections of the game. You can achieve variety by breaking your individual music segments down into loops that have a couple of different versions, so that the same version never plays twice in two iterations and doesn't always start out the same way.

One way to handle transitions in simple branching music is to write more music that purely acts as a transition from these existing music tracks to others. Even if it's not feasible to cover every possible music transition, you can also use the "connector tracks" to make a music track end early in the case where you're trying to avoid simple fade-in, fade-out music changes.

## Method 3: CCC-Combo

It's also important to note that the two major approaches discussed here (layers and branching are what they're typically called) can coexist conceptually. "Branching" is such a simple term and description of what's happening that you could very well be branching between layered music systems. This often requires a semi sophisticated playback system, so you have to balance what's worth your time to implement.

## Method 4: Pragmatism and Simpler Music Playback

And, of course, you could always just fade-in and fade-out your music as needed. No shame if that's what feels right, or it's not feasible to write connector tracks. Better this than hard cuts to completely unrelated piece of music--that would sound pretty awful.

I'd also like to address your "silent songs" idea. It's not bad, but what happens when you start playing one 300-second track for 5 seconds, then you get immediately into a state where you need to transition to another track? Waiting for the remaining 295 seconds to go by seems impractical if you really care about making that music transition.

However, if the music is purely background music, and its fundamental purpose is to provide to simply set an overall mood, then "simple background music list" is a perfectly legitimate way to think about it. At this point you are talking about a music playlist like you'd build in iTunes or Windows Media Player (is that still at thing?) so you should implement it with that in mind.

## Further reading

To learn more about standard approaches for designing music playback in games, you should take a look at learning materials for two of the largest interactive audio middleware tools that see common use in the industry, FMOD and Wwise.

Wwise has good reference material on this page. The "Making Interactive Music for Games" article is especially good as it goes into further depth about the information I've written here. The FMODTV Youtube Channel has videos with Stephan Schutze that cover FMOD Studio as a whole--including the parts of it that can be used to design music playback systems. Learning how these tools approach this problem can help you think about how to address your own game's needs.
> 22 votes

# Answer
Length of songs is irrelevant. The AAA way is to have all the music built around a theme and then to fade in/out variants like your "more violent" and "quite peaceful" as needed. With the common theme the music just seems to flow, but it does take a good composer and a ton of production work.

The indie way would be to fade out the old music before fading in the new, you won't get hear the cuts and can have dissimilar musical pieces. I really like your "silent songs" idea, very good and will keep the player from getting fatigued even during normal play.

You don't want to check every frame, but only on state transitions like "a battle just started" and "I just lost" if at all possible. This is because of the next point:

For transitions you want to keep a timer so you don't porpoise back and forth, once you've changed to a new song let it play for at least that time.

Everything else about your question is a matter of taste and style and can only be decided upon by trying it out in the actual game to see how it feels. Fast transitions versus slow fades, how long are the silence gaps, how many transitions over time, how sensitive is the choice to transition, etc...

Audio isn't a slam dunk, and excellent audio is a thing of beauty.
> 6 votes

---
Tags: music
---


# Question
Title: Is point texture filtering the same as nearest?
Is point texture filtering the same as nearest (different names for the same technique)?

# Answer
Yes, they are different names for the same thing.
> 2 votes

---
Tags: textures, filtering
---


title: VFX for Unity sci-fi game

text:
# Question
Title: VFX for Unity sci-fi game
Can someone please give me any tips/ guides on how to create hologram, disintegration & freeze effects in Unity game? I have a sci-fi shooter game in mind, and I would like to incorporate the above mentioned effects in it.

I would like to achieve something like these:

* Holographic effect - ,
* Disintegration effect -
* Freezing effect -

And I would prefer to achieve these without using a premium plugin. Budget issues.

# Answer
> 1 votes
That disintegration effect is clearly some complex shader work, and the hologram shader on 3D models from your first link may be tricky too, but everything else is easily done with a cubemap and/or additive blending. For the computer monitors, that's just a standard texture in a material with additive blending. For the freeze effect, that can be done with a cubemap, and for that second hologram model you could do a cubemap AND additive blending.

---
Tags: unity, special-effects
---


title: Multiplayer matchmaking algorithm

text:
# Question
Title: Multiplayer matchmaking algorithm
I'm building a game in which there are tournaments. During the tournaments we want players to play against each other in an efficient way.

What I'm looking for is a generic algorithm that will match players together in an optimal way in order to:

* Have the lowest amount of games possible
* Be reasonably sure that after all games are played, the highest-ranked player is the best

Tricky part:

* Games can have 2, 3 or 4 players in a death match depending on the tournament.
* Tournaments have two or more players, no other constraints.

Does such an algorithm exist?

**Note**: For the ranking, I will probably be using an ELO-based algorithm (unless you have a better suggestion).

# Answer
> 2 votes
The Swiss Movement is a well-known tournament algorithm used in Chess, Bridge and Go tournaments (at least). It works similar to an elimination, except no-one gets eliminated; in each round, players/teams with an equal win-loss record are matched up subject to the constraint of not having played each other previously in this tournament. Clearly for a good result one wishes to have:
*number of rounds \> log2 (number-of-entrants)*;
however, having one greater number of rounds than required by this formula can at times give even better differentiation. For some types of games it is possible to enhance the scheduling even more by having a mild victory-point scale rather than pure win-loss for each match.

The mechanics of matching entrants at each round involve first sorting by win-loss record (or VP's if applicable), and then working from both ends to the middle. In case of a severe conflict near the end of the event (ie teams having to replay each other), Bridge tournaments have a policy of forcing this replay as far down the standings as possible, without creating another such conflict.

Also, to maintain interest at the low end, it is common in larger Bridge tournaments to take the bottom half of the entrants at the half-way point and start a second (new) event. (Better players have been know to term this *The Swamp*.)

In world-championship Bridge tournaments, a complex combination of qualifying Swiss, followed by double-elimination knock-out with *repechage* is used. I admit to never having explored the intricacies of this, but a search of relevant regulations for Bridge Olympiads (in particular) should provide details for this mechanism.

---
Tags: game-design, algorithm
---


# Question
Title: Why do some games need to be rated by game rating boards?
I don't know much about why the games are rated in the first place, aside from the fact that it may help customers to filter out the games that aren't appropriate for them due to age or personal preferences.

Are there any other benefits to completing the rating procedure of a game?

I wonder if it is required at all to have your game rated by a local rating board. And what about countries that don't have their own game rating boards?

# Answer
Looking at the ESRB FAQ, you can see some answers to your questions:

> **Are all games and apps required to have a rating?**
>
> The rating system is voluntary, although virtually all video games that are sold at retail in the U.S. and Canada are rated by the ESRB. Many U.S. retailers, including most major chains, have policies to only stock or sell games that carry an ESRB rating, and console manufacturers require games that are published on their systems in the U.S. and Canada to be rated by ESRB.
>
> The ESRB system has been voluntarily adopted by several mobile app storefronts in the U.S. as well, and complete rating information for all ESRB-rated apps is available by searching the ESRB website. While certain types of apps may be exempt from ratings, participating storefronts typically require that non-exempt apps receive an ESRB rating.

In short, if you want to release your game in retail form, and in some cases in digital form to some specific sites, you'll need to have ESRB rating for the retailers to consider your game for sale.

It's made clear that the system is voluntary. It's not required to sell your game, but it may be required by specific retailers to carry your game.

Not getting ESRB rating limits your options for selling your game, but doesn't restrict you from doing so entirely.
> 7 votes

---
Tags: content-rating
---


title: SlimDX: Error while loading Effect

text:
# Question
Title: SlimDX: Error while loading Effect
Im trying to load a effect in SlimDX, but I get a error when I try to get the ShaderSignature. The error-code:

```
E_FAIL: An undetermined error occurred (-2147467259)

```

This is my code:

```
   EffectTechnique tech = this.effects.GetTechniqueByIndex(0);
   EffectPass pass = tech.GetPassByIndex(0);
   ShaderSignature shaderSignature = pass.Description.Signature;

```

Any idea?

# Answer
> 1 votes
This error can mean:

1. You forgot to install the DirectX SDK.
2. You need to try reinstalling the DirectX SDK.
3. Depending on your other code, you need to install the Debug Runtimes (specifically if you're using `CreateWithSwapChain` from one of the demos). This could also help get you more information.
4. You'll need to debug more. There's a page of Debugging tips you can use to try and track down the real issue.

---
Tags: c#, slimdx, effect
---


# Question
Title: Ways to make my game world bigger without slowing users CPU
I've been developing my first game for a little while now, but I've found that I want to make the game world MUCH bigger. It's currently about 300\*300 tiles, but has creatures and bad guys running around the whole thing, so I've got to keep track of all the enemies movement and hostile-finding algorithms.

I'm wondering how I can scale something like this up? It seems (from code profiling) that enemies are the limiting factor, and it's mainly that for each enemy, I need to scan through all the player-units and creatures to see if they're close enough for the enemies to see/attack.

**Edit:** W,S,A,D,B,Q, if anyone's interested in controls :)

**Edit 2:** Please tell me if there's any way I could improve the question!

# Answer
Just ignore any actors which are far away from the player(s). Don't update them and don't allow active actors to interact with them.

Most games divide the game world into zones, and only update the actors in the zones the player is in and the adjacent zones. Many even despawn the actors and respawn them at their initial positions when the zone becomes active again to save memory.

When it is important for your game concept that certain actors do things while the player is away (for most games it is not), you could freeze the action in inactive zones, and when the player comes near calculate the activity in the zone which happened in the meantime using a simplified model. When you have, for example, an RPG with a blacksmith NPC who makes swords by automatically collecting resources and bringing them to his forge, the simplified model would not do the routefinding but just use an estimation how many swords he would have made during the time the player was away, remove the required resources from the surrounding and give him that number of swords.

When you have actors which travel around the whole game world and you want them to keep doing that even when the player isn't close (like in Oblivion or Skyrim), you could strongly simplify the route-finding while the player is away. When you know by experience that traveling from town A to town B takes about 20 minutes, you can treat this as a single step with a cost of 20 minutes in your route-finding system. When the player now suddenly enters the area between town A and town B, and the NPC left town A 15 minutes ago, you would calculate the actual path and spawn the NPC on 3/4 of its way towards town B.
> 8 votes

# Answer
You could also do something similar to MineCraft so only the active blocks are loaded. For doing that, you could store each part (e. g. 32x32 tiles) in its own file and load always only the part the player is in and the surrounding. When the player enters another part, save the parts the player is two far away and load the new ones. If you use procedural generated terrain, it wouldn't be too complicated to create endless worlds without using too much CPU (of course, the game may lag short when the new map parts are loaded).
> 4 votes

# Answer
As everyone has already stated, Spatial Partitioning! I think a bare minimal 2D Grid vs. Bounding Sphere will cut it for most browser games.

Since nearly everyone has multiple processors, your game might benefit greatly from Web Workers.

This way you can let the main browser thread focus on providing a perfectly responsive interface at all times. Further, to combat the artifacts caused by updating entities at a lower FPS, you can calculate velocities in your AI update, and then predict positions every render frame.
> 3 votes

---
Tags: ai, performance, optimization, browser-based-games
---


# Question
Title: Translate velocity to mouse curos position
I have particles, with a velocity (x and y) per tick. I would like to to make my cursor a gravity force, so particles fly to the cursor's position.

How can I apply gravity (that is towards my cursor position) on my velocity (x and y)?

# Answer
Just subtract the particle position from the cursor position to make the acceleration vector. Then multiply the norm with the gravity constant.

```
//pseudocode
GRAVITY_NORM = 9.8;
accVector = normalize(cursor.pos - particle.pos);
//Apply acceleration: S = S0 + v0*dt + 0.5*g*dt*dt;
accNorm = particle.vel*dt + 0.5*GRAVITY_NORM*dt*dt;
particle.pos = particle.pos + accVector*accNorm;

```

This computation actually doesn't calculates the gravity force, but the gravity acceleration (in Earth). If you want to get the real gravity force for a more general case you should attribute your cursor and particle with mass. However this system implies that you cursor should also be affected by the force and I'm assuming that it isn't your intention. Anyway, the equation for the force is

```
f = G * ( m1 * m2 ) * 1/r*r, where G is the gravity constant,
m1 and m2 are the masses and r is the distance between the bodies.

```
> 2 votes

---
Tags: mathematics, algorithm, particles
---


# Question
Title: swipe effect problem using only mesh and array - libgdx
I tried to combine matdesl's and libgdx's draw lines algo ang code. but i can only create a line.

problem is i want to make a fruit ninja swipe effect but only knows this... problem is i want to make a fruit ninja swipe effect but only knows this... anyone try to help me on improving just a line to have a swipe effect like fruit ninja?

```
    public class GameTouch {

private static final int MAX_LINES = 1000;
private OrthographicCamera camera;
private Mesh lineMesh;
private Vector3 unprojectedVertex = new Vector3();
private FixedList<Vector2> list;

public GameTouch(){
    this.camera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    lineMesh = new Mesh(false, MAX_LINES , 0, new VertexAttribute(Usage.Position, 2, "a_pos"));
    list = new FixedList<Vector2>();
}

public void update(float delta){

    camera.update();
    camera.apply(Gdx.gl10);

    if(Gdx.input.isTouched()){
        unprojectedVertex.set(Gdx.input.getX(), Gdx.input.getY(), 0);
        camera.unproject(unprojectedVertex);
        Vector2 input = new Vector2();
        input.x = unprojectedVertex.x;
        input.y = unprojectedVertex.y;

        if(list.size > 0){

            Vector2 temp = new Vector2();
            float sqlen = temp.set(input).sub(list.get(0)).len2();
            Array<Vector2> tempA = new FixedList<Vector2>();
            if(sqlen >= 3){
                list.insert(input);

            }

            lineMesh.setVertices(getVertices(list), 0, list.size * 2);

        }else{
            list.insert(input);
        }
    }else{

         if(list.size > 0){
            list.removeIndex(list.size - 1);
         }
    }
    if(list.size > 2){
        //lineMesh
        lineMesh.render(GL10.GL_TRIANGLE_STRIP);
        Gdx.gl10.glColor4f(0f, 0f, 1, 0.5f);
    }
}

private float[] getVertices(Array<Vector2> list){
    float[] vertices = new float[list.size * 2];
    int counter = 0;
    for(Vector2 vertex : list){
        vertices[counter++] = vertex.x;
        vertices[counter++] = vertex.y;
    }

    return vertices;
}

private class FixedList<T> extends Array<T>{

        public FixedList(){
            super(Vector2.class);
        }

        public FixedList(int capacity , Class<T> type){
            super(false, capacity , type);
        }

        public void insert(T t){
            T[] items = this.items;

            size = Math.min(size + 1 , items.length);

            for(int i = size - 1 ; i > 0 ; i--){
                items[i] = items[i - 1];
            }

            items[0] = t;
        }
    }
}

```

# Answer
> 0 votes
seems like the answer is already here. this problem is heavily outdated i have already found the solution.

just find its source code in github

---
Tags: libgdx
---


# Question
Title: Handling Multiple Items Interaction (in a 2-Players Game)
**Back Story**

I'm working on a 2-Players 2D game that players play multiple rounds ,until one win.

In each round, each player choose some items (1 or more) for his/her car ( e.g. shield, anti-shield, power-up, speed, ... ) and their chosen items are hidden for opponent. when both player get ready, they just sit and see what happen to their cars which move toward each other (each round).

**Problem**

As I said, there are multiple items (read "magics") with different effect in my game. Each Item's effect may differ depends on item which it interact with. each item have some positive effect and some cost.

> For instance, If player 1 uses "speed" item, his car may cause more damage to opponent's car ,whereas if opponent had used a "truck-bumper", this "speed" would cause player 1 to get more damage instead!

After writing all the rules and effects of each item on a paper, I need your helps to find a good and structural way to handle them in code (except many nested if-else ).

**Finally**

I need some kind of structure or coding style for converting these rules to code and determining the net result of items interaction in each round according to items relations.

# Answer
This is how I'd do it.

First of all, we will define methods for the interaction between cars which take into account two items only each. Note that this is not C++. All parameters are considered to be passed by reference.

```
void interaction(Car car1, Car car2);

```

A concrete example would be your Bumper vs. Speed interaction:

```
void bumperVsSpeedInteraction(Car car1, Car car2)
{
     if (car1.HasPowerUp(Bumper))
     {
           car2.TakeDamage(X);
     }
     else
     {
           car1.TakeDamage(X);
     }
}

```

Next, we're going to use an ADT like the *dictionary* to map `<PowerUp, PowerUp>` (where the first PowerUp belongs to the first car, and the 2nd to the 2nd car) pairs to pointers to interaction methods.

Example:

```
interactionForPair[new Pair(Bumper, Speed)] = bumperVsSpeedInteraction;
interactionForPair[new Pair(Speed, Bumper)] = bumperVsSpeedInteraction;

```

We notice that if we consider `<Bumper, Speed>` to be the same as `<Speed, Bumper>` and just check which car has which power up in the interaction method, we don't have to add a separate interaction method for each. Depending on how you implement the Pair class (more exactly if on equality check, `Pair(a,b)` equals `Pair(b,a)`), you can avoid adding both keys to the dictionary.

Since I'm not clear why both cars would take damage if they both had *Bumper* and *Speed*, I'm not exactly sure how it would be appropriate to continue from here. In the end, however, you should have two cars, each with a list of active power ups.

```
Car1
{C1PowerUp1, C2PowerUp2}

Car2
{C1PowerUp1, C2PowerUp2}

```

Then, you'd have to apply some rule to decide which power up gets to fight which of the others. Suppose our rule tells us C1PowerUp1 gets to fight with C2PowerUp2. You'd then do:

```
Pair = MakePair(C1PowerUp1, C2PowerUp2); //Make a pair with the two power ups.
interactionForPair[Pair](Car1, Car2); //Call the appropriate method for this pair.

```

Any of the power ups can be `null` or a special constant defined by you which means the power up does not exist (if both cars are fighting without power ups, both pair elements would be null).
> 3 votes

---
Tags: c++, architecture
---


# Question
Title: Best practise for representing large spaces in a scene graph
I'm attempting to represent a procedurally generated world in a scene graph, specifically in the Jmonkey engine (Jme3). To make this managable I have broken up the world into smaller chunks. Each chunk consists of a triangle mesh of the relevant piece of terrain. (A Geometry object holding the mesh and the relevant texture.)

I can't find any information however on which way is best to represent these within a scene graph, specifically how to deal with the coordinates of the map & camera.

One way of doing it would be to simply add these pieces on their world coordinate (which could get extremely large) detaching any nodes that are not within range of the camera and moving the camera trough this theoretically-infinite space. This would be very convenient but can the scene graph deal with the currently rendered scene having very large coordinates? The translations on each piece could easily go into the millions or more "distance units" on the graph's axis.

Another method that comes to mind is converting the world coordinates to a smaller local space and move the terrain that is being rendered to stay close to the origin of the scene graph. Essentially moving the world around the camera.Possibly moving the whole structure along with the camera 1 chunk in the opposite direction to keep it centred whenever a chunk border is crossed. However this seems like it could also have a large impact on performance.

Which of these options, or possibly a completely different one, would be preferable to represent the world in terms of CPU/GPU usage?

# Answer
> 8 votes
You can easily have coordinates going into the millions on units with an int. You can go all the way up to 2,147,483,647 units in the positive or negative direction. Procedurally generated worlds are not *actually* infinite. They're just very very big. If you think that 2 billion isn't enough, use a long to store your chunk coordinates, then you can go up to 9.223372e+18 units. So, if your units were meters it would take a character 974.9 years to reach the bounds of your world *traveling at the speed of light*.

The scene graph can deal with longs no problem. You still want to limit the bounds of your scene to only the chunks within the area around your camera.

It's worth noting that using a float will make you loose accuracy at large distances, which can cause some funky issues. However, you can still make pretty large worlds with floats. But if you can stick with integer values (which I assume you can, since you're choosing the chunk size), do it.

See this question for a similar issue.

# Answer
> 0 votes
One solution would be to move the center of your scene, which would require to move back your chunk once you change the center.

---
Tags: terrain-rendering, scene-graph, jmonkeyengine
---


# Question
Title: Continuous world and very large levels: going around the FPU limitations with Ogre3D
I'm currently using Ogre3D, and I'm wondering is it's possible to have a very large level (hundreds of kilometers) using the right scenemanager. Storing or having the level is not a problem, since I can repeat objects in a procedural fashion, my objective is level size, not quality.

Taken from http://floatingorigin.com/mirror/continuous-world.htm :

Imagine two characters walking in formation two meters apart heading east away from the origin. At some point, the distance from each other is overwhelmed by the distance from the origin, and the characters will appear to be “at the same location”.

I'm wondering if solutions for those problem like the one described in the Dungeon Siege article are the only viable ones, and if it requires a deep engine modification or not. I'm not sure the paged scenemanagers or PCZ scenemanager reset the zero like I think.

# Answer
> 5 votes
Yeah you can have a massive world. But you're going to need to partition it spatially for a variety of reasons.

* Floating point accuracy tails off
* It becomes computationally impractical to update deterministic objects across a massive world without some form of spatial separation
* Networking becomes increasingly more difficult the more distance between players. especially as deterministic items need to be simulated in order to maintain determinism.
* You dont want to be culling 99% of the geometery you have in memory every time you render ;)

---
Tags: c++, ogre, floating-point
---


# Question
Title: Unable to Render to multiple rendertargets
I am trying to implement a simple deferred rendering engine in openGL and i have a little problem with the GBuffer. I cant get it to render to more than one texture at a single time, which is the one attached to GL\_COLOR\_ATTACHMENT0.

GBuffer initialization code:

```
    glGenFramebuffers(1,&m_FBO);
glBindFramebuffer(GL_FRAMEBUFFER,m_FBO);
//create Gbuffers
glEnable(GL_TEXTURE_2D);
//create diffusemap
glGenTextures(1,&m_Textures[GBUFFER_DIFFUSE_24]);
glBindTexture(GL_TEXTURE_2D,m_Textures[GBUFFER_DIFFUSE_24]);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,m_Width,m_Height,0,GL_RGB,GL_UNSIGNED_BYTE,0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,m_Textures[GBUFFER_DIFFUSE_24],0);
if(!glIsTexture(m_Textures[GBUFFER_DIFFUSE_24]))
    return false;
//create normalmap
glGenTextures(1,&m_Textures[GBUFFER_NORMAL24_MATID8]);
glBindTexture(GL_TEXTURE_2D,m_Textures[GBUFFER_NORMAL24_MATID8]);
glTexImage2D(GL_TEXTURE_2D,0,GL_RGB32F,m_Width,m_Height,0,GL_RGB,GL_FLOAT,NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,GL_TEXTURE_2D,m_Textures[GBUFFER_NORMAL24_MATID8],0);
if(!glIsTexture(m_Textures[GBUFFER_NORMAL24_MATID8]))
    return false;
//create depthmap
glGenTextures(1,&m_Textures[GBUFFER_DEPTH32]);
glBindTexture(GL_TEXTURE_2D,m_Textures[GBUFFER_DEPTH32]);
glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH24_STENCIL8,m_Width,m_Height,0,GL_DEPTH_STENCIL,GL_UNSIGNED_INT_24_8,0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glFramebufferTexture2D(GL_FRAMEBUFFER,GL_DEPTH_STENCIL_ATTACHMENT,GL_TEXTURE_2D,m_Textures[GBUFFER_DEPTH32],0);
if(!glIsTexture(m_Textures[GBUFFER_DEPTH32]))
    return false;
GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0,
                        GL_COLOR_ATTACHMENT1};
glDrawBuffers(2,drawBuffers);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

if(status != GL_FRAMEBUFFER_COMPLETE)
{
    printf("FBO error!!, status: 0x%x\n",status);
    return false;
}
glBindFramebuffer(GL_FRAMEBUFFER,0);

```

And then before i render all geometry i do this:

```
            glClearColor(0.2f,0.6f,0.3f,0);
    glBindFramebuffer(GL_DRAW_FRAMEBUFFER,m_FBO);
    GLenum drawBuffers[] = {GL_COLOR_ATTACHMENT0,
                            GL_COLOR_ATTACHMENT1};
    glDrawBuffers(2,drawBuffers);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT| GL_STENCIL_BUFFER_BIT);

```

And then after i rendered all of it i blit it to the normal framebuffer:

```
            RenderGeometry();
    glBindFramebuffer(GL_FRAMEBUFFER,0);
    glClearColor(0.0f,0.0f,0.0f,0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT| GL_STENCIL_BUFFER_BIT);
    glBindFramebuffer(GL_READ_FRAMEBUFFER,m_GBuffer->GetHandle());
    glReadBuffer(GL_COLOR_ATTACHMENT0);
    glBlitFramebuffer(0,0,1280,720,
        0,0,640,370,GL_COLOR_BUFFER_BIT,GL_LINEAR);

    glReadBuffer(GL_COLOR_ATTACHMENT1);
    glBlitFramebuffer(0,0,1280,720,
        640,370,640,370,GL_COLOR_BUFFER_BIT,GL_LINEAR);
    glfwSwapBuffers(m_Window);

```

And my fragment shader code is:

```
    #version 430

    in vec2 Tex;
    in vec3 Normal;

    uniform sampler2D   tex1;
    uniform bool        UseTexture;

    layout(location = 0) out vec3 FragmentColor;
    layout(location = 1) out vec3 FragmentNormal;

    void main()
    {
FragmentNormal.xyz = normalize(Normal);
if(UseTexture)
{
    FragmentColor = texture(tex1,Tex).rgb; //diffuse color
}
else
{
    FragmentColor = vec3(1,1,1);
}
    }

```

And the result is:

It should be two rectangles drawn to the screen one containing the diffuse color and one containing the screen normals. However i am only getting one.

# Answer
> 2 votes
You are blitting your normal buffer into a 0x0 rectangle when you use:

`glBlitFramebuffer(0,0,1280,720,640,370,640,370,GL_COLOR_BUFFER_BIT,GL_LINEAR);`

You are also wasting memory bandwidth by writing your normals using 32-bit floating-point. You can get away with 8-bit fixed-point most of the time, and when you cannot you should try an RGBA\_10\_2 or half-float (16-bit) format before jumping straight to 32-bit floating-point.

Also, make sure to bias and scale your normals before showing them on screen for the purpose of visual inspection. They can have negative values, which will be outside the visible color range. The normal way of tackling this is to multiply by 0.5 and add 0.5.

Judging by the name you're using for your texture ID, you probably meant to use an RGBA8 format for normals and pack the material ID into the A channel. In which case you need to write your normals the way I described above and then unpack them using: `normal = 2.0 * (normal - vec3 (0.5))`

---
Tags: opengl
---


# Question
Title: Painting terrain with a selection circle
I don't mean putting a circle under a unit like done in an RTS, that's fairly simply done with a scenegraph(-like structure). What I'm referring to is selection circles for things like Area of Effects that are painted on the terrain.

It seems relatively simple until I think about it.

Here are some images for reference:

https://i.stack.imgur.com/iXWXB.jpg http://im.tech2.in.com/images/2009/jan/img\_116282\_initialthreat\_640x360.jpg

The first image gets the idea across, but not the full scope. Basically, the floor is painted with a decal detailing the region that will be affected by the spell.

The second image gets it across much better, it's not just a flat painted circle, it wraps along the mesh.

At first I figured to use some sort of object selection, and then in the vertex shader draw the texture on the correct vertices based on... some criteria that I'm still working out. Most likely based on distance and angle from the intersection point. The difficulty seems to come in that the methods wrap onto objects that seem to be completely different meshes.

I can't find an image that shows it (and don't play WoW anymore so I can't take a screenshot), but say you have a terrain mesh and a house on top of it and I select a point very close to the house's wall. Instead of continuing on the terrain mesh, the selection circle will go as far along the terrain mesh as it can, and then wrap up onto the wall of the house. It also ignores certain objects (players, etc), but that's pretty easy to ignore with correct collision tags/callbacks.

It's not so much that I can't think of a way to do this, but all the ways I can think of would probably lag your game out or turn your processor into slag. Somehow I have to:

1. Draw a texture
2. With no breaks
3. Wrapping on multiple objects according to the terrain
4. Centered at a given point
5. Completely dynamically (so no pre-baking it into a bunch of dummy textures)
6. Quickly enough to be computed every frame

Is there a standard method for this? Am I just overthinking it?

My best guess is rather than do one ray cast and selecting that point as the "center" I do a **bunch** of casts and in each case select the nearest vertex and bind the appropriate UV coord to that vertex, but it seems messy and potentially performance heavy to select that many vertices that way at the CPU frame-by-frame level. Especially since ray casts in general are expensive, even with a good physics engine.

It also doesn't seem particularly portable to anything other than a selection circle. A similar case would be like drawing the movement arrow over the terrain in Total War games, a thick arrow is drawn between the unit and its destination (see here: http://webguyunlimited.com/pixelperfectgaming/wp-content/gallery/total\_war\_shogun\_2\_rise\_of\_the\_samurai/total\_war\_rots\_screenshot\_014.jpg ), this would seem to be a very similar technique to the AOE selection circle, but the ray cast method I mentioned wouldn't really work for it. There are, of course, numerous other examples too (such as trajectory markers).

# Answer
Overthinking is an understatement! In your case it's especially easy, just Offset and Scale.

To get an orthogonal projection looking down Y axis, simply discard Y component. Your (unprocessed) texture coordinate \[X,Y\] is your world position \[X,Z\]. Now offset, scale, and limit to control the effect.

Here is a pseudo GLSL example of an effect like the one in your links:

```
        // These should of course come from somewhere in your pipeline
vec2 SelectionPoint = vec2(0.5, 0.5);                //Red X
vec2 SelectionRadius = vec2(0.3, 0.3);               //White Box Radius
vec2 TopDownWorld = (ModelMatrix * gl_Vertex).xz;    //Blue X

        // This is a simplification of the projection, since you are axis locked.
vec2 ProjectedTexCoord = TopDownWorld;
ProjectedTexCoord -= (SelectionPoint - SelectionRadius);
ProjectedTexCoord /= SelectionRadius * 2.0;
vec4 ProjectedTexel = texture(SelectionTexture, ProjectedTexCoord);

        //* Stop the texture from repeating forever
if (ProjectedTexCoord.x > 1.0 || ProjectedTexCoord.x < 0.0 ||
    ProjectedTexCoord.y > 1.0 || ProjectedTexCoord.y < 0.0) {
        ProjectedTexel.a=0.0;
}
        /*///* A bit cleaner but less academic:
if (ProjectedTexCoord != fract(ProjectedTexCoord)) ProjectedTexel.a=0.0; //*/

        // Alpha blend the projected texture onto the final pixel color
gl_FragColor = gl_FragColor * (1.0 - ProjectedTexel.a) +
               ProjectedTexel * ProjectedTexel.a;

```

Note that ModelMatrix is NOT gl\_ModelViewMatrix (which is ViewMatrix * ModelMatrix)

Now for an example: (red X is the selection, blue X is the pixel we are shading) Lets work through some now, we are the pixel shader for the blue X

```
[0.75, 0.0] is our world coordinate
[0.5,  0.5] is our selection point
[0.3,  0.3] is our box radius

```

Or Simpler:

This gives our texture coordinate as \[0.916, -0.3\], which has a Y component less than zero, so the pixel is hidden using alpha=0. Although the X component is inside the box, near the edge (as you can see in the picture)

---

Now lets follow our selection point, which should clearly be right in the middle of the texture:

and it is :)

---

One more, to drive the point home, is the top right corner of the box where the answer intuitively should be \[1, 1\] because it's the top right corner ;)

and again it is
> 3 votes

---
Tags: textures, algorithm, rendering
---


# Question
Title: When in the development process should the programming start and what should be programmed first?
I think the title really says it all.

Should I start programming after designing the basic outline of the game or should I have the whole thing written out?

If I write the whole thing out isn't that waterfall development and isn't that bad?

What principles should I follow or steps should I take in order to keep my code up to date with the design and vice versa?

# Answer
> 2 votes
Depends on development methodology the fast answer is "When you have enough information to begin writing code".

My thinking on what "enough" should be is something like ...

1. I wont be rewriting large portions later.
2. What i'm writing is a small enough chunk that i can handle it as a "task".

I see so many people taking on tasks like "build the terrain" ... that's such a wide scoped task that it could take weeks and you have no idea of weather you are wasting your time or not. I would go with smaller tasks like ...

1. investigate potential options for terrain generation.
2. implement a proof of concept.
3. design the solution.
4. Begin development on terrain component (basic form only).
5. Add trees, buildings ect to terrain.

This works for me because I take an agile approach to my design, I pick up a small chunk of my project at a time and build it, then move on to the next.

Waterfall based development means you must have the full details of your project from start to finish before you begin. My experience is that this is falling out of favour in all but the most elongated dev processes because of the time taken to plan such a project. Typically waterfall based dev process involves just as pmuch planning time up front as the dev time that follows.

Simply put ... Waterfall: Planning time - 1 year Dev time - 1 year

Scrum / agile: Planning time - 1 week dev time - 2 weeks

You also have to factor in testing time and other process based time allocations (proof of concepts, meetings, design time, delays).

My advice (best i can give) ... Build a plan for a unit of work, then build to that plan. If the plan needs to change you should stop all development work and consider the impact of the change, update your plan then begin again.

Once the unit of work is developed ensure it gets thoroughly tested then repeat.

The agile approach (it works well for me).

# Answer
> 0 votes
It's a judgement call.

Advantages of starting coding early:

* You get stuff done on the coding front
* You create energy, enthusiasm and momentum in your team
* You can prototype to help you learn and solve technical / implementation issues
* Game design can benefit from frequent iteration. You need to build something to get that iterative loop going.

Advantages of waiting (i.e. doing other stuff first):

* You reduce the risk of producing a really badly designed monstrosity that ultimately needs to be thrown away.
* You might need to take important decisions (which game engine to use? is it multiplayer or not?) that fundamentally change how you build the game. No point starting until you've made these decisions.
* You reduce the risk of wasting time working on something that ultimately isn't needed

Overall, my recommendation would be to start coding pretty early, but *only for things that are properly designed* (which includes *understanding* the design, especially if you are part of a big team). If you're coding blindly on aspects of the game that haven't yet been properly designed, you will definitely get into trouble.

# Answer
> 0 votes
I'd say as soon as possible, simply because that is when you discover if you're cut out to program a game all by yourself (or in a group or whatever).

I've known so many people that were to create a game, that made super convoluted design documents and "concept art" (for characters that were supposed to be rendered in skin shaders, meaning that they had be rigged and modeled, something they thought was as easy as drawing an picture). None of them ever got past coding a single line of code.

Thinking about what cool game you want to do is easy, implementing it is hard, and that is when you discover if you're cut out of it.

I've made several games, all of them are shit, but at least I've implemented an idea I had from the start, making my own game art and stuff, and I had really fun doing it. That's more than can be said about my douchebag friends that were to make revolutionizing games that were supposed to turn the whole game community upside down. I don't want to sound like a downer, but don't underestimate how much time it takes to make a game, and it's not the design part that takes time.

---
Tags: software-engineering, planning, time-management
---