# Question
Title: If two objects interact, what holds the interaction code?
Think of a bullet and an enemy, or the player and the floor. If these objects interact, what holds the interaction code?

# Answer
**TL;DR:**

Your game objects do not know about each other, nor do they perform checks against other objects. You create a collision detection and collision resolution pattern that checks your game objects and performs the appropriate actions to simulate your game physics.

**The Good Stuff**

From previous attempts at writing collision detection and reading this book, there are two stages for collision detection and collision resolution. The first stage (collision detection) is an early-out pass where you determine if two objects may have a potential collision. Should any two objects form a potential collision, you then pass these objects into the second stage (collision resolution) to run a more fine grained check against the objects and attempt to resolve the collision.

Somewhere in your engine/game, you will hold an array of all the objects in your world. On each frame you would loop though the array and check each object against every other object with a simple bounding box/sphere collision detection.

Pseudocode:

```
dectectCollisions(objects)
{
    for(objectA in objects)
    {
        for(objectB in objects)
        {
            if(objectA != objectB) //ignore self
            {
                if(BoundingSpheresIntersect(objectA, objectB))
                {
                    collisionResolver.addObjects(objectA, objectB);
                }
            }
        }
    }
}

```

This kind of loop is rather inefficient but does leave room for improvement via use of spatial partitioning as an early-out for objects that are guaranteed to be too far apart to collide.

After checking the two objects for a potential collision (i.e. both objects are close enough to collide), the objects are passed off to perform a more precise collision detection routine.

Imagine you have two polygons of random shapes and sizes that are close enough to potentially intersect but do not due to their geometry:

Using bounding spheres, these two objects would create a false positive for a potential collision. This is where you would then perform a more thorough pass to determine whether the two objects do actually intersect.

Once you have found a true collision, your collision resolution step would then perform the appropriate action to resolve the objects by applying forces or moments depending on the granularity and needs of your game physics.

With this in mind, you can abstract the entire process of collision detection and resolution so that your objects need not know anything about each other, nor the process required to determine and resolve collisions. The two classes/managers that handle this for you only need to know the basic properties of each object to perform a quick and dirty check for collisions and then a more thorough check should it be required.
> 23 votes

# Answer
One way Unreal Engine 3 handles it:

The bullet gets a collision message saying it hit something, with an argument telling it what it hit. It can then call objectHit.takeDamage(self). The target then gets the TakeDamage message, with a pointer to the thing that hit it, and takes the appropriate action.

I personally like this approach because it means the bullet can take special actions (like making some sort of explosion effect depending on the type of thing hit) and the target can take special actions depending on the type of bullet.

It's also possible that the bullet knows what it does to targets, and can call function on it, like objectHit.freeze(self). Then the target knows it got hit by something that freezes it, and what kind of object that was.

EDIT: This answer is meant as a general picture of how it can work, since you're probably not working with UE3. :)
> 12 votes

# Answer
Thief did this very well in the Dark Engine with Sources and Receptrons. An object could have both of these properties, with different types. For example, a Water arrow would have a Source for WaterStim on contact. An explosion would have an AoE FireStim.

When a Water Arrow hits an object, the target object then searches its Receptrons for anything looking for a WaterStim with the appropriate intensity values. Then it executes whatever command is associated with it (in this case, turning a burning torch to an off torch, and emiting a puff of smoke.)

Since the same engine is used in SystemShock2 this is how all the different damage types are handled, different bullets have different Stims set, and different monsters then have Receptrons for the different Stim types and do damage equal to 1\*, 2\*, 1/2 the intensity depending on if the ammo type is "super effective" or not.

It seemed like a very flexible system as you could add sources and receptrons to objects in the level editor, (to make a one-off door which opens if hit by fire, say.) While you could also tell a receptron to "send script message" if the object had special scripts associated with it.

What you don't want to do is have to hardcode an nXn interaction matrix of all possible objects colliding with all possible objects! BY generalising interactions through standardised messages, you simplify the process.
> 10 votes

# Answer
One solution is to keep the containers of bullets and players in separate classes, and then have main() function which keeps the frame loop responsible for interaction.
> -2 votes

---
Tags: architecture
---


# Question
Title: How to grab textures from a texture atlas to be applied to 3d objects
Fairly basic question, but I'm having trouble on finding information on this sort of thing for beginners. I'm just trying to make cubes with different textures on the sides as a starting point. I have downloaded the source code for an 'infinite' cube engine that is similar to minecraft (this particular one is called TechCraft).

I am simply having trouble finding where the textures are actually being applied and how they are being grabbed and when and blah blah. Here is the code I am currently using:

```
   public void Draw(GameTime gameTime, bool underWater)
    {
        BoundingFrustum viewFrustrum = new BoundingFrustum(Game.Camera.View * Game.Camera.Projection);

        _game.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

        _game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        _game.GraphicsDevice.BlendState = BlendState.Opaque;

        _solidBlockEffect.Parameters["World"].SetValue(Matrix.Identity);
        _solidBlockEffect.Parameters["View"].SetValue(Game.Camera.View);
        _solidBlockEffect.Parameters["Projection"].SetValue(Game.Camera.Projection);
        _solidBlockEffect.Parameters["CameraPosition"].SetValue(Game.Camera.Position);
        _solidBlockEffect.Parameters["AmbientColor"].SetValue(Color.White.ToVector4());
        _solidBlockEffect.Parameters["AmbientIntensity"].SetValue(0.8f);
        _solidBlockEffect.Parameters["FogColor"].SetValue(Color.SkyBlue.ToVector4());
        _solidBlockEffect.Parameters["FogNear"].SetValue(WorldSettings.FOGNEAR);
        _solidBlockEffect.Parameters["FogFar"].SetValue(WorldSettings.FOGFAR);
        _solidBlockEffect.Parameters["BlockTexture"].SetValue(_textureAtlas);

        foreach (EffectPass pass in _solidBlockEffect.CurrentTechnique.Passes)
        {
            pass.Apply();
            for (int x=0;x<REGIONRATIOWIDTH;x++)
            {
                for (int y=0;y<REGIONRATIOHEIGHT;y++)
                {
                    for (int z=0;z<REGIONRATIOLENGTH;z++)
                    {
                        Region region = _regions[x,y,z];
                        if (region.BoundingBox.Intersects(viewFrustrum))
                        {
                            if (region.Dirty) region.Build();
                            if (region.SolidVertexBuffer != null)
                            {
                                _game.GraphicsDevice.SetVertexBuffer(region.SolidVertexBuffer);
                                _game.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, region.SolidVertexBuffer.VertexCount  / 3);

                            }
                        }
                    }
                }
            }
        }

```

And here is the SolidBlockEffect class:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

float4 AmbientColor;
float AmbientIntensity;

float3 CameraPosition;

float FogNear = 250;
float FogFar = 300;
float4 FogColor = {0.5,0.5,0.5,1.0};

Texture BlockTexture;
sampler BlockTextureSampler = sampler_state
{
    texture = <BlockTexture>;
    magfilter = POINT;
    minfilter = POINT;
    mipfilter = POINT;
    AddressU = WRAP;
    AddressV = WRAP;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TexCoords : TEXCOORD0;
    float Shade : TEXCOORD1;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoords : TEXCOORD0;
    float3 CameraView : TEXCOORD1;
    float Shade : TEXCOORD2;
    float Distance : TEXCOORD3;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    //output.Position.x += RippleAmount * sin(RippleTime + (output.Position.y));

    output.Shade = input.Shade;
    output.CameraView = normalize(CameraPosition - worldPosition);
    output.Distance = length(CameraPosition - worldPosition);
    output.TexCoords = input.TexCoords;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 texColor = tex2D(BlockTextureSampler, input.TexCoords);

    float4 ambient = AmbientIntensity * AmbientColor;
    float fog = saturate((input.Distance - FogNear) / (FogNear-FogFar));
    float4 color =  texColor * input.Shade * ambient;

    return lerp(FogColor, color ,fog);
}

technique BlockTechnique
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

So, I don't know if the texture is being picked from the texture atlas during the effect pass or what. If someone could please shed some light on how this code might be working.

I guess if it helps, my goal is to be able to draw my own texture atlas and tell the code what texture I want a particular cube face to use. And if this isn't enough code please tell me what I need to add!

The source code: https://techcraft.codeplex.com/

# Answer
> 1 votes
Before \`myVertexBuffer.SetData(vertices);' is called you need to set the 'TextureCoordinate' for each vertex. You will want to make 9 squares between 0-1 where 0,0 is the TL of you texture and 1,1 is the BR.

Example textcoords for the topleft most square. This would grab the top left 1/9 of a texture. ((0,0),(0,1/3),(1/3,0)),(((0,1/3),(1/3,1/3,(1/3,0)))

You are probably going to have to alter the library you are using.

http://msdn.microsoft.com/en-us/library/bb464051(v=xnagamestudio.10).aspx

Edit: You way of aproaching this is a little backwards of reality. You don't fetch textures from an atlas and apply them to a 3d model. The 3d model's verts contain the uv data and pull it from the texture.

---
Tags: xna, 3d, xna-4.0, effects, texture-atlas
---


# Question
Title: What is a good way to determine if a vector is between two other vectors in 2D?
I could operate with the angles, but I do not have the angles calculated yet (and would like to avoid having to do that). It would be possible to calculate and cache the local-coordinate-frame angles, though.

This is a routine that is run on every vertex of every convex polygon within the convex decomposition of every physically simulated object, so it should be as fast as possible.

I've got a corner of a convex polygon, so I have a vector from vertex to vertex-1 and another vector from vertex to vertex+1. It is easy to see that for a convex polygon, the interior of the polygon lies in the direction of the average of these two vectors.

I want to determine given any vector whether it points into that region or outside of it. Can I accomplish this using only cross products and dot products and similar fast operations? I am thinking about eventually offloading these calculations to a vertex shader, but as it changes the number of vertices required depending on an object's velocity, I imagine the logic could get dicey. Either way, before I attempt a vertex or geometry shader implementation I had better get a CPU solution working correctly first.

Here's an example: I want to find if N is between A and B. A points right at -10 (=350) degrees, B is at 15 degrees. So it looks somewhat like the \< symbol. Function should return true only if N is between -10 and 15, between 350 and 375, etc. This was just to paint a mental picture, the input to the function are vectors: I want to avoid operating on angles because I do not want to call atan2.

It may help if it is known that A cross B is always positive. This is the case because my polygon is CCW winded and convex.

# Answer
I think the best way to solve this, given A x B \> 0, is to simply check A x N and N x B are also both positive. It seems to be working well.
> 5 votes

# Answer
Endpoint vectors A and B, in 2d space. Third vector, C, might be somewhere between them. This is what we are checking for:

```
if (A + (B - A) * (Distance(A, C) / Distance(A, B)) = C)
    // line segments intersect.

```
> 0 votes

---
Tags: 2d, mathematics, vector, geometry
---


# Question
Title: Circle vs Edge collision detection / resolution
I made a javascript class Ball.js that handles physics interactions betweens balls as well as painting. In the v1.0, the ball vs ball collision detection and resolution is well handled.

In the next version (v2), I'm trying to add edgeCollision handling. I'm having some problems, maybe you will be able to help me.

All the v2 branch source code is on github repository : https://github.com/topheman/Ball.js/tree/v2

The v2 demos (where you can see the bug I will be talking about) : http://labs.topheman.com/Ball-v2/#help

As you will see on the demo, I have two major problems that I'm having a really hard time to solve on Ball.js :

* method `resolveEdgeCollision` : bounce angle is inconsistent
* method `checkEdgeCollision` : if the ball's velocity (the length that it runs each frame) is higher than its diameter, eventually, it will pass through an edge, without triggering any collision

Any Ideas ?...

# Answer
> 0 votes
The way I've written circle vs line collision before is to modify the problem somewhat:

1. Change the circle into a point.
2. Add the circle's radius to the line. That gives you one circle at each end, and two straight line segments joining them.
3. You can now cast a ray from the previous position to the next position, and test it against the lines and the circles. The earliest collision time from those four tests is the one you want to use.
4. If the ray intersects either a circle or line, it's fairly simple to calculate when and where that collision occurred, and resolve it.

# Answer
> -1 votes
Circle to polygon collision detection devolves into edge vs circle. I wrote about it here: http://gamedev.tutsplus.com/tutorials/implementation/custom-2d-physics-engine-oriented-rigid-bodies/

The idea is to find if the ball's center is closest to a vertex or the edge segment itself. From there deriving resolution information is trivial.

---
Tags: collision-detection, collision-resolution
---


# Question
Title: Using Renderscript for game development on android
Does any one know anything about using Renderscript for game development in Android 3.0. If you know, can you provide some good examples or demo links?

# Answer
> 1 votes
Don't use Renderscript for gamedev. It doesn't use GPU today and it is not portable. libgdx author has tried Renderscript and there is an interesting debate.

# Answer
> -2 votes
render script may is depreciated as a graphics library, but it may still be useful if you are using it to calculate physics or other parallelized tasks.

---
Tags: android
---


title: Glowing Sprites

text:
# Question
Title: Glowing Sprites
I really enjoy the simple sprite style that is just shapes + slight glow effect. Cipher Prime uses it a lot in their games.

I was wondering how this effect was achieved. Is the sprite itself just have a blur effect or is there some sort of post processing effect at work here?

# Answer
> 1 votes
Well, you can have it built into the sprite, but typically to render blurs one must use shaders to achieve this effect. (theres many tutorials online). Another way is to perhaps render a stretched version that will, depending on the stretching method, give a blurred effect. And then, to give appearance like above, re-draw the image non-blurred/stretched above that.

---
Tags: sprites, art
---


# Question
Title: Crowdfunding an indie game. What should I offer back?
I have seen many indie games making money for development using crowd funding (Kickstarter, IndieGoGo, et cetera). Some of the games will offer something back. For example, in an RPG game, you might get an NPC character based on you. Some other projects simply give you the final version for free.

Apart from actually finishing the game, which is probably the main reason why anyone would want to give you the money, what should my reward strategy be?

# Answer
> 19 votes
First of all you obviously need a game that people would want to play. Without that, no matter what you offer you will likely not get much support. So lets assume you have such a game and now you want to attract people.

Looking at the most successful game projects on Kickstarter (like Torment: Tides of Numenera or Planetary Annihilation) you will see a common pattern:

* full game for some basic pledge (about 15-25$) - this is the bread and butter and kind of obvious. You simply offer the game for "retail" price.
* full game + some goodies (soundtrack, artwork, developer diary) for a bit larger pledge - might not be the best thing for an indie game (i doubt you are going to bring a world class composer to make a soundtrack for you, but hey, who knows?) but you can still consider this.
* full game + goodies + slight involvement in development - now this is what you should probably definetly do. Allow the early backers to get into some "backers only" forum where you can discuss game design, where they can come up with suggestions etc. A bit of a higher pledge should ensure you will get only people seriously interested in your game which will not flood your forums with bad ideas.
* full game + goodies + more involvement in development - allow them to name characters or something, add them to credits. Many people like this kind of things and are willing to pledge quite a bit of money. And its also a nice thing to do.
* full game + goodies + early alpha/beta access - this is pretty much self explanatory. If someone is willing to invest so much into your project you should really allow him to see the product as soon as possible so he can see how good his investment was!

Obviously, depending on the size of your project some things might not be doable for you, but i think the general idea is clear. If you can also have some stretch goals which will up the tension as the funding campaign progresses that can help a lot too.

Best of luck!

# Answer
> 17 votes
I don't have hard data to back this up, but I firmly believe that offering a copy of the game as a reward is actually a *bad* plan from a long-term perspective. It can effectively soft-caps your sales, and since it's often the lowest reward level, similarly restrict your capital.

The Kickstarter (or what have you) campaign will act as a marketing push for your product, through which you'll generate some word-of-mouth and a grassroots fan base. If you offer what is essentially a pre-order, then you're burning a huge portion of that grassroots activism because your game isn't actually available yet, and you won't let that interest reach its full potential. Thus, you'll have a localized clique of fans who are very interested now, drive some "sales," but then don't gain you a whole lot until the game ships months later, and which point they may have mostly moved on and won't be as likely to help drive actual sales.

Additionally, offering pre-sales as a donation reward restricts a lot of your flexibility in adjusting your initial sale price to help cover and cost overruns you will have inevitably had during development.

To offset some of the "sticker shock" potential donators may feel by not having a pre-sale reward, you could offer to make their donation "count" towards the purchase of the final product when it ships (although this will likely involve management overhead on your part to support).

Obviously, the ideal reward in a crowd-funding pitch costs you *much* less than it costs the donator. Ideally it costs you nothing, but that's impractical once you factor in the opportunity cost of your time. You also want to eek the most value out of that donator's mindshare, so things that can keep them engaged during the development cycle are good.

Cheap things you can offer involve things you already have to do yourself (mainly oriented around content creation):

* Naming NPCs after donators or putting their likeness in the game is simple and easy and can make a lot of people happy.
* Have them help design a puzzle, or quest, or item, or enemy (Mercury didn't do quite this, but does thrive on user-supplied content).
* If your game has a server-side component or some place you can store account data, allow donators to have unique avatars or other special effects. Guild Wars 1 shipped with a Collector's Edition that gave you glowing hands when you would emote, and a *lot* of people were sad that the sequel didn't have a similar feature. A little bling can go a long way.

Capturing the mindshare of donators throughout development is important not only to build hype and anticipation, but to ensure they convert into actual paying customers on launch, and to keep them active as potential word-of-mouth influencers during and post launch.

* Allowing donators of a certain level access to internal forums or a stream of private development updates can keep people engaged while you work. You'll probably want to make sure there is at least a EULA, some basic legal protection, in place so you don't get embroiled in a lawsuit that you "stole the idea" of somebody who posted it on your forums (this is why professional game developers don't accept unsolicited "ideas" and such in the mail).
* You can also consider allowing donators at a certain level early access to the game, just be aware you could run into a piracy issue. This can be extremely useful since you get ongoing feedback as you iterate, which can really help shape the game in a positive fashion.

I would *avoid* offers rewards of a physical nature unless they are very simple to product (like stickers). Anything that will incur a manufacturing cost and administrative time on your part probably aren't your best bet; you have to pass those costs on to your donators and you rarely end up with very high-quality results.

Above all, try to tailor your rewards to what is unique or compelling about your game in some fashion. It's hard to provide many suggestions without knowing more about your game, but making sure the rewards jive with the brand and feel of the game itself can really help establish a firm bond between the donator and your project which will help keep them interested and more likely to spread the word around.

# Answer
> 6 votes
I've made some reasearch on few game projects in Kickstarter. I have picked smaller projects on purpose, something doable in few people, or in a single person. These are all recently successfuly funded projects. I haven't found any successfuly funded projects that don't offer the digital copy, so I picked a project that as one of its goal has to release the game for free. I looked into other projects as well, but as PeterK said, there is a pattern.

1. A.N.N.E
2. Among the Sleep
3. Bitcrobes

**1. A.N.N.E**

4,113 Backers, $100,272 pledged of $70,000 goal

* Only 66 backers are willing to pay $1 and receive just a virtual thank you.
* 2952 backers are willing to pay $10/$15 to get digital copy of the game with some goodies ($15). That's more than half of all backers and about half of the goal!
* Hundreds of people are willing to pay more if they get the game and their name somewhere in the game. It looks like they don't really care where - the cheaper the better.
* Very few people are willing to pay to have their own NPC, but the goal is very expensive and probably involves quite a lot of developer-donator interaction.

**2. Among the Sleep**

8,110 Backers, $248,358 pledged of $200,000 goal

* 179 backers are willing to pay $5 just for forum access
* 4768 backers (more than half) are willing to pay $15/$20 (early bird existed) when they receive a copy of the game
* only 1624 are willing to give $5 extra for soundtrack
* 700 backers - but that was the limit - are willing to pay $30 for two digital copies
* hundreds of people can pay more than $100 to get access to alpha/beta stage
* tens of people are willing to pay a thousand for their name in the game and contact with the developers - while this doesn't look like many backers, it makes quite a lot of money.

**3. Bitcrobes** 52 Backers, $813 pledged of $660 goal

* Truly an indie project, 1 person. The goal is to have the game free, so you will get your copy in any case.
* A lot of people are willing to donate $1 for a good cause :)
* Gratitude and wallpaper - 14 x $10
* A lot of money raised from very few people who want to unlock special features.
* 3 x $75 for having your own bitcrobe! This is a significant amount for this project

---

**Conclusion**

From this mini-research I'd say that for a game that will be released and sold for some retail price, the rewards should be (in order of "popularity times money"):

1. Digital copy of the game (with extra digital content) and supporter badge on forums if applicable
2. (1) + Name in the game in credits
3. (2) + Access to alpha/beta test and/or being part of development (suggestions)
4. (3) + Part of the game itself (NPC, place, name on a stone etc)
5. (4) + Personalized item from the developers/meet up

For a game that is released for free, the order changes and point 4. will be no.1. The rest will probably stay the same (excl. the digital copy).

---

**To summarize answers from the others**

1. Always offer something that doesn't cost you anything.
    * There is a controversy whether offering a digital copy costs you or not. I'd say it doesn't (excl. discount), because the interested person will either buy it during the campaign or later. From experience, many companies make a lot of money on pre-orders. All early-bird discounts work like that - companies like less money now then possibly more later. It minimizes the risks. *For truly indie project, you want to make sure you have money to finish the project first* and this makes it the most important option.
2. When you offer something that costs you time/money, *make the price reflect that*. But make sure you offer it, because there are always people going for this option. Offering to be part of the game is a good way to go.
3. Early access to the game and suggestion forum can create possible issues with piracy and legal issues with suggestions, but being handled correctly, it can give a lot of important feedback. *Also people are willing to pay for that.*
4. A meetup with developers, skype conference etc. is not as popular and doesn't make a big part of the donations. But it might create a positive hard-core fan base!

# Answer
> 3 votes
Let's face it, people who back your project probably only want one thing:

* *The Product*

In the case of a video game it is a optimal reward since the cost per digital download, for you, the developer, is nearly 0. This should be your basic reward, everything above should just be extras for those who want to fund you more.

Some viable extras would be:

* *Beta access*: Earlier access to the game, for many people this seems to be a kinda big deal. Maybe not ideal for the game though as there will be less impact when it is finally released, on the other side early user feedback is very useful.
* *Collector's Edition*: Exclusive features for people who backed. a additional character for example.
* *Take part in the design of something*: Should be limited to higher tier rewards as this eats up development time and could influence the quality of the game.
* *A meet-up with the developers*: Something for hardcore fans, should be limited to a few.

I would avoid any physical rewards since they cost you money and time and there isn't that much interest in those.

# Answer
> 2 votes
Here is the numbers from Prison Architect, they implemented a crowd-funding model and are still in Alpha and already have raised over $3.4 million

http://www.introversion.co.uk/prisonarchitect/

(Overall: $3,460,225)

Base Pack ($30): (Included Alpha Access) 89,811 Sold - $2,694,330 (Greenlighted on Steam now)

Aficionado ($35): (Includes Alpha Access, PDF of Prison Architect Art book, and a download of the Official Sound Track.) , all previous tiers of donation rewards- 3,841 Sold ( $134,435 )

Introversioner ($40): Get all four Introversion games, all previous tiers of donation rewards 6,689 Sold - $267,560

Name in the Game ($50): One of the prisoners named after you, all previous tiers of donation rewards 5,945 Sold - $297,250

Physical Pleasures ($100): special limited edition Game DVD and Soundtrack CD, a Poster, T-shirt

Digital-Immorto-Criminalise Your Face (100 max) ($250): Not only a character named after you, but you also get the artist to design a entire character to look like you, all previous tiers of donation rewards - 63 Sold - $15,750

Shake it like a Polaroid Picture (20 max)($500): Same as above tier however you'll be used in a in-game scenario/campaign as well, all previous tiers of donation rewards - 17 Sold - $8,500

Warden Norton I presume? (5 max)($1000): Remember the Civ V world leaders that each bring a special world ability? Not content with your own prisoner likeness, and custom polaroid? Come in at this level and you'll also get to design the warden. There will be five wardens in game and the player will have to choose which one to use each time. One of these will be designed by you and us and have a special feature or buff that we'll work together to figure out. As if that isn't worth the price tag alone you also get....every......other......tier. 6 Sold - $6,000 Oops :)

---

I think this is a great example of pricing tiers, rewards and how far a community will go to get behind a game they are really truely excited about. Chris the lead developer / only programmer i'm aware of from a 3 person team, even came out and blatently said "we have no idea how long we'll be in alpha phase, quite a long time i'm sure."

Not to mention Introversion although quite famous among cult circles, is fairly unknown to the general population and about as Indie as you can get. At the time they started Prison Architect KickStarter was not available for use in the UK so they designed their own crowd funding model. And in a interview Chris stated that it felt morally wrong and borderline lying, to use kick starter as Kickstarter "mission" is to get a project off the ground and running, and Prison Architect already had been worked on and near an alpha state by the time Kickerstarter was available in the UK.

# Answer
> 0 votes
For start you should always have some kind of demo and story behind your game. If you just want to "create a game" that is nice but very doubtful.

If you, on the other hand, come with a really interesting demo, a very nice designed trailer and few main ideas that you are planning to use in your story then people will definitely wish to support that. If people are not supporting it, then it is not good enough, so go back to the whiteboard and create something even more awesome.

# Answer
> 0 votes
It mainly depends on what kind of game it is.

But one thing that always works is rewards which are about visual enhancements. Skins/Dyes/Character equipment

This is good because it doesn't affect game play and imbalance the game for players who are not rewarded and keeps things interesting and competitive.

Make sure that the items/skins are unique and limited.

---
Tags: monetization, fund-raising
---


title: Differently-sized sprites?

text:
# Question
Title: Differently-sized sprites?
I'm still at the very early stages of my game design -- nowhere near actually needing the sprites yet -- but a thought occurred to me: What's the best way to approach sprites of different dimensions?

In context, my game will use sprites to represent different space ships (long-range plans include a 3D engine with actual ship models, but for now it's 2D with simple sprites). I've always thought of using sprite sheets as the best way to handle multiple different sprites in games. But some of my ships will be bigger than others. So while one ship might be represented by a 20x15 sprite, another might be 25x18.

How should I best approach this? One sprite sheet and somehow include in my sprite objects the dimension of each frame? Or should I group the sprites into different sprite sheets based on their size? Or should every frame on the sheet be the same size (the "biggest"), and just not use up the entire area for every sprite? Maybe abandon sprite sheets entirely in this case?

# Answer
> 5 votes
One solution would just be to pack as much as you can on a single sheet: Texture packing algorithm

Part of the data that results from that is where the sprite is in the texture and how big it is, so you can use that information to draw the portion of the image that you need for a given sheet.

Be sure to not use mipmaps, though.

# Answer
> 2 votes
You could round them to the next power of two (or any other size, but powers of two are always convenient) and collect all of the same power of two in a single sprite sheet.

# Answer
> 2 votes
A few other notes on texture "atlases" as they're usually called, or sprite sheets.

* Make sure you disable any filtering.

The reasoning behind this is that any kind of filtering will blur one texture/sprite into the next.

If you really must use filtering, ensure that you leave a gutter area around each image to account for the filtering. The trick here is to extend the last pixel into the gutter area so that any filtering (or averaging) will average the same colour as the last colour in the actual texture.

If you use a black (or other solid colour) as a gutter region, you will be in some very weird averaging. and leakage back into the original image.

* Try and use power of two sized textures

Yes, all the graphics cards now support non power of two textures. Most of the time they just inflate the texture to the nearest power of two in the driver underneath you. Be nice to your graphics card, use a power of two, your texture cache will thank you.

* There's lots of really cool packing algorithms

But in reality, a simple "left" until it wont fit, then "down" works surprisingly well, especially with regularly(ish) sized textures.

* Pack heavily used textures first.

It can be very useful though to pack often used textures near to each other to minimize cache thrashing and texture cache use!

# Answer
> 1 votes
If you insist on a sprite sheet, there are algorithms that will generate the smallest possible area with all the sprites in it (or write one yourself for fun). However with basic compression, you're better off making a big, but organized sprite sheet:

1. Easier to manage and look at
2. You can always pack it if you ever get to ship
3. Even if you don't, basic compression will make the difference negligible

However using separate files for each sprite is a more modular way of going about this. The difference is organizational and personal preference - I learned to use sheets from the first tutorial I saw. Then I figured it would be easier to use separate PNGs for everything, and that's stuck with me.

Edit: Here is an another answer that links to two tools for texture packing.

---
Tags: sprites, spritesheet
---


title: Raycasting problem

text:
# Question
Title: Raycasting problem
I have a problem with my raycasting. I have 8 cubes, that define the first level of an octree (Eg. they create bigger cube).

I need to raycast them and "render" each cube. If I have only one cube, the raycasting works fine. If I use 8 cubes, I have a problem. If I move my camera, gaps between cubes start to appear. Cubes are moving apart.

The whole octree bounding box min is (0,0,0), max is (64, 64, 64). Each box has size 32x32x32 and all boxes are set in \[0,0,0\] and move to their right position with transform matrix tmp

```
for (int i  = 0; i < 8; i++)
{

    MyMath::Vector3 centerVec = this->streams[i].center;  //left-bottom corner of box
    MyMath::Matrix4x4 tmp = MyMath::Matrix4x4::Translation(centerVec);

    tmp = tmp * *(camera->GetViewMatrix());
    tmp = MyMath::Matrix4x4::Invert(tmp);

    CastRays(tmp, camera);
}

```

CastRays goes through every screen pixel and calculate ray from pixel position and camera coordinates.

```
foreach pixel
{
        Vector3 vec = Map2DTo3D(x, y, width, height, &cameraCoordSystem);
        Vector3 dir = vec - cameraPos;

        Ray ray;
        ray.dir = dir;
        ray.origin = cameraPos;

        ray.dir = TransformCoordinate(ray.dir, worldInv);
        ray.origin = TransformCoordinate(ray.origin, worldInv);
        ray.dir = Normalize(ray.dir);

        int value = TraverseRay(ray);
.....
}

```

Traverse ray uses "An Efficient Parametric Algorithm for Octree Traversal" algorithm

```
int TraverseRay(ray)
{
        if (ray.dir.x < 0.0f)
        {
                ray.origin.x = boxSize - ray.origin.x;
                ray.dir.x *= -1;
        }

        if (ray.dir.y < 0.0f)
        {
                ray.origin.y = boxSize  - ray.origin.y;
                ray.dir.y *= -1;
        }

        if (ray.dir.z < 0.0f)
        {
                ray.origin.z = boxSize  - ray.origin.z;
                ray.dir.z *= -1;
        }

        float tx0 = (0 - ray.origin.x) / ray.dir.x;
        float tx1 = (boxSize  - ray.origin.x) / ray.dir.x;

        float ty0 = (0 - ray.origin.y) / ray.dir.y;
        float ty1 = (boxSize  - ray.origin.y) / ray.dir.y;

        float tz0 = 0 - ray.origin.z) / ray.dir.z;
        float tz1 = (boxSize  - ray.origin.z) / ray.dir.z;

        //infinity test - not included... have no effect on bug

        if (Max(tx0, ty0, tz0) < Min(tx1, ty1, tz1))
        {
                return 1;
        //there is procsubtree().. but again.. no effect on error... error occurs
        //even with return 1
        }
        else
        {
                return -1;
        }
}

```

The space between boxes is changing its size with respect to the camera. There should be no space between boxes: it should be one single square (if I rotate this, there are other 4 boxes from octree behind those)

Image:

# Answer
> 1 votes
I cannot sure how your math library is working exactly, but a function named TransformCoordinate is usually used to transform a position vector including translation. A directional vector should use another transform usually named TransformNormal.

In the CastRays function, you used TransformCoordinate to transform a directional vector, ray.dir. It might cause wrong results.

---
Tags: voxels, raycasting, octree
---


# Question
Title: How can efficiently I edit my 2D tile-based maps?
I've been developing a very basic 2D tile-based game for my own experience. I read what must be hundreds of tutorials on what I found on Google with "tile based maps".

Almost every tutorial I see is an engine that reads a text file and loads tiles based on the numbers in the file, such as:

```
0,0,0,0
3,0,0,3
2,0,2,2
2,0,2,2

```

But what if I were making a map that contained several 100 tiles?

surely there's an easier way to make a map than by writing a ton of numbers into a text file? How can this be done quicker?

An idea I had was making the world a single layered image: A layer for the objects/sprites/characters and another on top of that for tiles that should be under you like walls, trees, etc.

Is this possible/worthwhile?

# Answer
When you handcraft the map you probably want some kind of map editor. When it is for learning (and otherwise too), I would recommend to make your own editor. That way you discover what difficulties is involved and you can make a perfect fit for your particular use case.

When storing the map you might want to save more than just the tile id, so in the end you probably have to come up with your own map/save format.

And just to keep your options open, here is an alternative approach:

* "Procedurally generate" the map instead of handcrafting it. The maps are generated from a "pseudorandom seed" (just a long integer number), so all you need to save is the seed and any eventual changes to the generated map.
* For map and game state storage, use an embedded database like SQLite instead of files. This way you can make advanced queries against your current map/game state.
> 1 votes

---
Tags: xna, 2d, tiles, maps, tilemap
---


title: Volumetric Fog Shader - Camera Issue

text:
# Question
Title: Volumetric Fog Shader - Camera Issue
I am trying to build an infinite fog shader. This fog is applied on a 3D plane.
For the moment I have a Z-Depth Fog. And I encounter some issues.
As you can see in the screenshot, there are two views.
The green color is my 3D plane. The problem is in the red line. It seems that the this line depends of my camera which is not good because when I rotate my camera the line is affected by my camera position and rotation.

I don't know where does it comes from and how to have my fog limit not based on the camera position.

**Shader**

```
Pass {
        CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            uniform float4      _FogColor;
            uniform sampler2D   _CameraDepthTexture;
            float               _Depth;
            float               _DepthScale;

            struct v2f {
                float4 pos : SV_POSITION;
                float4 projection : TEXCOORD0;
                float4 screenPosition : TEXCOORD1;
            };

            v2f vert(appdata_base v) {
                v2f o;
                o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                o.projection = ComputeGrabScreenPos(o.pos);
                o.screenPosition = ComputeScreenPos(o.pos);
                return o;
            }
            sampler2D _GrabTexture;

            float4 frag(v2f IN) : COLOR {
                float3 uv = UNITY_PROJ_COORD(IN.projection);
                float depth = UNITY_SAMPLE_DEPTH(tex2Dproj(_CameraDepthTexture, uv));
                depth = LinearEyeDepth(depth);
                return saturate((depth - IN.screenPosition.w + _Depth) * _DepthScale);
            }
        ENDCG
    }

```

Next I want to rotate my Fog to have an Y-Depth Fog but I don't know how to achieve this effect.

---

It seems that this is caused by \_CameraDepthTexture, that's why depth is calculated with the camera position.
But I don't know how to correct it... It seems that there is no way to get the depth from another point. Any idea ?

Here is another example. In green You can "see" the object and the blue line is for me the fog as it should be.

# Answer
> 2 votes
Well this can't be solved in a single rendering pass, you need to render your scene from another point of view (different camera) to a separate off-screen render buffer in a different pass and then convert this buffer into a texture and bind it to \_CameraDepthTexture.

I don't know how this is done in unity, but practically speaking, you should create a new camera that renders to an off-screen buffer, separately from your main camera point of view, this will let you render the scene twice; once from each camera, the new depth camera will render the scene into the off-screen buffer, the main camera will then render to main frame buffer and use the off-screen buffer as a texture for the plane.

The new camera position might "follow" some constraint depending on how you want the fog to look like, (e.g. its position might be aligned to the world z-axis or perpendicular on some plane. which is something not very clear in the example)

---
Tags: unity, shaders, glsl, hlsl, fragment-shader
---


# Question
Title: Projecting world coordinates to screen coordinates issue - points disappear when origin not in view
I am trying to implement a 2d line drawing effect on a 3d mesh using Ogre. In order to do so, I perform silhouette detection on the lines of the object (this works) and then project these lines from world to screen coordinates.

Here is the code I use for converting the coordinates:

```
            bool toDeviceCoordinates(Ogre::Vector3 &result, Ogre::Vector3 &point,Ogre::Camera *camera)
            {
                if(!camera->isVisible(point))
                {
                    return false;
                }
                Ogre::Vector4 p(point.x,point.y,point.z,1);

                p = camera->getViewMatrix()*p;
                p = camera->getProjectionMatrix()*p;

                result = Ogre::Vector3(p.x,p.y,p.z);
                result /= p.w;

                return true;
            }

```

To draw these points to the screen I just pass them through the shader like so:

```
            gl_Position = gl_Vertex;

```

This works fine except when the origin of the scene is not visible.

Any idea where I am going wrong?

# Answer
Solved the problem:

The shader was the culprit - seems it didn't like me skipping the application of the modelviewprojection matrix.

Instead, I applied the above function to convert my points to screen space. I then did my calculations on it - extruding more vertices from it etc. I then applied the inverse matrix operations to those points to return them to world space. These points were then passed to the shader and instead of:

```
gl_Position = gl_Vertex;

```

I use the more correct:

```
gl_Position = modelViewProjectionMatrix*gl_Vertex;

```

So in essence here is my process: world -\> screen -\> extrude points -\> world -\> screen
> 0 votes

---
Tags: c++, 2d, ogre, projection, viewport
---


title: Accidental noise - Gradient function

text:
# Question
Title: Accidental noise - Gradient function
Related to my previous question (2D Terra(ria)in generation - Accidental noise) I'm stuck on understanding how the gradient function itself works (in the Accidental library).

After help on chat (thanks Jon!) I understand that upon defining the gradient, for example, Gradient(0,0,0,1), it *returns* a function that upon its turn would return correct values between 0 & 1 for the arguments you provide.

So calling the this function with (0,40) would give you a value back between (0,1). However, I don't understand how it would do this without knowing the outer "range".

E.g. If you'd render the gradient image that's shown on his site:

Would you do that by defining the gradient(0,0,0,1) and then calling it for each pixel? (0,1) (0,2), (50,50),...? In that case, pixel (0,200) would have to return 1, but if you'd have an image of 400 pixels high, (0,200) would have to return 0.5

And calling it with values between (0,0) & (0,1) with predefined steps (1/200 or 1/400 for example), seems to make the gradient noise function itself rather useless.

If possible, pseudo or python code would be very welcome to illustrate how the "internals" on that gradient function would work, perhaps I'm thinking of it too complex.

Thanks in advance!

# Answer
> 5 votes
The values specified when you create your gradient, are your endpoints. So for example, when you create a gradient with the values (x1=0, x2=0, y1=0, y2=1), you are creating a gradient line on the y-axis with its endpoints being 0 and 1, on the y-axis.

Okay, so you have a gradient on your y-axis, starting at point 0, all the way to point 1. What does this mean?

> If it lies on or beyond P1, the value is assigned as 0. If it lies on or beyond P2 the value is assigned as 1. Anything in between is assigned as a linear interpolation between 0 and 1.

This doesn't mean your image is 1 pixel high, it just means your gradient is 1 unit high in your function.

When you retrieve values from this function, you can scale according to your image.

For example:

```
for (int i = 0; i < imageWidth; i++)
{
    for (int j = 0; j < imageHeight; j++)
    {
        double x = i / imageWidth;
        double y = j / imageHeight;
        double val = gradient.Get(x,y);
    }
}

```

# Answer
> 4 votes
Everything you pass into the function should be scaled by the size of your world. Since the gradient lies between 0 and 1 of the function, you essentially just normalize everything based on your maximum world height. To illustrate, here's a little function that would do something like that:

```
float gadientAt(worldX, worldY)
   return gradientFunction(worldX/WORLD_SIZE_X, worldY/WORLD_SIZE_Y)

```

While you don't really have to scale the x axis (since the gradient is along the y axis), we're just ensuring the function works for all types of gradients.

If you were to pass in values outside of the 0 to 1 range, you'd just get 0 or 1 for return values.

You can always create the gradient function with the size of your world `Gradient(0,0,worldMinY,WorldMaxY)`, but people usually like to think in normalized values.

---
Tags: python, perlin-noise
---


# Question
Title: either use a for loop or iterator for the List of sprites for loop Optimization in libgdx
I am making and there I am making a frequent use of java.util.ArrayList for enemies, coins and shots. Is there any other utility in libgdx better than this from the Performance point of view.

Further, I can get my things done using a for loop too.So, Which would be better to use. A FOR LOOP or an ITERATOR

# Answer
> 2 votes
The most generic answer is to leverage a profiler; and you generally don't want to worry about these sorts of decisions too much until you have evidence that they are the source of an actual performance *issue* in your game.

However, you can make some initial decisions about the choice of container and traversal method based on some information about the algorithmic properties of those containers. For example, if all you're going is traversing a collection in order over and over, an array is usually better than a linked list due to its improved cache coherency / locality of reference (arrays are contiguous; elements in a linked list *may* be spread out all over your address space unless you're using a pooling allocator for the elements).

Similarly, trivial iteration of an array via a for loop with an index is about as bare as you can get: it involves the minimum of overhead. Iterators usually require the construction of some object and related state (because they hold the iteration state within them). This means they have a very slight memory overhead and potential garbage-collection overhead (due to transient object allocation). But on balance, they allow you to pass the iteration state around to other interfaces -- generally provided that you don't modify the underlying container during the iteration, which can invalidate the object state.

In short, to best decide the data structure you need, and the interaction methods you should use with that structure, you should make sure you have a basic understanding of the algorithmic tradeoffs of your options and the context within your game where you're going to employ these structures. Beyond that, you should not stress out about it too much -- always aim for readable, clear code first. Then profile your game regularly and investigate actual bottlenecks as they arise.

---
Tags: android, game-loop
---


# Question
Title: Should I accumulate state time based on a global or a parameter?
Generally, we associate a "state time" with our sprites. Libgdx provides a method to do so:

```
float deltaTime = Gdx.graphics.getDeltaTime();

```

However, in the main game loop, we have a delta time as a parameter in `render()` methods. Suppose my player has states like `Idle`, `WalkLeft`, `WalkRight`, `Jump`, `Hit`, and `Die`. I use the delta time to know how much total time has elapsed within a state:

```
public void setState (int state){
    float deltaTime = Gdx.graphics.getDeltaTime();
    this.state = state;
    this.stateTime += deltaTime;
}

```

Is it proper to write this, or I should take the parameter for delta time from the method that calls it?

# Answer
> 6 votes
I think you're conflating *render* and *logic* updates. The delta returned by the `Gdx.graphics` object is an elapsed time value that probably should only be used for render updates, but the state an object is in is more of a game logic issue, and you generally want these things handled on different timers.

This is because if you *pause* your game logic (by stopping the game logic timer, so all delta times for logic are zero), you may still want some aspects of your rendering (such as, perhaps, HUD animations) to continue.

So first I would recommend you divorce your graphics and logic timers. Then, I would recommend pushing the delta time through to every object that needs it as a parameter. You can still your delta time by calling `Gdx.graphics.getDeltaTime`, but do it only once at the top-most update function, and push the resulting delta down through every game or render object's own update methods. This helps decouple them from the global instance, allowing you to do better global control of timing-related effects (like slowing everything down, or pausing things as described above).

I'd also recommend moving the update of the elapsed time into an actual `update()` method, and not doing it in `setState`. It makes very little sense that setting the state would also advance the object's simulation time, and it means you can't call `setState` more than once in an update interval without artificially pushing the clock for that object forward.

# Answer
> -3 votes
`Gdx.graphics.getDeltaTime()` returns the same delta for each frame.

Running this code will never return "Delta different" even though it does get called at different times.

```
    float delta = Gdx.graphics.getDeltaTime();

    for(int i = 0; i <= 1000000 ; i++)
    {
        if(delta != Gdx.graphics.getDeltaTime()) Gdx.app.log("Test", "Delta different");
    }

```

---
Tags: libgdx, timer, timestep
---


# Question
Title: What is an appropriate level of granularity for component-based architecture?
I'm working on a game with a component-based architecture. An `Entity` owns a set of `Component` instances, each of which has a set of `Slot` instances with which to store, send, and receive values. Factory functions such as `Player` produce entities with the required components and slot connections.

I'm trying to determine the best level of granularity for components. For example, right now `Position`, `Velocity`, and `Acceleration` are all separate components, connected in series. `Velocity` and `Acceleration` could easily be rewritten into a uniform `Delta` component, or `Position`, `Velocity`, and `Acceleration` could be combined alongside such components as `Friction` and `Gravity` into a monolithic `Physics` component.

Should a component have the smallest responsibility possible (at the cost of lots of interconnectivity) or should related components be combined into monolithic ones (at the cost of flexibility)? I'm leaning toward the former, but I could use a second opinion.

# Answer
> 14 votes
There's a line between complete granularity, leading to no code wastage or blob-like state (which is why component architectures are favoured), and usability.

Obviously things may have a `Position`, but they're not necessarily dynamic (so why have `Velocity` and `Acceleration`?). However, something with a `Velocity` is going to be a moving object, so it makes sense to also have `Acceleration` grouped.

Are you going to have a case where **v** and **a** are going to be needed, but you don't want a physics simulation for them? Similarly, is there going to be a point in `Gravity` if they're not physics objects?

*tl;dr Group what makes sense.*

# Answer
> 6 votes
To avoid micromanaging each and every variable I'd suggest by starting heavy, choose divisions around responsibility and refactor when the situation presents itself logically. You can start the first designs on paper. At some point these gross divisions of responsibility will become the building blocks of your entities.

So for a rushed example you have Game. Game splits into Environment + State. Environment splits into StaticWorld + MovingStuff. State splits into AIControlled + PlayerControlled. The gross idea of Damage splits into TakesDamage + GivesDamage.

And so on.

Much like the common advice to "Build games, not engines!" for new practitioners I recommend "Build Games, not elaborate component systems!" because only with personal experience with a running game will you know whether an elaborate component system is called for in future works.

# Answer
> 4 votes
My guess would be to combine components who will have lots of interaction. In your case, i'd keep the position in a single component, and have the velocity & acceleration kept together in a physics component.

But it depends a lot on what your game features are (unless you're building a framework with no specific game in mind).

# Answer
> 4 votes
I realize this is an old question but maybe someone will find this answer useful.

I believe that **`Systems`** will better help you to understand how to construct Components. Systems exist in architectures where components don't contain their own logic, aside from simple getter/setters and helper functions. Systems operate on Entities which satisfy the Component requirements. This is why it is best to separate component data as much as it makes sense for that data to be processed without the other data.

For example, you might have a `MovementSystem` which updates its Entities' `Position` based on their `Velocity`. This could be for simple entities in the game. But, for the **Player** and **Enemies,** you might want movement that has `Acceleration` which is processed in `AcceleratedMovementSystem`. But for **Obstacles** you might want `Friction`. The **Terrain** might also have friction, but it won't have a velocity component. But what about `Gravity`? Just add it Player, Enemy, and Obstacle, and create a `GravitySystem` to process it.

The bottom line is that the more **decoupled** your `Components` are, the more **extensible** the `Entities` will be when using `Systems`.

Edit: Made last statement clearer.

Edit: Ok, I've been working on my own System and came to this realization. An example for splitting up Position and Velocity is that manipulating Velocity causes the Position to change with a MovementSystem. As a result, an 'InputMovementSystem' doesn't need a Position to cause the Player to move from user Input because the MovementSystem will pick up the changes in Velocity to apply to Position. Granted, it would still work fine to put them together, but thats an example of why the don't need to be.

---

I read a blog post recently that said something like this:

> "If you have data that can be grouped with 2 different components, it is best to create a third component with that data."

---
Tags: architecture, entity-system, component-based
---


# Question
Title: Do associative array data structures have a place in game development?
Is it a bad idea to use a map data structure (an associative array or dictionary) in game development?

According to this flowchart, the ideal container for storing game object's container would actually be a map for many games. But I've heard anecdotal claims that maps are a very bad choice for games.

Is this true?

# Answer
Are associative arrays a good idea for games? Perhaps, depending on your needs.

However, you need to differentiate between comments about "associative arrays" and specifically about the class `std::map`.

### Associative Arrays

Associative arrays are just some kind of data structure that allows you to associate one kind of value with another, such that you can look up a value with another value. There are many kinds of associative arrays, some of which are really implemented with a regular array.

Hash tables are a form of associative array.

The "conventional wisdom" among many C-style game developers is that looking up entities by name is not worth it. This "wisdom" effectively says that your entities should be in one big global fixed-size array. When you create a new one, you find an unused index, set it to be used, and you pass the "index" around as the name.

Entities may have an actual string name, but you won't be using that to find the entity by name very often; generally speaking, you will reference entities by either pointer or index. This is still an associative array; it just uses an index rather than a name as its key value.

One pitfall you may have with associative arrays is that you may need to collate entities based on different properties. Things like "find all entities with blue hands" or whatever. Your associative array isn't going to help you; you'll have to take a linear walk down the entire list of entities to deal with that.

If your game does this kind of collation a lot, then adding other data structures might be a better way to go. Of course, that's rather complex.

### std::map

`std::map` is a specific *implementation* of an associative array. And while it is the shortest associative array in the standard library, it has certain performance quirks.

Specifically, every insertion is a memory allocation. But more than that, because the memory is likely not contiguous, accessing different elements will likely miss the cache. If you ever need to walk through the list of all entities (to render them, update their position, etc), every entity is basically going to be a full cache miss.

You can read more in this PDF; it talks about `std::set`, but they're both the same under the hood.

The "conventional wisdom" I stated earlier tends to avoid that issue. But really, it's bad coding for C++. It's really just a poorly-designed pool allocator, and an actual pool allocation system would be far better at achieving the same effect.

A better alternative would be using Boost.Container's `flat_map` class. It essentially takes the concept of a sorted `vector` from the PDF and implements a variation of `set` and `map` from it. Insertion and deletion will be slightly painful, as it will have to shuffle elements around. They'll be more painful than the pool allocator case, certainly. But iteration will be quite fast.

However, what matters most is that you think about how much this *matters.* Is your game *performance heavy* at all? More specifically, is your game's performance going to be contingent on the memory performance of the class that contains your entities? If not, then what matters for you is *user convenience*. Do what it takes to get the job done. And if `map` does the job, use it. If it starts to become a performance issue, you should be able to replace it with something else.
> 13 votes

# Answer
Take blanket statements like that with a grain of salt. Only a tiny fraction of the code in a game is performance sensitive. If a map is the collection you need, use it. Otherwise don't.

You're trying to be specific with an example of holding a bunch of "GameObjects" in a map. What are you mapping to/from? Why do you need to sort your GameObjects? If you can answer both of those questions well, then a map may very well be what you need.

From my experience, when dealing with any sort of entity system, the entity container does not have any additional data that needs to be stored outside of the GameObject, nor does the container have to be sorted. I just need everything in one place so I can quickly complete actions on all of them, an array or vector is perfect for that.

But perhaps your game, for some reason, needs a LOT of arbitrary communication between GameObjects. You give each GameObject and ID and want to be able to tell your container to get another GameObject by it's ID. After some profiling, you realize that searching through an unsorted array of GameObjects is your bottleneck because of how much searching you have to do. You figure you can refactor the ID outside of the GameObject and you want your data to stay sorted to make searching quicker. In this case you could try replacing the array with a map and see if there are any noticeable performance improvements.

On the other hand, there is something to be said about a map not being stored contiguously in memory. Looking at it through a data-oriented programming lens, maps (and all hierarchical data structures) are a nightmare. Flat data structures have less iteration overhead and cause less cache misses. Additionally, it makes parallelizing code much easier. Give each thread an index and a length and tell them to go. Assigning nodes to threads from a tree is significantly more complicated.
> 4 votes

# Answer
A data structure is a tool, like any other. That means it has places where it is appropriate and places where it is not, and a map is no different.

If it fulfills the need of your program, makes logical sense in the use case and contributes to the improved readability of your code, then use a map.

If that use case ever becomes a performance concern (which you'll know through regular profiling of your game), address that concern then.

You've provided no references or citations to the assertions that maps have no place in game development, but if you had I suspect those claims would be easy to dismiss as overgeneralized hand-wavy FUD.
> 4 votes

# Answer
Ill add that it's also very dependent on the data you're modelling, and the operations that you perform on the data. If you're just writing something simple, you're not likely to suffer the same performance problems that people who are actively pushing the hardware very hard.

Maps, or associative containers, as your diagram suggests, are fantastic for random access patterns. they're not so great for linear access. They're also pretty decent for when you need to insert and remove a lot of items. being STL, they're also going to work with very very minimal bugs (read "if it breaks, its 99.99% your code).

As always make it work first, make it fast later. The key to doing that effectively is good API design which is optimised around your access patterns, but hides the underlying data structures. Once you've got it working. profile profile profile. Its quite likely that any performance issues you will have *wont* be based on your usage of std::map.

The only data structure you should try and avoid at all costs is the linked list. They're terrible for linear processing due to being cache inefficient, and they're horrible for random access as you have no way to jump to a particular node without iterating the list. doubly linked lists are somewhat better, but you're far better off just using an array, or a tree.
> 3 votes

---
Tags: performance, data-structure
---


title: XNA Texture2D positioning problem

text:
# Question
Title: XNA Texture2D positioning problem
I'm currently stuck on something that just seems extremely odd. I'm creating a game with kinect, and when the player performs an action I want to place a texture onto the screen where their hand is.

I currently have that code implemented. I have something like:

```
var myVector = Skeleton[JointType.RightHand].Position;

```

When I get the vector coordinates I store them in an array and that allows me to reference it later if/when I need to. That is the HitVectors array.

The numbers that are recorded into the array are the actual coordinates of the \[RightHand\] in relation to it's pixel coords on the screen. So for instance your hand is at 100X and 400Y. the array gets a new Vector2(100f, 400f), and so on...

```
public override void Draw(GameTime gameTime)
{
        // This game has a blue background. Why? Because!
        ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
                                           Color.CornflowerBlue, 0, 0);

        SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

        spriteBatch.Begin();

        spriteBatch.Draw(targetTexture, hostileOne.CollisionBox, Color.White);

        if (hostileOne != null && hostileOne.HitVectors.Count > 0)
        {
            foreach (var pos in hostileOne.HitVectors)
            {
                //trying to get the textures to not draw in a diagonal line
                //spriteBatch.Draw(impactTexture, pos, Color.White);
                spriteBatch.Draw(impactTexture, new Rectangle((int)(pos.X), (int)(pos.Y), 256, 256), Color.White);
            }
        }

        spriteBatch.End();
}

```

but the texture isn't drawn to those coordinates on the screen. Instead they are essentially only drawing on a diagonal line, at a 45 degree angle. It seems like the oddest thing to me. I've double checked to make sure that the position coords being passed into the sprite batch are correct, and they are. I've checked to make sure that the coordinates of the hand joint that i'm tracking is at the correct X and Y coordinates when I record its position. So to me, everything seems good until the spritebatch.Draw() method is executed.

For extra info, my texture is a 256x256 png file, the spriteBatch being used is from the GameStateManagement example. It's in the ScreenManager class.

photo of issue: http://i1366.photobucket.com/albums/r770/csmhowitzer/debugdiag\_zps4239d261.png

How I convert my Kinect joint position in 3D space to 2D:

```
protected Vector2 CalculatePointPosition(SkeletonPoint point)
    {
        var pointx = point.X;
        var pointy = point.Y;
        var pointz = point.Z;
        var pointnormx = pointx / pointz;
        var pointnormy = pointx / pointz;

        return new Vector2((pointnormx + 0.5f) * (int)screenSize.X, (pointnormy + 0.5f) * (int)screenSize.Y);
    }

```

If you need any more info let me know.

Thanks in advance everyone

# Answer
the code I was using was:

```
protected Vector2 CalculatePointPosition(SkeletonPoint point)
{
    var pointx = point.X;
    var pointy = point.Y;
    var pointz = point.Z;
    var pointnormx = pointx / pointz;
    var pointnormy = pointx / pointz;

    return new Vector2((pointnormx + 0.5f) * (int)screenSize.X, (pointnormy + 0.5f) * (int)screenSize.Y);
}

```

and the issue was a syntax error where I had coded in `var pointnormy = pointx / pointz;` and it should've been `var pointnormy = pointy / pointz;`

so the correct code in this case was:

```
protected Vector2 CalculatePointPosition(SkeletonPoint point)
{
    var pointx = point.X;
    var pointy = point.Y;
    var pointz = point.Z;
    var pointnormx = pointx / pointz;
    var pointnormy = -(pointy / pointz);

    return new Vector2((pointnormx + 0.5f) * (int)screenSize.X, (pointnormy + 0.5f) * (int)screenSize.Y);
}

```

this function is taking the real world measurements of a point in space (in my case it's the user's right hand) and takes the normal vectors and multiplies them by the screen width and height respectively.
> 0 votes

# Answer
Use Viewport.Project to project the 3D point to 2D.

http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.viewport.project.aspx
> 0 votes

---
Tags: xna, textures, spritebatch, kinect
---


# Question
Title: Why is Farseer not working in Windows Phone 7/8?
I created a new Windows Phone Game (4.0) project in Visual Studio Express 2012 and added the Farseer project to the solution explorer. But adding a reference to the Farseer project is not working. I always get this error message:

A reference to 'Farseer Physics XNA WP7' could not be added. References with different refresh levels are not supported.

What is wrong? How can I use Farseer in Windows Phone 7/8?

I uploaded the two projects on pastebin.

Farseer project: pastebin.com/uyRusHxM

Windows Phone project: pastebin.com/s74Gr66y

# Answer
## If your project is 7.1 and Farseer is 7.0

Right click the Farseer project and click `Upgrade to Windows Phone 7.0`.

## If your project is 8.0 and Farseer is 7.1 or below

To upgrade to WP8.0 is more of a pita though not too bad.

You will need to edit the csproj file for both projects. So for both of them.

1. Right click the project in the solution explorer and select “Unload Project”.
2. Right click the project again and select “Edit csproj”.

This option is out of synch between the two projects. Find out the status of the `XnaRefreshLevel` tag in your project. I think it should be `<XnaRefreshLevel>1</XnaRefreshLevel>`. If so add that option under the same grouping in the farseer project. It may not be but the point is to make it so that the Farseer project has the same `XnaRefreshLevel` entry as your project.
> 2 votes

---
Tags: xna, c#, farseer-physics-engine
---


# Question
Title: Why would a Bounding Sphere and BoundingBox not intersect (when they should)?
I have a bounding sphere and a bounding box that should be intersecting, however, `Intersects(...)` is returning `false`. For example, the following returns false:

```
new BoundingSphere(new Vector3(500, 105, 0), 25).Intersects(
    new BoundingBox(new Vector3(466,219,0), new Vector3(519,26,0))
)

```

# Answer
According to http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.boundingbox.boundingbox.aspx

The constructor of BoundingBox expects minimum and maximum points. Your second vector's y is less than your first vector's y. This might break the intersection test.
> 7 votes

---
Tags: xna, c#, collision-detection
---


# Question
Title: How are 3D models created in video games?
How are 3D models in games designed and displayed? Is it all code? Drawn on paper, then on a 3D graphics software, then... what?

Of course, game *programmers* won't define every vertex of every shape(/object,) they want to be drawn, all in code (whether in Direct3D or OpenGL.) So, do the game *designers* have tools to use, like Maya or something like it of proprietary 3D graphics softwares out there; they "draw" the model in that software, export it in whatever format, then *programmers* parse it via code and automatically enter the decoded/parsed raw vertices of the object/model?

I have Googled much but I couldn't find something solid to explain how this aspect of professional video games is worked on.

# Answer
In all the games I've worked on, the the Asset Creation Pipeline goes something like this:

1. the concept artist (for levels/backgrounds/level models) or character artist (for models) will generate sketches for characters/levels/etc. usually multiple options are given to the creative director / lead art to decide which one they like better.
2. The concept / character art that has been approved is given to a modeler to use as reference. Sometimes additional profile/front on art is done by the character artist to provide a cleaner frame or reference for the modelling process. I've seen many a modeler with the concept art stuck up within 3d max/maya/etc as direct reference.
3. The modelers typically generate the base textures for the model as well, usually with the correct shader materials for the runtime. shaders are used to render the model in the game, and may have specific texture/uv/etc requirements which need to be provided by the modeler or assigned texture artist.
4. It will be the Level Designer's job to piece together the assets to "build" level itself.

Its unusual for an entire level to be built as a single piece of geometry. Most levels are built of pieces, or sections. (eg: infamous used a set of hexagon "tiles" http://www.gamasutra.com/php-bin/news\_index.php?story=118581 and skyrim (and many others) use a lego style approach to piece together levels http://www.gamasutra.com/blogs/JoelBurgess/20130501/191514/)

There's usually a level editor of some description involved in this process, although many games have used 3d modelers as "level editors" for instancing previously created assets.
5. Once all this is done, the assets are typically processed by the *Toolchain* which turns the 3D Modeler friendly files into game ready data which can be loaded directly into the Runtime.

Toolchains (the bit that takes the raw assets and transforms them into game ready data) are often some of the most complicated pieces of engineering in game development. They need to talk to many different applications, understand many different file formats, and also understand how to transform data into a more efficient and instantly usable format. Toolchains typically also perform lighting pre-passes, vertex welding, LOD generation and so on. Often building the entire data set for a large AAA game will take a very long time, often greater than 8 hours for a complete rebuild. So Toolchains typically also contain distributed processing to spread the load across all the PC's in the entire studio.

The *Runtime* is the game itself. The executable which runs on your PC, or Console. Inside the Runtime there will be a system called a Resource Manager. It's the Resource Manager's job to load the assets requested by other systems within the game.

E.g.: When you tell the game load into a Level, the Level's metadata will provide the Resource Manager with a list of which assets need to be loaded to display the level. Likewise, each Asset will contain a list of any Textures, Materials, or Sub Assets that are required to be loaded.
6. Once everything's actually loaded into memory. The game will send things which are visible to the *Renderer* which will then interact with the API used to actually draw things on the screen.

Programmers can (and do) generate vertex information by hand. This is typically called "Immediate Mode Rendering". It's not very efficient, and is only used for situations where its not possible to use pre-generated, or shader manipulated vertex data. Eg: UI Rendering, Fullscreen Quads.

Typically 99% of the objects onscreen will be pre-generated vertex information rendered in "Retained" mode, With shaders performing any manipulation required. Eg: Skinned Animation
> 16 votes

# Answer
Here is a simple answer: They do it all in 3D graphics applications like Maya or 3DS Max. First they do some concept arts (on paper), according to them they create models, textures (in Photoshop or something like that). Simple animations are done whole in software too, more complex animations are done via Motion Capture and then mapped to your model. For animation you usually use Skeleton animation.

All of these data is saved in files.

When your game starts, it parses all these files and loads models, textures, animations. And when it's needed, it displays them.
> 7 votes

# Answer
The programmers actually *can* define each vertex individually if they want to. This is, of course, never the case unless they're making some sort of basic cube demo. Normally, what's saved in the model files is something along the lines of a list of vertices that the programmer can effortlessly easily plug into their model-drawing code. There's obviously more to it than that, but basically model formats are giving indirect "instructions" on how to draw a certain model.

In many cases, and for many model file formats, the coding side has been done for you. There are even some text-based model formats, with accompanying drawing code, that make it pretty easy for an amature coder to follow how the model is being translated into code.

I've never been the person to actually write this code, though, so it's possible a few details of my explanation are off.
> 4 votes

# Answer
I have been working on my own to try to put a game together. I can give you a simple list of the programs I use.

Modelling: 3D Coat, modo

Rigging: modo

Textures: GIMP, Inkscape

Game Engine: Unity

Obviously this is a small list of applications, but for me they work and are affordable for hobbyist and indie developers.
> 2 votes

---
Tags: graphics-programming, 3d-modeling
---


title: Using Box2D for range detection?

text:
# Question
Title: Using Box2D for range detection?
I have two entities. One has a sword, one has a bow and arrow. When the bow entity is 100 units away, he needs to begin attacking. Likewise, when the sword entity is 10 units away, he needs to begin attacking.

My idea is to create an actual physical body for collision detection and a range body (or fixture?) for range detection. However, I don't want the range body to start pushing and affecting other entities. I simply want to detect when one entity's range body collides with another entity's physical body.

Is this the right thing to do and how can I do this with Box2D?

# Answer
You can utilize Box2D sensors (or contact listener) for this. Setting one up is fairly simple, and a tutorial can be found here. The basic code (from the link):

```
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact) {
    // console.log(contact.GetFixtureA().GetBody().GetUserData());
}
listener.EndContact = function(contact) {
    // console.log(contact.GetFixtureA().GetBody().GetUserData());
}
this.world.SetContactListener(listener);

```

This listener is where you'll set up your response to your objects getting near each other.

You can read a little about them in the official Box2D manual, under section "6.3 Sensors".
> 3 votes

---
Tags: physics, box2d
---


# Question
Title: Is hard-abstraction from SDL, OpenGL, OpenAL, Freetype, etc. worth it?
Is it really worth to abstract away from underlying mechanisms by means of pure virtual functions just to get rid of `#include <SDL.h>` in high-level classes? I'll still have high-level classes like Font, Canvas, Texture, but they'll use the libraries directly.

# Answer
Sounds a bit like pre-mature optimization to me -- not so much for execution speed here, but in terms of software architecture.

While it is true that it will be a lot harder to introduce certain abstractions after the fact, i.e., when your code base has already reached a considerable size, you have to ask yourself what you gain from introducing another layer of abstraction:

1. Is it so you could swap out libraries? (Are you ever going to do that?)
2. Is it so your code becomes more portable? (Are you really going to support multiple platforms?)
3. Etc.

I would think there's probably enough other stuff to worry about, and thus avoid introducing more complexity. If you don't already have a good reason to do it, I would say *let it go, Indiana*. Should you ever get to the point where you actually *need* such an abstraction, you could always refactor your codebase (albeit probably not without sweat and tears).
> 2 votes

# Answer
Instead of writing an abstraction layer, which will just add overhead, bugs, and nonsense, make sure that you constrain all uses of the SDL types to your renderer and don't allow them to be littered throughout your code.

Careful design of where you do things, and when, will make it almost as easy to swap out renderers as If you abstracted the whole thing. But without the initial overhead.
> 2 votes

---
Tags: c++
---


# Question
Title: Which is the best LOD method for planet rendering?
I'm currently working on my thesis, it is an engine to render terrains of planetary size.

I'm still finishing my research and I have encountered a lot of stuff about this subject, the problem is that I can't decide on which Level of Detail (LOD) method I should use.

I know about geomipmapping, geometry clipmaps (GPU) and chunked LOD by Ulrich that work good on large terrains and can be used to render 6 faces of a cube and then "spherify" the cube by this method and I understand how to implement all of these methods on GPU using C++/OpenGL/GLSL (using methods like ROAM or any other method that doesn't use a cube is out of my reach because of texturing is a pain). Also I recently got into a tutorial of rendering terrains using tessellation shaders here

So, I don't have the time to implement ALL the methods and see which one is the best and more suitable for a planetary scale and I'm asking here to see if someone has made this kind of comparison and help me decide which method should I implement and use (my tutor is kind of crazy and wants me to do something with an icosahedron, but I can't understand that method unless using ROAM)

Anyways, if you can help me decide or have any other suggestion or method I really will appreciate. One condition is that the method should be able to implement GPU side (at least most of it) to prevent CPU bottleneck.

Another request is that I know there are numerical problems about precision with floats when getting a lot of detail in the terrain, I don't know how to solve it, I read a solution in a forum but can't get to understand how to implement, I lost track of that thread and I would like to know how to solve this precision problem.

I'm currently reading about some matrix transformations to solve the float precision, z-fighting issues, frustum culling with dynamic z-values, and data representation for chunks (using patch space with floats and its position in the world coordinates as double) so I think I can solve the precision problem easily. I still need a comparison between LOD methods with your opinions and suggestions to decide which is better for this project. Take in count difficulty of implementation vs visual quality vs performance, I want the best.

Something I forgot to mention is that the generation is hybrid, I mean, I should be able to render the planet entirely using GPU (heights calculated on the fly) and/or using a base height-map image and add details with GPU (vertex shader). Texturing will be a side part I will trouble latter, right now I'm happy using just colors depending on the height, or maybe using some kind of noise texture generated on the fragment shader.

# Answer
Finally, after a lot of researching I can conclude that, as some one said before, There is not universally "best" method. But my research led me to the knowledge of the following things:

Depending on the mesh you will finally use:

* **Spherified Cube:** any LOD method with quadtree implementation will work just fine, you just have to take care on special cases like borders between faces, in wich case, your quadtree has to have a pointer to the neighbor in the adyacent face in each level.
* **Any other:** I think that ROAM (newer version 2.0 or any other extension as BDAM, CABTT or RUSTIC) will do well, however, these algorithms are hard to work with, require more memory and are a bit slower than other aproaches with cubes.

There are many LOD methods that can fit well, but my personal top 5 are:

1. Continous Distance-Dependent LOD (CDLOD)
2. GPU Based Geomety Clipmaps (GPUGCM)
3. Chunked LOD
4. Rendering Terrains with OpenGL GPU Tessellation (Book: OpenGL Insight, Chapter 10)
5. Geometrical MipMapping

Each one offers an unique way to render terrains, for example, CDLOD has a very easy implementation using shaders (GLSL or HLSL) but is also capable to be implemented on CPU (for legacy hardware) however the goal on Planet Rendering is to explode the best on moderns GPUs, so GPUGCM is the best when you want to squeeze your GPU. They both work very well with data-based, procedural or mixed (terrain based on fixed data or heightmaps and detail added with procedural work) rendering of large terrains.

Also Spherical extension to the basic Geometrical Clipmaps method exists but has some problems because the planar samples of the heightmap has to be parametrized using spherical coordinates.

Chunked LOD, in the other hand, is perfect for legacy hardware, doesn't need any GPU side calculations to work, it's perfect for large datasets but can't handle procedural data in real time (maybe with some modifications, it could)

Using Tessellation shaders is another technique, very new, since OpenGL 4.x came out, in my opinion it could be the best, but, we are talking about Planet Rendering, we encounter a problem that other methods can handle very easy and it is about precision.

Unless you only want your precision to be 1Km between verticies, go for Tessellation shaders. The problem with really big terrains with this method is that jitter is kind of hard to solve (or at least for me, since I'm new to tessellation shaders).

Geomipmapping is a great technique, takes advantage of the quadtree and has a low projected pixel error, but, for planetary rendering you will need to set at least 16+ levels of details, that means you will need (for stitching pourposes) some extra patches to connect different levels and take care of your neighbor's level, this can be tedious to solve, especially using 6 terrain faces.

There is another method, very particular in its own: "Projective Grid Mapping for Planetary Terrain" excellent for visualization, but has its disadvantages, if you want to know more, go to the link.

**Problems:**

* **Jitter**: Most of today’s GPUs support only 32-bit floating-point values, which does not provide enough precision for manipulating large positions in planetary scale terrains. Jitter occurs when the viewer zooms in and rotates or moves, then the polygons start to bounce back and forth.

The best solution for this is to use "Rendering Relative to Eye Using the GPU" method. This method is described in the book "3D Engine Design for Virtual Globes" (I'm sure you can find it on the internet aswell) in where basically you have to set all your positions with doubles on CPU (patches, clipmaps, objects, frustrum, camera, etc) and then MV is centered around the viewer by setting its translation to (0, 0, 0)T and the doubles are encoded in a fixed-point representation using the fraction (mantissa) bits of two floats, low and high by some method (read about Using Ohlarik’s implementation and The DSFUN90 Fortran library).

Although the vertex shader requires only an additional two subtractions and one addition, GPU RTE doubles the amount of vertex buffer memory required for positions. This doesn’t necessarily double the memory requirements unless only positions are stored.
* **Depth Buffer Precision**: Z-fighting. As we are rendering very large terrains, in this case: planets, the Z-buffer has to be HUGE, but it doesn't matter wich values you set for znear and zfar, there will always be problems.

As the Z-buffer depends on a float point interval, and also it is linear (although perspective projection is non linear) values near the eye suffer from Z-fighting because the lack of precision 32-bit floats have.

The best way to solve this problem is to use a "Logarithmic Depth Buffer" http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html

A logarithmic depth buffer improves depth buffer precision for distant objects by using a logarithmic distribution for zscreen. It trades precision for close objects for precision for distant objects. Since we are rendering with a LOD method, far objects require less precision because they have less triangles.

Something important to mention is that all the methods listed (except for the projective grid) are very good when doing physics (collisions mostly) because of the Quadtree base, that is something mandatory if you plan to make a game.

In conclusion, just check all the options available and go for the one you feel more confortable, in my opinion CDLOD does a great work. Don't forget to solve the jitter and Z-buffer problems, and most important: have fun making it!

For more information about LOD check this link.

For a complete demostration about spherifying a cube check this link.

For a better explanation about solving jittering and Z-Buffer precisions, check this book.

I hope you find this little review useful.
> 20 votes

---
Tags: c++, opengl, terrain-rendering, level-of-detail, planet
---


title: Sprite sheet resolutions and Tile Maps

text:
# Question
Title: Sprite sheet resolutions and Tile Maps
I am making a game using Cocos2d-x and want to support multiple mobile phone resolutions and sizes.

Right now I have made my game sprite sheets set on a resolution of iPad Retina's resolution of 2048X1536 and then will use Tiled Map editor to design my game levels.

My question is on what basis do I scale my sprite sheets for different resolutions suppose iPhone etc so that my Tiled Map's design does not get effected when used in the game ?

# Answer
> 2 votes
It depends on your implementation.

A. You can keep tile size constant (e.g. 64px). This way depending on screen resolution the number of tiles that fit on the screen will change. And of course you will need to take care about retina displays, cos they have very high pixels-per-cm density.

B. You can scale your tiles to preserve constant physical size (e.g. 2cm). For that you need to know how many pixels fit into physical 2cm (look into display dpi setting) and scale accordingly.

C. You can choose a simple approach and always render 10 tiles across irregardless of screen size and pixel density.

Pick the way that suits your game best.

---
Tags: textures, sprites, tiles, cocos2d, spritesheet
---


# Question
Title: How can I divide a 3D mesh into small pieces?
I'm considering a manufacturing game. A player should assemble parts of an object in given time. The object will be a 3D mesh model. I want to automatically split the 3D mesh into many small pieces to be provided to players. Each divided piece is needed to have area as similar as possible. And I want to control the number of pieces too within range about 2~6. How can I do this?

I know the method to modify a given mesh like adjusting values of vertices, indices. All I need is the algorithm.

# Answer
One method I used (in a geometry application not a game) was to traverse the mesh using depth/breadth first search and extract each connected component to a separate mesh . This will give you nice results as far as your mesh is composed of parts that are not connected. The problem though is that if your mesh is connected this doesn't work.

The other method I can think of is you can generate a 3D grid based on the shape and the size of the mesh, and split the mesh based on the distribution of the vertices, the problem; this will look ugly and unnatural.

**What I recommend is combining the two methods above.** So the first algorithm will split the mesh into parts and the second one to split each part to uniform number of sub-parts and you can iterate until you get satisfactory results. The problem though "realistic results" is something very hard to do without any human input, so I recommend there are some constraints put by the guy who will make the models for each model, this way you will get some randomness from your algorithm while getting more "realistic results" because of the constraints.

**Edit**: You can also combine some kind of real time constructive solid geometry with the other methods but that might be kind of hard to implement.

**Edit**: Well, most of the models I worked with were exported from CAD applications and were nicely connected (as they would be in real life), so your best bet might be to design your models with this in mind, but anyway you may want to use some kind of tolerance or graph radius; for example if a certain component has graph radius less than K you don't make it a separate part.

You can also use some geometrical attributes of your mesh (as the traverse only use topological properties) one might be using a tolerance; sometimes a vertex will be duplicate (you have two vertices that have the (almost) same value), in a naive BFS they might be treated as disconnected, in real world though, you may want to "merge" them which might not be good for rendering, in this case you need to merge them only when dealing with connectivity issue and not in the vertex buffer that is going to be rendered.
> 3 votes

---
Tags: algorithm, 3d-meshes
---


# Question
Title: Disjointed bones in 3ds Max - Are they a problem?
The title sums up my question fairly well. I'm working with a biped, and I'm not sure whether to put the extra effort into connecting all the bones, or just to leave spaces between each of them. What do you think?

Screenshot:

https://i.stack.imgur.com/35ZsF.png

# Answer
The space or no-space between joints/bones are just cosmetic, and should not pose a problem. The placement of the pivot is the most important factor, it determines the origin of the rotation and should be chosen carefully.

I think you'll be fine. The mesh on the other hand seems very dense, it can affect performance greatly, especially deforming meshes.
> 1 votes

---
Tags: animation, 3dsmax, skeletal-animation, rigging, biped
---


title: Move-Cycle generates unintended numbers

text:
# Question
Title: Move-Cycle generates unintended numbers
I have an image I want to move like it's hovering up and own in a cycle. For that image I have the Y

```
float _sMY = 10;

```

My cycle is this:

```
if (!_hoveredDown)
{
   _sMY -= 0.1f;
}
else
{
   _sMY += 0.1f;
}

if (_sMY < -10)
   _hoveredDown = true;
else if (_sMY > 10)
   _hoveredDown = false;

```

But during this cycle, the image stutters in certain positions and debugging told me that `_smY` goes way to `-5.677342E-06`.

Why do you think this is happening?

Fix, which won't work:

```
float hoverSpeed = 0.1f;
hoverSpeed += (float)(GameTime.ElapsedGameTime.TotalSeconds);

if (_hoveredDown)
{
   _sMY += hoverSpeed;
}
else if (!_hoveredDown)
{
   _sMY -= hoverSpeed;
}

if (_sMY < -10)
    _hoveredDown = true;
else if (_sMY > 10)
    _hoveredDown = false;

```

# Answer
> 2 votes
I noticed a number of strange things in your code. For one, you were adding the game time in seconds to the movement speed of the object. Since the game time is incremental, that would make the object move ridiculously fast after even just a few seconds, (possibly explaining the stutter)

Corrected code follows :

```
//definitions
float hoverSpeed = 0.1f;
//i removed the increment on the hover speed from here.
//from what i saw, it made no sense and would make the object move more and more erratic.

bool _hoveredDown = false;
float _smY = 10;

//this is in your game update loop (i suppose)...
if (_hoveredDown)
{
    _sMY += hoverSpeed;
    // a boolean only has two states, so there's no need to check if it really
    // really really really is the other state if it is false.
    // so just a single if/else will do.
}
else
{
    _sMY -= hoverSpeed;
}

if (_sMY < -10)
{
   _hoveredDown = true;
}
else if(_sMY > 10)
{
  _hoveredDown = false;
}

```

---
Tags: c#
---