# Question
Title: 8-bit Game: To pre-scale images, or post scale my Cocos2d scene. Which is the better approach?
I'm wanting to develop a game with an 8-bit feel. Since this game is mostly for my personal enjoyment, I've set a requirement that I want my game to have an 8-Bit feel to it that is most similar the 8-Bit systems of yore, on a lovely CRT TV.

This is also my first Cocos2d project so I don't know which approach is better. I'd like the general advice of the community on how to render my game. I've come up with two possible approaches. Please advice which is better.

---

**Approach #1**

Create images for backgrounds and sprites using the "8-bit" resolution of my game. After I'm done making an image, I scale it up and I save two variants; the standard sized one and the "@2x" variant.

When I render the game, everything looks very 8-Bit but I will still need to apply mathematics to every animation so that my virtual pixels always shift by 4 or 8 pixels (for retina displays) on the screen when they move.

This approach doesn't sound difficult but it seems like it could become a bit annoying and tedious.

---

**Approach #2**

Generate all content in my image designer at the exact resolution of my virtual screen. When I generate my scenes in Cocos2d, I generate them all with the "virtual resolution". When the scene is displayed on the iOS screen, I scale the entire scene up to the resolution of the device.

I think this could be the simplest approach since all of my sprite and background movement mathematics can just behave as normal. However, I'm not sure that this approach is even possible. Furthermore, I know that within iOS, graphic scaling has an anti-alias affect that gets applied to graphical objects as they scale-up. Obviously, I'd want to cut this affect off and just use a "nearest neighbor" algorithm to scale-up my scene.

If I can't cut off the scaling anti-aliasing, I don't want to use this method. However, if I can setup such a rendering system, I think this approach would be best.

---

So, my question is simple. Can I use approach #2 and, if so, which approach is really easier to work with in Cocos2d and iOS?

# Answer
> 4 votes
Use Approach #2 (render to a small offscreen texture, then display that texture onscreen scaled up using nearest-neighbor texture sampling), because:

1. **The asset workflow is simpler**. You can edit individual pixels, without having to quadruplicate them, or manually scale everything up.
2. **The assets will probably take up less space on disk**. This is particularly important when distributing mobile apps.
3. **Your offscreen rendering code will have fewer pixels to push, which will probably improve performance and/or consume less battery life.** Rendering a game screen typically involves overwriting a lot of pixels (drawing the background first, then drawing sprites on top of it). By rendering to a smaller texture offscreen, you're overwriting a smaller number of pixels than you would overwrite if you were rendering at a larger pixel scale. Rendering the game screen is also typically pretty expensive per-pixel since you'll probably be using complex shaders, whereas upscaling and nearest-neighbor texture filtering a single texture are both very cheap on modern OpenGL hardware.

Here's how:

```
// Create a small offscreen texture
CCRenderTexture *rt = [CCRenderTexture renderTextureWithWidth:320 height:240];

// Start capturing all rendering operations to the offscreen texture
[rt begin];

// Render
...

// Stop capturing to the offscreen texture
[rt end];

// Use GL_NEAREST (nearest-neighbor) texture sampling
[rt.sprite.texture setAliasTexParameters];

// Create a sprite from the offscreen texture
CCSprite *s = [CCSprite spriteWithTexture:rt.sprite.texture];

// Render the sprite fullscreen
...

```

# Answer
> 0 votes
If you're calculating the render scale real-time, you're losing FPS. Consider authoring your images at 2x scale, and using that to render them at 1x scale.

---
Tags: iphone, rendering, cocos2d
---


# Question
Title: Tile collision, can't get correct behaviour
I define a tile with a rectangle. This is displayed below.

```
public class Tile : Sprite
{
    Rectangle rectangle;

    public Rectangle GetRectangle
    {
        get
        {
            return rectangle;
        }
    }

    public Tile(Texture2D texture, Vector2 position, int tileWidth, int tileHeight) :
        base(texture, position)
    {
        rectangle = new Rectangle((int)position.X, (int)position.Y, tileWidth, tileHeight);
    }
}

```

These tiles are created by my level editor and placed on a map.

I have a player class here but I can't get it to behave with my tiles. Either I can get collisions working on the y, but then the character can't move on the x. Or I can get it moving on the x but if the player walks into tiles from the side the character won't respond.

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using GameStateManagement;

namespace NecromancerGame
{
    public class Player : Sprite
    {

        private float speed;
        private float jumpHeight;
        Rectangle rectangle;
        //private Vector2 velocity;
        private float timer;
        private float timeToChangeFrame;
        private int frameNumber;
        private int fps;
        private int frameWidth;
        private int frameHeight;
        private bool facingRight;
        private float gravity;
        SpriteEffects effect;

        public Vector2 GetPosition
        {
            get
            {
                return position;
            }
        }

        public Player(Texture2D texture, Vector2 pos, int fps, float moveSpeed):
            base(texture, pos)
        {
            int timer = 0;
            int frameNumber = 0;
            timeToChangeFrame = 0.20f;
            this.fps = fps;
            frameWidth = texture.Width / (fps + 1);
            frameHeight = texture.Height;
            facingRight = true;
            speed = moveSpeed;
            rectangle = new Rectangle((int)position.X, (int)position.Y, frameWidth, frameHeight);
            gravity = Stats.gravityStrength;
            origin = new Vector2(frameWidth / 2, frameHeight / 2);
        }

        public void StartJump()
        {
            velocity.Y = -Stats.jumpHeight;
        }

        public void ChangeDirection()
        {
            facingRight = !facingRight;
        }

        public void Update(GameTime gameTime, List<Tile> tileList)
        {
            Vector2 oldPosition = position;
            bool colliding = false;
            timer += (float)gameTime.ElapsedGameTime.TotalSeconds;
            if (timer > timeToChangeFrame)
            {
                frameNumber++;
                if (frameNumber >= fps)
                {
                    frameNumber = 0;
                }
                timer = 0;
            }

            if (facingRight)
            {
                velocity.X = speed;
                effect = SpriteEffects.None;
            }
            else
            {
                velocity.X = -speed;
                effect = SpriteEffects.FlipHorizontally;
            }

            velocity.Y += gravity;

            Vector2 potentialPosition = oldPosition + velocity;
            Rectangle potentialNewPosition = new Rectangle(rectangle.Center.X + (int)velocity.X, rectangle.Center.X + (int)velocity.Y, frameWidth, frameHeight);

            for (int i = 0; i < tileList.Count; i++)
            {
                if (potentialNewPosition.Intersects(tileList[i].GetRectangle))
                {
                    //Point point = potentialNewPosition.Center - tileList[i].GetRectangle.Center;
                    position = oldPosition;
                    //position = oldPosition;
                    //velocity.X = 0;
                    //position.X = oldPosition.X;
                    colliding = true;

                }
            }

            position += velocity;

            rectangle.X = (int)position.X;
            rectangle.Y = (int)position.Y;

            base.Update(gameTime);
        }

        public override void Draw(SpriteBatch spriteBatch)
        {
            base.Draw(spriteBatch, frameNumber, frameWidth, frameHeight, effect);
        }

    }
}

```

# Answer
> Or I can get it moving on the x but if the player walks into tiles from the side the character won't respond.

Well, I've noticed one fallacy in your logic that is most probably what's leading to this:

```
for (int i = 0; i < tileList.Count; i++)
{
    if (potentialNewPosition.Intersects(tileList[i].GetRectangle))
    {
        position = oldPosition;
        colliding = true;
    }
}

```

If a collision is found, the player's movement is simply 'cancelled'. Here, if he collides with a block, he simply is sent back to where he came from. What we should do when dealing with tile collision is not cancel a movement, sending the object back to its starting position, but rather *correct* it.

What your algorithm should do is place your player's hitbox outside of the colliding tile, but no further from it. For example, considering that your player is basically a rectangle, if it was found to be inside a tile, you could make it so that `Player.Right = Tile.X` (if he was moving rightwards), or `Player.Bottom = Tile.Y` (for downward movement), or `Player.X = Tile.Right` (leftward), or `Player.Y = Tile.Bottom` (upward). This places him right alongside the tile, outside.
> 1 votes

# Answer
Not saying this fixes the problem but this line seems suspect:

```
Rectangle potentialNewPosition = new Rectangle(rectangle.Center.X + (int)velocity.X, rectangle.Center.X + (int)velocity.Y, frameWidth, frameHeight);

```

Should be:

```
Rectangle potentialNewPosition = new Rectangle(rectangle.X + (int)velocity.X, rectangle.Y + (int)velocity.Y, frameWidth, frameHeight);

```

There were 2 problems:

1. You were using rectangle.Center.X for both x, y
2. You were using the center of the player rectangle as your top, left when creating potentialNewPosition rectangle.
> 1 votes

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


title: DirectX post-processing pipeline

text:
# Question
Title: DirectX post-processing pipeline
I'm trying to make a simple post processing pipeline, depicted as follows with 3 effects in this case:

```
        |------|    |------|    |------|
   I -->|Shader|-O->|Shader|-I->|Shader|-O->
        |------|    |------|    |------|

```

`I` and `O` stand for a pair of 2 `ShaderResourceViews`/`RenderTargetViews`.

My plan was to do the following:

1. Create a shader resource and render target for each the input and the output
2. Apply the shader
3. Swap input and output to be used for the next shader
4. Goto 2.

This sounds somewhat confusing, but basically the same 2 `ShaderResourceViews` /`RenderTargetViews` should be reused for each stage of the post processing pipeline.

Is this possible, or do I have to create separate input and output `ShaderResourceViews` /`RenderTargetViews` for each stage of the postprocessing pipeline?

# Answer
> 3 votes
You'll need to create the textures with both the `D3D11_BIND_RENDER_TARGET` and `D3D11_BIND_SHADER_RESOURCE` bind flags, and you must take care to unbind them from their previous assignment before swapping them, but it should work fine.

Also, make sure the format you want to use is listed in the supported render target formats, and not listed in the formats not supported for Texture2D here: http://msdn.microsoft.com/en-us/library/windows/desktop/ff471325(v=vs.85).aspx

---
Tags: directx, directx11
---


title: Why Game engines use C++?

text:
# Question
Title: Why Game engines use C++?
1. Why most of the game engines use C++ to develop game?.
2. Why not java or C#?.

# Answer
> 7 votes
I would say it's because C++ is, among major languages, the one that works at the highest level, without sacrificing access to low level control.

In C++ you have complete control of what is going on with your program, which may be desirable, especially for severely restricted platforms such as consoles.

For example: garbage collection as available in C# and Java is usually non-deterministic. Not only there is no accurate way for you to know exactly how much memory you're consuming at a given moment, but also you don't know when the garbage collector will run, probably slowing your main thread.

In consoles, even up to the Game Cube and dare I say the Wii, having extreme control of your program's timing is crucial to develop games that perform well. Many games time the game processing exactly while after a scanline has finished, and before the next one comes in. You only have a few microseconds to do work, which translates to a fixed amount of CPU ticks, so unless you know how exactly your code will be assembled, where your cache misses will be, and how long they will take, you won't be able to push the console to the limit. Doing this is impossible if a garbage collector is randomly popping in and messing with your timings.

This is of course historical. Modern consoles and PCs are more relaxed, and you can do a lot without really pushing the machine to the limit, so now you have XNA and PSM that let you program in C#, Android which lets you program in Java, and even Flash and HTML5 which let you program in variants of ECMAScript.

But even so, C++ will let you go to the edge when doing optimizations, as you can even eventually do inline assembly wherever you want. Java and C# simply don't let you do this.

# Answer
> 2 votes
The generally used graphics libraries API, like DirectX and OpenGL are written in C, and provides you an C interface for usage. They have bindings to other languages, but most of these based on the C implementation, or tries to use the API procedures through his own native interface (eg. Java - JNDI) which is written mostly in C...

# Answer
> 1 votes
C++ is generally considered "better" than other languages, for several reasons. Mainly, almost all professional programmers know C++, but aren't as familiar with other languages. Therefore, there is a larger variety of third-party libraries and tools available for C++.

Also, Java and similar languages must run in a virtual machine, which is considered slower or less efficient than native code produced by C++.

However, in my experience, the speed and efficiency of these languages is not what makes the decision, it is only familiarity.

It should be noted that many games run on a C++ engine, but most (if not all) of the game's logic is implemented in a scripting language, such as Lua.

---
Tags: c++
---


# Question
Title: DirectX / Instance Buffer - How To Use Instance Buffers To Enable Reuse of VertexBuffer Data?
I created a simple Model framework in C++ 11 so that the same model can be rendered in different parts of a scene.

What I am trying to figure out is how to reference VertexBuffer data already "set" in the GPU for reuse as I draw different instances(100x) of different geometries, (i.e., square, triangle, etc).

I apologize that I had not understood the complexity of this particular question and have not been very good at making my question clear. As I am researching, I am clarifying the detail of the question.

Given: 1. Model Vertex Data is Stored in a Vertex Buffer, (that I refer to as the static/default Vertex Buffer). 2. Instance Position, (Vertex) data is stored in an instance buffer. 3. Constant Data, (World, View(to be changed), Projection) is stored in the Constant Buffer.

How Do I: 1. Update the entire Instance Buffer without having to re-bind the Static Buffer, and/or 2. Update only one instance in the Instance Buffer without having to re-bind the entire Instance Buffer

In the following code: I am defining both the Instance and Static Vertex Buffers' Element Description at the same time... Want to break this up, so that I can call VertexBuffer's initialization methods once, and then Instance Buffer's stuff over and over again:

```
void ModelRenderer::InitializeInputElementDescription()
        {
            // InputElementDescription = new D3D11_INPUT_ELEMENT_DESC[2]();

            InputElementDescription[0] = D3D11_INPUT_ELEMENT_DESC();
            InputElementDescription[0].SemanticName = "POSITION";
            InputElementDescription[0].SemanticIndex = 0;

        InputElementDescription[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
            InputElementDescription[0].InputSlot = 0;

            InputElementDescription[0].AlignedByteOffset = 0;
            InputElementDescription[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
            InputElementDescription[0].InstanceDataStepRate = 0;

            InputElementDescription[1] = D3D11_INPUT_ELEMENT_DESC();
            InputElementDescription[1].SemanticName = "TEXCOORD";
            InputElementDescription[1].SemanticIndex = 0;

            InputElementDescription[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
            InputElementDescription[1].InputSlot = 1;

            InputElementDescription[1].AlignedByteOffset = 0;
            InputElementDescription[1].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA;
            InputElementDescription[1].InstanceDataStepRate = 1;
        }

```

Shader File: My Semantic isn't being recognized somehow here, but I can manually set a shape's position.

```
cbuffer ModelViewProjectionConstantBuffer : register(b0)
{
    matrix model;
    matrix view;
    matrix projection;
};

struct VertexShaderInput
{
    float3 position : POSITION;
    float3 instance_position : TEXCOORD;
    // float3 color : COLOR0;
};

struct VertexShaderOutput
{
    float4 pos : SV_POSITION;
    // float3 color : COLOR0;
};

VertexShaderOutput main(VertexShaderInput input)
{
    VertexShaderOutput output;

    // Move the Instance someplace into the world.
    float3 translatedPosition = input.position + input.instance_position;

    float4 pos = float4(translatedPosition, 1.0f);

    // Transform the vertex position into projected space.
    pos = mul(pos, model);
    pos = mul(pos, view);
    pos = mul(pos, projection);
    output.pos = pos;

    // Pass through the color without modification.
    // output.color = input.color;

    return output;
}

```

Initializing InstanceBuffer: Something like this would be called every frame, or so. But right now, I am sending this info along with the static vertex buffer info:

/*****\*****\*****\*****\*****\*****\*****\*****\*****\*****\*****\*****\******/ void ModelRenderer::InitializeInstanceBuffer() { HRESULT result;

```
instances = new Position[2]();
instances[0].X = 0.0f;
instances[0].Y = 0.0f;
instances[0].Z = 0.0f;

instances[1].X = 0.5f;
instances[1].Y = 0.5f;
instances[1].Z = 0.5f;

// Set up the description of the instance buffer.
instanceBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
instanceBufferDesc.ByteWidth = sizeof(Position) * 2;
instanceBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
instanceBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
instanceBufferDesc.MiscFlags = 0;
instanceBufferDesc.StructureByteStride = 0;

instanceSubResourceData.SysMemPitch = 0;
instanceSubResourceData.SysMemSlicePitch = 0;

instanceSubResourceData.pSysMem = instances;

result = DeviceManager::Device->CreateBuffer(&instanceBufferDesc, &instanceSubResourceData, &instanceBuffer);

delete [] instances;

```

}

Here, I am setting my VertexBuffer and InstanceBuffer into the InputAssembly (IA), both at the same time. I would only want to do this once on initialization, and then call a similar method that doesn't reference the initial static vertex buffer data again:

```
/******************************************************************/
    void ModelRenderer::Stage()
    {
        DeviceManager::DeviceContext->OMSetRenderTargets(
            1,
            DeviceManager::RenderTargetView.GetAddressOf(),
            DeviceManager::DepthStencilView.Get()
            );

        DeviceManager::DeviceContext->UpdateSubresource(
            ConstantBuffer.Get(),
            0,
            NULL,
            &ConstantBufferData,
            0,
            0
            );

        DeviceManager::DeviceContext->UpdateSubresource(
            instanceBuffer,
            0,
            NULL,
            &instanceSubResourceData,
            0,
            0
            );

        unsigned int offsets[2] = {0,0};
        unsigned int strides[2];

        ID3D11Buffer* bufferPointers[2];

        strides[0] = sizeof(NS::Vertex);
        strides[1] = sizeof(Position);

        bufferPointers[0] = ModelRenderer::VertexBuffer.Get();
        bufferPointers[1] = ModelRenderer::instanceBuffer;

        DeviceManager::DeviceContext->IASetInputLayout(ModelRenderer::InputLayout.Get());

        DeviceManager::DeviceContext->IASetVertexBuffers(
            0,
            2,
            bufferPointers,
            strides,
            offsets
            );

        DeviceManager::DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        DeviceManager::DeviceContext->VSSetConstantBuffers(
            0,
            1,
            ModelRenderer::ConstantBuffer.GetAddressOf()
            );
    }

```

Thanks for the help!

# Answer
> 4 votes
You could go about this in different ways.

Usually, you have a model's geometry centered around the origin (0,0,0), and to place it somewhere in the world you would use a world matrix, which offsets the entire model to a desired new position.

This world matrix can reside in a constant buffer accessible to the vertex shader, where it would be combined with the view and projection matrices, and then used to transform your vertex data.

Constant buffers allow you to provide variables to your shader code, however they remain constant while a shader runs. An example in shader code:

```
cbuffer perObject
{
    float4x4 World; //world matrix carrying position information
    float4 objColor;
};

cbuffer perScene
{
    float4x4 ViewProjection; //view & projection matrix
};

```

Here is a tutorial that covers constant buffers, among other things: http://www.rastertek.com/dx11tut04.html

And an article on MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476898(v=vs.85).aspx#Shader\_Constant\_Buffer

With this approach you can move your model to different positions by calculating a new world matrix and updating the constant buffer containing the world matrix, no need to update the whole vertex buffer.

If you are drawing many instances though, you could use an instance buffer in which you store all the different positions your object should be drawn at.

An instance buffer is not much different from a vertex buffer, the elements from the instance buffer will be received as parameters in your vertex shader.

You would call `ID3D11DeviceContext::DrawInstanced(numVertices, numInstances, vertOffset, instOffset)` or `DrawInstancedIndexed(..)`, and your vertices will be drawn numinstances times, each time supplying a different element from your instance buffer to the vertex shader.

Here is a tutorial that covers instancing in D3D11: http://www.rastertek.com/dx11tut37.html

---
Tags: directx, directx11, pipeline, vertex-arrays, c++
---


# Question
Title: Practical Way to Store and Communicate Data for a Multiplayer Game Like This
I am working on my first multiplayer game, as I have become bored with my single player indie games. However, I have a question. Players will be placing items on a map which is arranged in a grid, what is the best way to store this data on a server?

UPDATE: So essentially this is what I need to do. I currently have a database with player money, etc. I need some way of once the player places something on the map, for the server to check my database for how much it costs, so it can see if the player is cheating or not. My issue is I don't know the best way to communicate this data to the server and have it store it (the location of different things on the map, etc)

I was originally thinking to serialize the map, send it to my server, and store it in my database, but to query the database EVERY SINGLE TIME that the user changes something on the map seems to be a little ridiculous.

# Answer
When the server needs to have constant access to the map, then it would be better to load it once and keep the map in the servers memory. That way you avoid contacting the database all the time. When you don't want to lose any game state when the server crashes, you could save the map sporadically (like every few minutes, assuming that the players actually changed something).

You didn't write anything about the gameplay concept and the scale of your game, but when your maps are very large, it might be a good idea to divide them into sections ("chunks") and store these individually in the database. That way you don't have to load the whole map, but only the chunks close to the active players. You also don't need to save the whole map, but only those chunks which have changes.
> 1 votes

# Answer
What I would say is to keep all data in the client as a "backup like" storage then whenever a player does anything it gets what was changed and sends it to the server.
> -1 votes

---
Tags: networking, multiplayer
---


title: Good map file structure?

text:
# Question
Title: Good map file structure?
I need a map file structure for my game but does anyone know a good way to map it out? I was thinking something like this:

```
name=MyMap
add[floor[stone]][solid][20, 640]
add[playerspawn][20, 620]

```

# Answer
Planning on making these map files by hand? You have 409,599 more lines to write if you want to fill a 640x640 tiled map.

You should store the map in a binary format. An easy way to do that is to serialize the data structure you're storing the map with in RAM.

It would be far easier to write a simple visual editor that allowed you to place tiles and write a binary file, than to write out so many lines by hand.
> 3 votes

# Answer
Depending on what you are going to do for a game, this is diffrent. In other words, An fps, might store additional stuff on the map like, monsters, spawn points of monsters, pickups, and more.

While a RTS might only store, the diffuculty to move there, the tile, and what kind of protection this tile gives.

But you structure there looks wery promising. seems like it will be easy to just add up stuff. and easy to remove stuff. And flexibility is allways a good choise.
> 0 votes

# Answer
I'd recommend you the XML format and, specifically for the tiles, you can try to put just the tile number, something like this:

```
<Map>
   <Tiles> 0 10 2 3 4 5...
           .
           .
           .
   </Tiles>

   <CollisionLayer>
           0 0 1 1 0 0...
            .
            .
            .
   </CollisionLayer>

   <BlendLayer>
            .
            .
            .
    <BlendLayer>
</Map>

```
> 0 votes

# Answer
This depends on various points. Since you didn't really go in-depth with your current setting (game-type, platform, etc.), all I can do here is do assumptions.

1. ### The dimension

2D vs. 3D, the probably biggest aspect. While storing a pure 2D map (even if it has multiple layers) as a text-like file is still possible, doing the same with a 3D file would be madness.

As an example, the UDK example map "Day and Night" is 189214 kb big. If you were to type every byte per hand, this would take ~150 hours in total, given that you can type 6 days straight without pause.

So clearly, if you aim to create a 3D map, don't even think about creating those by hand.
2. ### The game type

Various different games require different features. For example:

* A side-scrolling shooter requires lot of spawn-points for enemies and practically one big background-image, but the player is practically in a moving box.
    * A jump 'n' run might be built like a list with "blocks" and other things in it.
    * A "Pokémon"-like RPG with a grid, multiple layers and events could quickly go beyond everything you want to write by hand and you'd end up writing your own map-creator tool in the process of development.
3. ### The platform

I have no idea what platform you're working on, PC, Mac, iPhone, Android, GBA, etc., but I have to inform you that various gaming platforms already have either established game SDK's or Frameworks, such as GameKit for iOS, which already comes with every XCode install.

Do a Google-search for your platform and maybe ask around to see which frameworks fit your game and platform. While I do encourage you to do things on your own as you begin, seeing how "pros" do things can't hurt. (*E.g. it helped me a lot to see how notch stores his blocks in Minecraft.*)
4. ### The tools

Depending on the size of your game, you might feel the need arise to add a map editor to your game. Not just for the user, but also for yourself! I mean, if you write a set of ten maps, each consisting of a 25 x 25 x 1 tiles, then you could do it by hand, but as soon as events, layers and other more advanced things come in, I strongly advise to create such a tool.
> 0 votes

---
Tags: maps, file-format, file
---


# Question
Title: OpenGL RTT FrameBuffer question and Rendering to texture while sampling it
What i need to do:

* Blur the selected texture and pass the texture to another effect for postprocessing.
* Notice that i want one texture passed all over.

How do i want to do this:

* Bind the FBO ( with texture to be blurred attached as colorbuffer )
* Change the FBO viewport size to match the texture size
* Enable the shader
* Bind the texture
* Render viewport sized quad with the texture and output to that texture via FBO colorbuffer
* Unbind texture
* disable shader
* Disable fbo
* ...
* pass that texture to another effect..

What i have already done:

* A FBO with ColorBuffer attached ( the texture i want to blur ),
* The shader
* All the other reqd stuff..

What's the problem?

* When i want to blur texture and i bind that texture as a color buffer to my FBO, and then pass the texture via uniform to the shader while rendering to sample it (and blur), the results are not stored. Seems like FBO can't have the same texture stored as output and sample it at the same time ( kind of understandable ).

Question:

* Is this normal behavior ? How do i approach 'blur a selected texture' so that i can pass one texture over to another effect to work on it ?

I can imagine a 'dummy' texture within the effect class to which FBO renders to and then it gets copied to a texture that was requested to be modified.. Any better option ?

Thanks for shedding a bit of light on this, i think i need some logic help in here.

# Answer
> Render viewport sized quad with the texture and output to that texture via FBO colorbuffer

This is called a "feedback loop". It is *decidedly* wrong. And while texture barrier could save you in certain cases, it can't save you when you want to do a blur filter.

You're going to have to render to a different texture than you read from.
> 2 votes

---
Tags: c++, opengl, shaders, glsl, opengl-es2
---


# Question
Title: Is "forcing the user" to accept the terms an acceptable design in a smartphone/iPhone game?
I am about to release my first iPhone game, has been a long project and I involved several people. My lawyer strongly recommended me to add a "terms and conditions" page at the beginning of the app and to allow the user to continue to the game only if he presses "I agree".

In the iTunes game description I will include a link to the EULA and a warning saying "DISCLAIMER: The game will ask you to agree to the following EULA: HTTPLINK EULA.".

My main reason for adding this is that I got the license to use the name from relatively famous people and I need to put the terms and conditions in order to protect both my company and my licensee.

Some developers suggested me to avoid this strongly as I will lose user base. From my perspective I think that including terms and conditions is a fair thing to do and non-smartphones users are used to accept EULAs. It is true that on smartphones you rarely see this and can this really affect my game? Would you argue against my design choice to allow the user to play only if he accepts the EULA?

Are there among you any smartphone game developers that have had similar concerns and have asked their users to accept the EULA?

# Answer
The iTunes App Store already has a process in place for adding custom terms and conditions to any app you upload.

http://developer.apple.com/library/ios/#documentation/LanguagesUtilities/Conceptual/iTunesConnect\_Guide/8\_AddingNewApps/AddingNewApps.html

Scroll down to "Providing an End User License Agreement".

Tell your lawyer about this if he doesn't already know. I'm guessing there's language in the iTunes EULA that says by downloading any app you're already agreeing to its EULA (a standard one is provided).
> 8 votes

# Answer
I don't know about other countries, but in the Netherlands, forcing an agreement after the purchase has already been made invalidates the agreement.
> 2 votes

# Answer
I don't think I've ever seen any (Android) game so far doing something like that, even if it's been some third party working for a bigger company/licensor and I'd consider it a major deterrent.

The only similar thing I've seen so far are main menu buttons such as "license", "open source licenses", "third party licenses" or something similar showing required notices such as LGP licenses or anything similar.

I'd try to talk to the licensor to get a relatively short (and still satisfying for them) legal notice such as "xyz is a registered trademark of...". Display this on the launch/title screen together with another line and something like "By playing this game you agree to be bound by the \[gamename\] end user license agreement." being clickable to view the whole thing.

As for the real people portion, I'd say displaying a simple notice at startup "All people and places are strictly fictional." or anything like that should be sufficient, but you better ask your lawyer about that part (and the whole thing).
> 1 votes

# Answer
EULA is something that distracts the gamer basically..in my opinion.

But if your lawyer is strongly thinks it should be there then there is no point of discussion in legal terms. of course your lawyer is in a better position to judge the scenario as he is having all the ground level facts.

I would suggest you to go on with your lawyer's suggestion.
> 1 votes

---
Tags: game-design, iphone, legal, user-experience, ui-design
---


# Question
Title: How do I calculate how an object will move from one point to another?
Here's the problem: A player starts the game in the 0 coordinate (x=0,y=0). When the user clicks on the screen, it returns the coordinates of the destination. Now the player has to move from its current position A(0.0) to B(x,y). Take into account that B is in the first Quadrant so x\>0 and y\>0.

How will the player move? I know that I will have to use this: `atan2(positionY-destinationY, positionX-destinationX)` to get the angle.

Now what? How will the player move with a fixed velocity (which by the way will be a variable, so a player may move faster while using some "items")?

Whose answer is better? What is more accurate? Trigonometry or Linear Algebra?

# Answer
**Basic trigonometry example**

cosine for x axis

sine for y axis

speed is whatever you would like the movement each time to increment by... Obviously the higher the number the more pixels it will move at any given time so the quicker it will be.

```
dx = (double) (Math.cos(angle) * speed);
dy = (double) (Math.sin(angle) * speed);

A.x += dx;
A.y += dy;

```

**Linear algebra example**

Check Sidar's answer :).. Explains it way better than I could.

This is in java... You can easily convert it to C++ though.
> 6 votes

# Answer
To add to Savlons answer:

There are two ways of doing this

Vector2D objects(Assuming your positions are vectors):

```
Vector2D diffVec(B.posVec-A.posVec);
diffVec.normlize(); //Assuming it's applied on the vector itself
// and does not return a new one.
//This vector is now a unit vector which represents the heading/Direction
//without the "speed" (Well its speed is 1, more precisely its MAGNITUDE is 1).

diffVec.multiply(speed);

camera.velocity = diffVec;

```

The normalize function would probably look something like this:

```
void Vector2D::normalize(){
     float len = length();
     this.x /= len;
     this.y /= len;
};

 float Vector2D::length(){
    return sqrt(x*x+y*y);
 };

```

Now if you're not using vectors this could be translated to:

```
float dx = destinationX-positionX;
float dy = destinationY-positionY;

```

Let's pretend dx and dy are the components of an imaginary vector. ( And by components I mean the x and y properties ).

We can perform the same calculations as we have in our Vector2D class: First we need to "normalize" our imaginary vector by dividing it by its length. Pythagoras theorem, remember that one?

```
float length = sqrtf(dx*dx+dy*dy);

```

Now we use this to normalize our imaginary vector:

```
dx/=length;
dy/=length;

```

Now if we were to apply the Pythagoras theorem on our new dx and dy value you will notice that the length is 1. Meaning that we have a direction, and a magnitude of 1. To change it to our speed simply multiply each component by it.

```
dx *= speed;
dy *= speed;

cam.velocityX = dx;
cam.velocityY = dy;

```

Imagine a vector to be an arrow with a specific length. When you normalize it you bring the length to one.

So if you multiply it ( by a scalar ), the speed in this case, the x and y components adjust accordingly that the length of the vector is the speed it's multiplied with.
> 11 votes

# Answer
Forget atan2. You don't need angles. Think in terms of linear algebra approaches.

You have a source and a destination. Subtract source from destination to get a vector representing the change. Normalize this. You now have a unit vector pointing from source to destination. Multiply by speed. You now have the offset to apply each update. It's that easy.
> 8 votes

---
Tags: c++, movement, maps
---


title: Road / river generation on 2d grid map

text:
# Question
Title: Road / river generation on 2d grid map
This is a newbie question, but here it goes:

My map is a 2d grid, and I want to generate roads and rivers. The route from the starting to ending point must not be the optimal route in number of tiles. Instead, they should have a certain level of randomness (turns).

Is there a standard algorithm for this kind of thing?

Cheers!

**UPDATE:**

This is the result of playing with weights on the grid, and applying a shortest path algorithm (Bellman-Ford) using the jgrapht library. I went with Donutz' answer after all.

http://pastebin.com/AGQGK5ik

# Answer
> 19 votes
You can generate the optimal path using A\*, then distort it with midpoint displacement.

This will ensure your endpoints are met and allow you to control the randomness to a great degree. For example, I would not randomize roads as much as rivers. Whatever intelligence is building roads typically attempts to be optimal about it.

Take care to ensure that if your map has obstacles, you check after each iteration that you're not crossing through those obstacles.

Another method would be to generate Perlin noise after finding the optimal path, then shift your points based on the noise generated. For example, using this noise:

Then show with the optimal path in red and the shifted path in blue:

Notice how the shifted path has "settled" into the darker areas of the noise. The same way a river might flow through a valley.

One benefit of the Perlin noise choice is you can factor in your obstacles and avoid them as part of the algorithm.

# Answer
> 3 votes
The A\* algorithm will also allow you to assign values to tiles indicating their suitability. For instance, you can assign the lowest cost scores to low land for rivers, to flat land (but not swamp) for roads, and generate based on that. This doesn't give you the shortest route, but it does give you the most efficient route. Apply a little randomness to your tile values and you can get some sub-optimal routes.

# Answer
> 2 votes
What about when height is a factor? I can make a heightmap with diamond square algorithm. I was thinking of adding some random water to each tile and then iterating through and moving water to lower elevations until it was all settled, but that would slow, and would probably make lakes, not rivers.

I was also thinking of looking at normals for each tile. If 2 normals point towards each other, then that must be a valley. Water would collect in a valley. If they point in the same direction or away from each other, water wont collect. This would probably be faster than the iteration method, but might not make lakes, only rivers. I'd have to play around with it to keep from turning every instance of tiles point towards each other into a river.

---
Tags: algorithm, maps, tilemap, grid, content-generation
---


# Question
Title: Creating a custom binary format for 3D meshes
I've seen people saying it's better and faster to use a custom binary format for your 3D models, based on your needs, instead of using exchange formats. But, I'd like to know how to create a basic format, that contains just vertex and index data, how to write this data into a binary file and read it. Much obliged.

# Answer
What you ultimately end up using at runtime is going to be processed version of your exchange formats whether you do it offline or at runtime. The main differences are:

1. If you do it at runtime then you're going to end up paying the processing cost repeatedly and
2. You probably want to spend as little time processing and optimizing as possible so your load times are reasonable

I'm not sure what your use case is but I assume you'll be putting the data into either a D3D or OpenGL set of index/vertex buffers. It sounds like you're already familiar with what an index/vertex buffer is, so I think the part you might be missing is what D3D calls the vertex declaration.

OpenGL does the same thing but I find it less well defined conceptually. You'll want to take a look at the OpenGL wiki for Vertex Specification paying particular attention to glVertexAttribPointer.

Anyway, the vertex declaration specifies in the type of each component and where it occurs in a vertex. For example, a vertex declaration could look something like:

* \[Offset 0\] - Position - 3 32-bit floats (xyz)
* \[Offset 12\] - Texture Coords - 2 32-bit floats (uv)
* \[Offset 20\] - Colour - 1 normalized packed ARGB value (or RGBA, or BGRA, or... depends on the system)

Given this vertex declaration, you would then proceed to write out your vertex buffer using this description. I generally tend to just match it with a straight C structure:

```
struct MyVertex
{
    Vector3F Position;
    Vector2F UV;
    int32_t mColour;
};

```

Create an array for all the vertices, populate them as appropriate and dump that and the vertex description to a file.

On the runtime side, you'll then load your data into memory, and then make the appropriate calls to D3D/OpenGL to say "my vertex format is this" and construct your vertex buffer by passing a pointer to your data array.

Index buffers are basically identical except you just specify the size of each index (8 bit, 16 bit, etc.).

It gets slightly more complicated if you want to have different vertex buffers supplying different streams of data, but I hope that's good enough to help you understand the general idea.
> 9 votes

# Answer
I've implemented such offline format near month ago for my engine. The basic algorithm is:

1. Write formal specification for output binary file in word processor. Header + data blocks. Data types, offsets, descriptions of each element of each block table.
2. Write offline exporter from your 3D editor into C++ code text headers using embedded scripting language. Then coding this try to export everything there. verts xyz, color verts, all UVw texture channels, indicies, faces, edges, face normals, vertex normals, binormals, tangents, materials, objects names, quaternions and matricies for each keyframe, bone weights, bone lists, animation metadata(fps, frame quatity) e.t.c.
3. Include headers with data to C++ offline converter project using a pre-build script. Run project and compile headers text data files to binary. Use specification from step 1 to code converter correctly. Here you should care about attributes data types. i.e. you can store vertex XYZ as float, short or just char. It's important to add support to each reasonable data type here and at step 5.
4. Write online loader of your file. Simply read fileheader into predefined struct and put each data block to char\*
5. Write online shader generator, render code generator and VBO initializer using information about exported attributes in file header and mesh properties.
6. Render

Do not forget to add support for vertex data compression, triangle strips, multiple files export.

Just simple vertex coords and index data export is insufficient to render. You need more data. As much as can be extracted from 3D editor. Moreover this data should take as little GPU memory space as possible.

The main disadvantage of such scheme that step 3 is difficult to transfer to other computer, to get final binary pack you should always rebuild conversion project using custom script. But it gives your much more possibilities to work with data using many existing C++ libraries, but not a poorly developed editor script languages.
> 4 votes

---
Tags: c++, 3d-meshes, binary
---


title: Good way to store entity data

text:
# Question
Title: Good way to store entity data
I'm building an RPG style game, but i have some trouble with storing data from entities. These entities can carry data including but not limited to their location, their graphics, whether they are solid, and so on.

I have thought about just storing it as a list of numbers, but this means that a single change (adding a variable for example) will break the entire saving system.

Is there an easier and more versatile way to store this information?

EDIT: Ok i did a bit of searching and i found a bunch of questions basically the same as this one. Feel free to ignore this question ;)

# Answer
Assign each entity an ID, then store each component (location, solid, etc) in a separate table indexed by the entity ID.

Or just use JSON.
> 1 votes

---
Tags: java, data-structure, savegame
---


title: Box2D and Slick2D: Graphics bug

text:
# Question
Title: Box2D and Slick2D: Graphics bug
**The bug**

The physics ground represented by a horizontal line. The object is stationary, and seems to be pretending that the ground is lower. This is because the center of the Shape is incorrectly located, or because I am transforming it improperly.

This is a cube displayed with the same system, and the center at the center of the object. It acts correctly, but that may just be because of its symmetric nature.

Shapes appear to rotate around points which are not at their center of mass when I view a simulation involving a convex polygon and a static plane. I wrote the draw code myself, as shown below. More specifically, see the render function, which draws all objects in the Box2D world. One possible location for the bug is in the code where I'm transforming the Graphics object, and the other is when I'm creating and transforming the Slick2D Shape I will be drawing.

What is causing my graphics glitch?

Below is the source of the program in question.

IMPORTANT NOTE: This code is fully compilable and self-contained.
If you have jBox2D and Slick2D, you'll be able to compile and run it.

Note that to use jBox2D, you'll have to add some slf4j packages (slf4j-api and slf4j-nop if you just want it quick).

```
package junk;

import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.collision.shapes.ShapeType;
import org.jbox2d.common.MathUtils;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.BodyDef;
import org.jbox2d.dynamics.BodyType;
import org.jbox2d.dynamics.Fixture;
import org.jbox2d.dynamics.World;
import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Polygon;
import org.newdawn.slick.geom.Transform;

public class Junk extends BasicGame
{
    World world;
    int velocityIterations;
    int positionIterations;
    float pixelsPerMeter;

    public Junk()
    {
        super("Hello World");
    }

    @Override
    public void init(GameContainer gc) throws SlickException
    {
        velocityIterations = 10;
        positionIterations = 10;
        pixelsPerMeter = 30.f;

        world = new World(new Vec2(0.f, -9.8f), true);

        {
            BodyDef dground = new BodyDef();
            dground.active = true;
            dground.position = new Vec2(0.f, 0.f);
            dground.type = BodyType.STATIC;
            Body bground = world.createBody(dground);
            PolygonShape sground = new PolygonShape();
            sground.setAsEdge(new Vec2(-30.f, 0.f), new Vec2(30.f, 0.f));
            bground.createFixture(sground, 1000.f);
        }
        {
            BodyDef dbox = new BodyDef();
            dbox.active = true;
            dbox.position = new Vec2(0.f, 10.f);
            dbox.angle = MathUtils.PI / 3.f;
            dbox.type = BodyType.DYNAMIC;
            Body bbox = world.createBody(dbox);
            PolygonShape sbox = new PolygonShape();
            Vec2[] data =
            {
                new Vec2(-0.3f, -0.7f),
                new Vec2(0.0f, -1.0f),
                new Vec2(0.3f, -0.7f),
                new Vec2(0.5f, 0.5f),
                new Vec2(-0.5f, 0.5f)
            };
            sbox.set(data, 4);
            //sbox.setAsBox(0.5f, 0.5f);
            bbox.createFixture(sbox, 1.f);
            bbox.setAngularVelocity(10.f);
        }
    }

    @Override
    public void update(GameContainer gc, int delta) throws SlickException
    {
        world.step((float)delta / 1000.f, velocityIterations, positionIterations);
    }

    @Override
    public void render(GameContainer gc, Graphics g) throws SlickException
    {
        Body current = world.getBodyList();
        Vec2 center = current.getLocalCenter();
        while(current != null)
        {
            Vec2 pos = current.getPosition();
            g.pushTransform();
            g.translate(pos.x * pixelsPerMeter + (0.5f * gc.getWidth()),
                       -pos.y * pixelsPerMeter + (0.5f * gc.getHeight()));
            Fixture f = current.getFixtureList();
            while(f != null)
            {
                ShapeType type = f.getType();
                switch(type)
                {
                    case POLYGON:
                    {
                        PolygonShape shape = (PolygonShape)f.getShape();
                        Vec2[] verts = shape.getVertices();
                        int count = shape.getVertexCount();
                        Polygon p = new Polygon();
                        for(int i = 0; i < count; i++)
                        {
                            p.addPoint(verts[i].x, verts[i].y);
                        }
                        p.setCenterX(center.x);
                        p.setCenterY(center.y);
                        p = (Polygon)p.transform(Transform.createRotateTransform(current.getAngle() + MathUtils.PI, center.x, center.y));
                        p = (Polygon)p.transform(Transform.createScaleTransform(pixelsPerMeter, pixelsPerMeter));
                        g.draw(p);
                        break;
                    }
                    case CIRCLE:
                    {
                        CircleShape shape = (CircleShape)f.getShape();
                    }
                    default:
                }

                f = f.getNext();
            }
            g.popTransform();
            current = current.getNext();
        }
    }

    public static void main(String[] args) throws SlickException
    {
        AppGameContainer app = new AppGameContainer(new Junk());

        app.setDisplayMode(800, 600, false);
        //app.setShowFPS(false);
        app.start();
    }
}

```

# Answer
First thing I would look at is how setting the center point of object affects the local coordinate space of your polygon vertices.

Box2d gives you the position of the geometry at its center of mass by default, and the verts will be offset from the center in local space. I would try commenting out the lines:

```
p.setCenterX(center.x);
p.setCenterY(center.y);

```

Also to determine if you have a translation or rotation problem, I would drop some polygons into the scene that will rotate when they land, if they roll along the ground correctly but slighly penetrating the surface, you have a translation problem.

If they rotate from a point outside the object itself, you have a rotation problem
> 2 votes

---
Tags: java, graphics-programming, slick, jbox2d
---


# Question
Title: Pygame's rotation methods have crippling issues, but is it me or Python's pygame?
http://www.youtube.com/watch?v=lNJFxvR6ex8&feature=youtu.be

On rotate and rotozoom, can't find fixes on these on the internet, anywhere. Basically, the video is showing 4 things in this order: 1. A ring image being rotated with .rotate. 2. A simple image being rotated with .rotate. 3. The ring rotated with .rotozoom. 4. The simple circle rotated with .rotozoom.

The difference: In 1 and 2, the images do not have that slight quiver/movement, but are reduced in quality. It might be difficult to tell with the video quality, but the ring image is slightly pixelated/blurred. In 3 and 4, the images are of equal/better than 1&2 quality when rotated with rotozoom, but they have this VERY SLIGHT but noticeable wobble about them. This is VERY noticable with test 3, where I put my mouse next to the circle outline, and you can see it move.

ANY and all help will be greatly appreciated, AND this will help many people for a long time, i'm sure.

Here are images of the differences in picture quality of rotate vs rotozoom:

http://s189.beta.photobucket.com/user/ECSit/library/PyGame%20and%20Python

# Answer
Rotations of anything other than 90 degree increments requires resampling which cannot be done both quickly and accurately in software, and always loses detail anyway. The same applies for scaling/zooming for anything other than integer increments.

The slight 'wobble' you sometimes see is presumably related to the fact that the image size and height must change during rotation and therefore the centre of the image falls between 2 pixels half of the time, and must be rounded to one or the other to be rendered.

Ideally, if you want real-time rotation and scaling with sub-pixel precision, you need to be using a system backed by OpenGL or DirectX. In Python, that usually means pyglet, but you can roll your own using pyopengl. This cannot completely prevent some degree of blurring or pixellation, because information is necessarily thrown away when you resample an image, but it will usually be better than if done in software and certainly faster.
> 1 votes

---
Tags: rotation, python, pygame, transformation
---


# Question
Title: How a "view" is handled in an Entity-Component based model?
Coming from an MVC background, I am trying to understand Entity-Component based model. However, i can see description about the use components( data objects ) and entities ( group of different data-objects ie components), but cannot see how view is created. I can see something called "render" components though. But how would i use it ? It seems, i don't need to bother about separation of view from data in this architecture. But i doubt, if this is the case, then things would mess up.

# Answer
Entity-Component systems are different from MVC systems. Specifically, an Entity-Component system is not a type of MVC system.

There are a broad range of component-based entity systems, each of them handling this a bit differently, but the way I decouple drawing from data is to use `System`s. A system is a class that takes data from components and works with them as a group. Some examples of systems would be a `CollisionDetectionSystem` or an `AnimationSystem` or, being the point of this question, a `GraphicsSystem`. The `GraphicsSystem` would be registered with each component, and they could pass in their data to the system.

This pattern lets you decouple most, if not all logic from components (including rendering). There are definitely other ways of doing it, but I've found this one to be the most straightforward.
> 4 votes

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


# Question
Title: How could I store different abilities in the player class?
So, I have a player class with basic actions. During the gameplay he unlocks new abilities. I don't know how to store new actions within the player class. To be precise - I know how, but my method is too messy and i want to clean up code. Also, I want to add to the enemies some of those abilities. In other words, every game entity(expect walls, perhaps :D) should have a collection to which i can add methods that extend entity functionality. How do i make this?

# Answer
> 0 votes
I've received a great reply on StackOverflow This problem can be solved with dictionary and lambda functions

```
public Dictionary<string,Action> Powers = new Dictionary<string,Action>();

```

And add new powers to this dictionary:

```
Powers["Double Jump"] = () => { //jump code };

```

Then just call whenever you want `Powers["Double Jump"]();`

# Answer
> 1 votes
I recommend you approach used in the Artemis Entity System Framework. You can think about your player, enemy, wall etc. like about container (entity) for components. Then you precise actions (systems) for entities with particular set of components.
For example you can create system that allows player to fly when the X key is pressed (in-game condition) and when entity represented player has component **flying** (in-engine condition). Assume that player has ability for fly only if he has some wings in inventory. If this happen just add component **flying** to player entity and this will unlock flying for player.

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


# Question
Title: Playing a sound only once during collisions
So recently i thought i figured out a solution for it, only to find out it doesnt work when i have more than one of the same object type added to the level.

What i was doing is iterating through my different list of objects and checking if any of them are colliding with the player, if they are i play the sound for that one colliding with the player and then i set the boolean for the sound to true, meaning the sound has been played now.

When their are no collisions going on or if the current object being iterated isnt colliding with the player i set the sound boolean back to false. So as you probably can see, there is a issue when there is more than one of the same objects added because one of them will set the boolean to false and the sound will be played over and over as long as the player is colliding with one of the objects.

So i have run out of solutions to fix this so i am seeking out help.

Thanks anyone who can offer assistance.

EDIT:

Here is an example of how i am doing it now:

```
private void checkNeutalSwitchers() {

Iterator<Tile> switcherIT = this.neutralSwitcherTiles.iterator();

while (switcherIT.hasNext()) {
    Sprite square_sprite = switcherIT.next();
    float distance = MathUtils.distance(playerBoat.getX(),
            playerBoat.getY(), square_sprite.getX(), square_sprite.getY());
    if (distance < 11) {
        if (square_sprite.collidesWith(player)) {
            if (square_sprite.getUserData().equals("triangle")) {
                playerBoat.detachChild(player);
                player = swithcer.getTriangle();
                playerBoat.attachChild(player);
                if (this.neutralSwitcherBool == false) {
                    this.neutralSwitcherBool = true;
                    this.switchShapesSound.play();
                }

            }
            if (square_sprite.getUserData().equals("square")) {
                playerBoat.detachChild(player);
                player = swithcer.getSquare();
                playerBoat.attachChild(player);
                if (this.neutralSwitcherBool == false) {
                    this.neutralSwitcherBool = true;
                     this.switchShapesSound.play();
                }

            }
            if (square_sprite.getUserData().equals("circle")) {
                playerBoat.detachChild(player);
                player = swithcer.getCircle();
                playerBoat.attachChild(player);
                if (this.neutralSwitcherBool == false) {
                    this.neutralSwitcherBool = true;
                    this.switchShapesSound.play();
                }

            }
            if (square_sprite.getUserData().equals("rectangle")) {
                playerBoat.detachChild(player);
                player = swithcer.getRect();
                playerBoat.attachChild(player);
                if (this.neutralSwitcherBool == false) {
                    this.neutralSwitcherBool = true;
                    this.switchShapesSound.play();
                }

            }
        } else {
            this.neutralSwitcherBool = false;
        }
    }
}

```

}

# Answer
Maintain a list of active contacts. Then you can check or have events for "collision started," "collision ended," and "collision maintained." Fire the sound only when a collision is started.

You can maintain contacts easily using a hash table. Sort the object ids/ pointers. So the lesser is first, and add the pair to the table. You can store extra information if it helps at all. Just use the sorted objects pair as a key.
> 1 votes

---
Tags: android, andengine
---


# Question
Title: Implementing an automatic navigation mesh generation for 2d top down map?
I am currently in the middle of implementing an A\* pathfinding for enemies. In order to implement the actual A\* logic, I need a navigation mesh for my map.

I am working on a 2D top down rpg map. The world is static, meaning there is no requirement for dynamic runtime mesh generation. My world objects are freely placed (not snapped to grid), rotated and scaled, which means that using a grid based A\* is going to be a little complicated.

For example, how would I know a grid tile contains a collidable object? Lets say that object is actually located on the tile next to this, but is rotated and scaled such that it is still blocking the way?

I could check for the middle pixel of the grid tile to see if it contains any of the nearby objects color data, but it still wouldn't be all that accurate and occasionally enemies could get stuck in between objects.

# Answer
> 1 votes
From what I understand of your question, you are trying to figure out how to make a navmesh out of a tile-/grid-based terrain.

Well in fact, tiles/grids are inherently easier to work with, and one way or another you are going to have to apply A\*, but you can apply it just as easily to a grid as you can to a navmesh. The point being that A\*, like any *graph search algorithm*, operates on graphs. A navmesh is a graph, and so is a tile grid (although more densely and regularly connected).

I'd suggest that you simply focus on doing pathfinding in a grid, unless you believe there is some substantial gain to be had by using a navmesh (I don't).

And if you do, then a possible way is to generate a navmesh *first*, then rasterise its polygons by filling them in with tiles of different types (you'd use point-in-polygon checks for this). Now you'd have a tile based world, but you'd also have a nice navmesh already present and in agreement with the tiles. It's harder to do this the other way around, IMO (produce navmesh from tiles, which I think you are suggesting). Caveat: The problem here is, well, creating a planar navmesh graph. Not really that easy, I'm afraid, unless you have some ideas of your own. The graph planarity problem is one of the hardest problems in computer science. Hence: Use a grid.

**EDIT** I am guessing (I have to guess a lot here!) that the reason you might prefer a navmesh over a grid is because you want creatures / objects to be placed or to roam "pixel-freely" rather than snapping to grid cells. Well I would still recommend sticking with the grid, but maybe flood-filling certain areas with a code to say, "this is zone 1", "this is zone 2" etc. That way you can limit your entities to ranging about in a given zone. To remove the aliasing effect of a grid, you can also introduce minor variations to the centre point of each tile, so that it looks less regular when you entities move. Just a thought.

# Answer
> 1 votes
If you want to precalculate the paths (and it fits in memory), you might want to check out some kind of **all pairs shortest paths** algorithm, like the Johnsons algorithm and stock away all paths in a container where the key is the start and end positions.

Reading the edit Nick Wiggill posted, this won't help you make 'pixel perfect' paths though.

If you want to do a true 2D-Navmesh (and not precalculate the rotation etc and set those overlapped grids to pass or block, which I would suggest) you need to:

Rotate, Scale and Transform your blocking rectangles/meshes, to new 'meshes' and then use Boolean unions on all the overlapping ones and there you are, a nav mesh in 2D.

# Answer
> 1 votes
The key premise to maintain is that navigable regions should not contain collidable objects. In a tile based representation, this means that if a tile contains any collidable object, that tile is impassable to all game entities. Collide against this navigation map, rather than the objects that were inserted into the map, and you avoid your problem.

You will encounter efficiency problems, as tiles may end up being marked as impassable when only a small part of the tile is obscured by a collidable object. Decreasing the size of your tiles will improve this, at the cost of more tiles, and with that higher memory usage and search times.

Depending on the size of your world, distribution of obstacle sizes and rotations, this may make a purely tile based solution impractical, but remember, you can always adjust your world design to fit your technical constraints.

---
Tags: ai, navmesh
---


title: Slide effect in voxel collisions

text:
# Question
Title: Slide effect in voxel collisions
I'm making a voxel engine, and I'm trying to figure out the right way to make efficient collisions with a slide response (making the player slide against the wall).

Currently my collisions are pretty simple : if, after update, the player bounding box collides with the voxel world, then we just cancel the collision.

I have seen this answer on SO, but I don't understand what the answerer means here. Since a voxel is a single unit, how can I compute its normal ? Should I map the 3x3x3 block surrounding the voxel to a precomputed normal ?

> * Take the unit surface normal of the colliding voxel (pointing outward).

# Answer
> 1 votes
You're drawing faces for the the terrain right? Just like you're computing faces for a voxel, you can compute the normal. The normal pointing outward of the voxel is the same normal pointing outward for the face you're drawing. If you have access to the vertices, you can compute the normal formed by the surface triangle you collided with.

Or more simply the normal is just the voxel pointing to the next voxel that's empty. For example:

The red lines point from the solid voxels towards the empty voxels. The black lines represent the faces being drawn. The red lines are the surface normals for the solid voxels.

---
Tags: collision-resolution
---


title: Parallax With Box2d iphone

text:
# Question
Title: Parallax With Box2d iphone
I am creating the simple game. In that game car will move and obstacles will come in the car way we will have to save that car from that obstacles. What I have done. I have created the car with the box2d body and I have added the parallax background now it seems that car is moving. The problem I am facing is that how will I add the obstacles box2d object randomly in the way of car ? How will I add the random box2d objects in the parallax background?

Thanks,

# Answer
No one is going to write your code for you,

there are plenty of tutorials out there for cocos2d and box2d so i suggest you read them. Are you using tileD? Or are you just using a picture as a background?

if you use TileD you can add an objects layer with object nodes on it and tell your obstacles to spawn on the object nodes in tiled... Then just update the obstacles position to that of the object nodes..

Or if you are using just an image you can spawn the obstacles outside of the screen and then just move them along the same way that your background is moving... If you took away the background you would just see a car staying still with obstacles flying at it... But add a moving background and it looks like the obstacles are apart of the background.

Good luck
> 0 votes

---
Tags: iphone, box2d, cocos2d
---


title: AI surrounding algorithm suggestions

text:
# Question
Title: AI surrounding algorithm suggestions
I am building up a simulation where predator groups (tribes) try to hunt other agents in the simulation (whom also are clustered in groups).

Now I got to a point where members of a group follow their leader and wait for any sort of commands (currently passed as strings and vector that they need to move towards). Anyway the idea is to implement some interesting surrounding behaviour just like predators hunt in group they surround their prey.I shall attach a picture for better explanation:

The green circles are the agents that predators are hunting. The red circle is the leader of the predator group and the black dots are other predators. The sort of behaviours I am looking for should be similar to shown in the picture where on the right side of the picture the predators are surround the pack of green agents as instructed so by the leader of the predator pack.

What I was thinking initially was find the leftmost agent in the green pack and the right most in green agents pack and make members of the predator group move towards them.However at this point I shall mention that predators have a fixed field of view so it may not see all of the pack at first.

So I am wondering if anybody came across something like so or have any good ideas how to go about producing this sort of behaviour.

# Answer
> 2 votes
One possible method could be a draw an ellipse around the target pack and calculate the circumference.

divide the circumference by number in pack to evenly distribute.

create paths for units to move to their points.

---
Tags: java, ai, movement
---


# Question
Title: Error when trying to use VBO "array vertex_buffer_object must be disabled to call this method"
**EDIT**

*I have effectivley re-wrote this question in order to greatly imrpove its quality - see revision logs if you must*

I have narrowed down my problem to the initialisation phase of my program, when I am trying to create my vertex buffer. The code that I am currently using is...

```
vaoID = new int[1];
gl.glGenVertexArrays(1, vaoID, 0);
gl.glBindVertexArray(vaoID[0]);
vboID = new int[1];
gl.glGenBuffers(1, vboID, 0);
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, vboID[0]);
FloatBuffer vData = FloatBuffer.allocate(vertexData.length);
vData.put(vertexData);
vData.rewind();
gl.glBufferData(GL4.GL_ARRAY_BUFFER, vData.capacity() * (Float.SIZE / 8), vData, GL4.GL_STATIC_DRAW);
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); // With out this line my code throws the exception
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(0, 4, GL.GL_FLOAT, false, 0, null); // This is the line where the exception is thrown
gl.glBindVertexArray(0);

```

So yes, at present my code is able to run with out crashing, but it must have a mistake some where as I am not able to get this to render. For the buffering the index data, I use this code, which does complete successfully when it runs

```
gl.glGenBuffers(1, bufferIDs, 0);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, bufferIDs[0]);
ShortBuffer iData = ShortBuffer.allocate(indexData.length);
iData.put(indexData);
iData.rewind();
indexCount = iData.capacity();
gl.glBufferData(GL4.GL_ELEMENT_ARRAY_BUFFER, indexCount * (Short.SIZE / 8), iData, GL4.GL_STATIC_DRAW);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0);

```

Then when it comes to drawing, I perform the following steps, and I don't think this really matters, as I am sure I am still not buffer correctly in the first place

```
// first I bind my VAO
gl.glBindVertexArray(vaoID[0]);
// then bind, draw, unbind the index buffer
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, bufferIDs[0]);
gl.glDrawElements(GL4.GL_POINT, indexCount, GL4.GL_UNSIGNED_SHORT, 0);
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, 0);
// finally I unbind the VAO
gl.glBindVertexArray(0);

```

I am fairly sure that this is the correct process for rendering buffered geometry. I have confirmed that my shader code is correct and valid by use of some immediate drawing commands, so I do I have full pipeline, it just seems I am not feeding data into it. As a point of interest, I also tried editing my vertex shader to set all points to (0,0,0,1) so that if any points where being passed in, I should see them, but this did not work, which I took to mean that I am not passing data into my shader in the first place.

Thanks for all the help so far.

# Answer
> 2 votes
Your first problem is here:

```
gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0); // With out this line my code throws the exception

```

That's unbinding your buffer object before the `glVertexAttribPointer` call. You *need* to have a buffer bound in order for that to be a reasonable call. It's the combination of having a buffer bound to `GL_ARRAY_BUFFER` and calling `glVertexAttribPointer` that sets up an association between a buffer object and a vertex attribute.

Once you've called `glVertexAttribPointer`, *then* you can unbind the buffer. But not until then.

Your other problem is this your element buffer setup code.

```
gl.glBindBuffer(GL4.GL_ELEMENT_ARRAY_BUFFER, bufferIDs[0]);

```

`GL_ELEMENT_ARRAY_BUFFER` is part of the VAO's state (unlike `GL_ARRAY_BUFFER`). So you need to do it while your VAO is still bound to the context, not after.

# Answer
> 1 votes
Are you using a vertex buffer somewhere else in the code? Or using a third-party library that does?

I would try calling `gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);` at each frame, just before `gl.glEnableVertexAttribArray(0);`.

# Answer
> -2 votes
I am facing the same problem with VBO myself, so cannot help you much with it but I have one basic suggestion

```
    gl.glBindBuffer(GL4.GL_ARRAY_BUFFER, 0);
    // With out this line my code throws the exception

```

The above line is de-allocating your buffer so you are right. No data is being copied to the vbo. The drawing process needs to be bracketed within the calls

```
    gl.glEnableCLientState(GL2.GL_VERTEX_ARRAY);
    //TODO Drawing Commands
    gl.glDisableClientState(GL2.GL_VERTEX_ARRAY);

```

If someone can shade some more light on this issue it will be very helpful as it is very difficult for java users to get clear answers on VBO issues.

---
Tags: opengl, java, jogl, vbo
---


title: Transfering a game from Python to C

text:
# Question
Title: Transfering a game from Python to C
I have a simple game RiceRocks which I want to translate into C programming language not C++,because I know C better. I know only basic C++ such as : loops,control statements, arrays. Where to start? What library should I use?

# Answer
> 2 votes
If you have some knowledge of C and Python, the code shouldn't be hard to port. The only thing missing from the standard C which you need to write the game, is a graphics library. As you can see, the Python implementation uses something called `simplegui` which creates the window, loads images and then draws them. You can do this fairly easy in C using the SDL library. Here's a set of tutorials to help you get started: http://www.lazyfoo.net/SDL\_tutorials/

Oh, and you need to transform the classes into structures. Just place all the members of the class in a C struct, and implement each method as a function that gets a pointer to the struct ( just as the python methods get a reference to `self` as their first parameter ).

# Answer
> -4 votes
First off, saying "I know C better" is wrong because that doesn't sound right, and C is technically not better because it's missing a lot from C++ and it's not OOP which means classes and objects don't exist in it. Second off if I were you I would learn C or C++ until your great at it and then look into game libraries such as GLFW or GLUT or a C++ game engine like Irrlicht.

---
Tags: python, c
---


title: Repeat texture in a scrolling game

text:
# Question
Title: Repeat texture in a scrolling game
The bottom region of the screen is filled by a repeated texture:

```
grassTexture = new Texture(Gdx.files.internal("images/grass.png"));
grassTexture.setWrap(TextureWrap.Repeat, TextureWrap.Repeat);
grassSprite = new Sprite(grassTexture, 0, 0, width,grassTexture.getHeight());

```

However, The grass should also be scrolled to the left (looping texture from edge to edge). I have got this in the render() method:

```
scrollTimer += 0.0007f;
if (scrollTimer > 1.0f)
        scrollTimer = 0.0f;
grassSprite.setU(scrollTimer);
grassSprite.setU2(scrollTimer+1);
grassSprite.draw(spriteBatch);

```

The scrolling part now works. However, the grass texture is not repeated anymore. It looks like this:

# Answer
> 4 votes
I don't know libgdx enough, but I can hint you at a general approach I'd use:

* Draw the texture using a quad with a wide of `screenWidth + textureWidth` (instead of `textureWidth` you could use `tileableWidth` in case the texture itself repeats the tile already).
* Draw the quad at position `x` where `x` is animated using this formula: `x = (x + dx) % textureWidth` (again `textureWidth` could be `tileableWidth`; `dx` is the change per iteration, which could be fixed or time based depending on your implementation).

This will cause your texture to loop indefinitely, without requiring shaders, changing texture coordinates, etc. and without wasting unnecessary drawing time (only minimal overhead when trying to draw parts outside the screen).

---

Edit: With the attached pictures, I'd imagine the issue is this line:

```
grassSprite.setU2(scrollTimer+1);

```

By setting your right border to `scrollTimer+1` you essentially tell the engine to repeat the texture exactly 1 time. This is wrong and the culprit here. The solution depends on the number of repetitions you need to fill the available space. For example, the following line should do the trick in case you have to repeat the texture 5 times to fill the given space:

```
grassSprite.setU2(scrollTimer+5);

```

---

Edit 2: Just noticed another mistake in your code that might make the textures "jump":

```
if (scrollTimer > 1.0f)
    scrollTimer = 0.0f;

```

This part should rather be something like this:

```
if (scrollTimer > 1.0f)
    scrollTimer -= 1.0f;

```

---
Tags: textures, libgdx, spritebatch
---


# Question
Title: What is a reliable and easy way to build an AI?
> **Possible Duplicate:**
> New to creating AI - where to start?

I'm making a "Mario Like" game and I was wondering how would an AI generally work? I'm thinking of that it could just go to the player and fire whenever the player is x amount away from it but this is just confusing me. I'm not asking for anyone to write an AI, I'm asking about where to get started on building one or any experience you have with building an AI.

# Answer
Savlon already linked a great answer with several links in the comments.

However, for a simple Mario-like (hey!) platformer, I wouldn't worry too much about the AI.

In fact, you don't really need any real AI to create a nice and solid platformer (don't overcomplicate it!):

* To avoid NPCs somehow dieing or wasting their "time" (or the system's processing power) before the player is there, only spawn them with the player being nearby. This way they don't have to determine whether the player is nearby, what they should do, etc.
* Most classic enemy behavior can be realized using some very simple rules:
    + Let the enemy walk to the left. If he collides with something, he'll turn to the right.
    + If the enemy shouldn't fall off platforms (red turtle in classic Mario games), then check whether there is something walkable in front of them. If there isn't, change direction.
    + If the enemy should idle (piranha plants), just check how distant the player is. Don't leave the tube as long as he's closer than x units.
    + To decide which direction to shoot (hammer bros), just determine which the direction the player is.
    + Boss behavior can be controlled using similar logic combined with (pseudo) random numbers. Keep in mind that a big part of the gameplay for most platformers is the fact you'll have to find and remember patterns (e.g. when a boss jumps or when he shoots) to beat the game and not get hit. If you add AI, this won't necessarily become more challenging or interesting. It's more likely it gets too predictable or players will just aim for some loophole to get the AI into bugging out (not necessarily; but I consider this a great example why you won't need a full AI).
* Classic consoles didn't have the processing power for real time AI decisions, as such this is really uncommon in this genre anyway. I'd say go with fixed/coded behaviors first and concentrate on gameplay. Later on, if you feel like it, you can extend this even more and in the end you'll essentially get an AI like behavior without writing explicit code for it.

---

Might be interesting to note:

The only AI involvement in a classic Mario-like platformer I know of is the approach to write a "jump and run solver" AI to essentially speed-run such a game (e.g. for *Infinite Mario*; more information can be found on MarioAi.org). So you're "programming" the player, not the enemies. Keep in mind that I'm not talking about something like the "guide mode" Nintendo introduced with the latest installments of the series. These are - as far as I know - just fixed instructions/scripts solving the levels in a very specific way (path, timing, etc.). Fun fact: With a real enemy AI using random decisions etc. something like that would be a lot more complicated to do (if possible at all, given limited resources and the player not wanting to wait).
> 11 votes

---
Tags: xna, game-design, ai, game-mechanics
---


# Question
Title: Best way to store NPCs, Monsters, Shops, etc for JavaScript game?
OK, let's say I have a JavaScript game (preferably on jQuery framework) and its using HTML5 Canvas.

What would be your way of storing data to map out shops, monsters, and NPCs? I was thinking maybe JSON txt files on the website? Or maybe simple text files and simple delimiters? I am not sure. How would you store that kind of data?

# Answer
JSON is definitely the way to go, it's nice and lightweight. Though, storing the data in a database is probably more secure than static files on the server - it prevents people from accessing the files directly. JQuery makes it insanely easy to execute ajax queries, you'll just need a simple PHP (or maybe ASP, depending on your host) script for the ajax to call, to handshake info between javascript and the database. Some quick hunting on google reveals a ton of tutorials and demo classes, so even if you don't have any server-side scripting knowledge, it shouldn't be an obstacle. Best of luck!
> 4 votes

# Answer
JSON would be fine, so would anything else. You can use XMLHttpRequest to load it, or some other technique as you see fit.

JQuery really doesn't buy you anything, it's almost exclusively for manipulating the DOM, if you use Canvas, you don't need it (You still need a DOM, but it probably very rarely changes).
> 2 votes

---
Tags: javascript
---


# Question
Title: How to do perspective projection “parallax” but without changing the scale or offset of objects?
Hello everyone I have this problem that I have tried everything I could think of. The problem: I am making a 2D game with parallax effect but I am using 3d space so am not simulating the parallax but letting the perspective projection take care of it for me. now the problem i have my own game editor where I design the levels, in this editor I use just images and I set a Z value for each layer. however I want the layers to show in the game engine exactly as I set them in the game editor, in short I want perspective projection to do parallax but without changing their scale or offset/position.

obvious solution is to scale them up and offset them but the problem how to calculate their offset? with scaling I tried object-\>Scale(object.Z/view.Z) and seems to return them to their real size but their positions are still wrong. I tried object-\>setPositionX(object-\>getPosition().x\*(object.Z/view.Z)) and seems to be aligned except they all seems shifted.

I have tried unprojecting and tried to convert from world matrix to screen matrix and find some ratios and so on.

If anyone have any idea or anyway how this could be done in an elegant/mathematical way , I will be most grateful.

Thank you all in advance.

# Answer
The easiest way to do that is to use an orthogonal projection when rendering, but do your own perspective divide on the origin of the objects.

If you want to use a perspective project when rendering, you'll need to reverse the effects of the assumed original perspective projection used when editing, and apply the new perspective projection for the current camera when playing.

In your editor, you have a camera. This camera transforms from the object coordinates into screen coordinates. Now, in your editor, this is an orthogonal camera, but you want to pretend that it actually was a perspective camera. If you take the screen coordinates, run them backwards through the camera transform for the perspective camera, you get new object coordinates out. This transform is a transform that you want to apply to your objects.

What happens when you render:

```
screen_position = screen_from_world_matrix * world_position

```

What you want to happen in your transform pipeline, is add another few steps, to transform between these various spaces: playscreen, playworld, editscreen, and editworld. editscreen has the same coordinates as the original orthogonal editor camera, and the pretend perspective editor camera, as that's the space where we'll be doing the "trick" of pretending that a different camera is being swapped out.

```
playscreen_position =
    playscreen_from_playworld_matrix *
    playworld_position

playworld_position =
    playworld_from_editscreen_matrix *
    editscreen_from_editworld_matrix *
    editworld_position

```

playworld\_from\_editscreen\_matrix is the inverse of editscreen\_from\_playworld\_matrix, which happens to be the screen\_from\_world\_matrix of the pretend camera!

The good news is that all of these matrixes can be concatenated into one:

```
playscreen_from_editworld_matrix =
    playscreen_from_playworld_matrix *
    playworld_from_editscreen_matrix *
    editscreen_from_editworld_matrix

```

Or if you just want to apply the editworld-to-playworld transform:

```
playworld_from_editworld_matrix =
    playworld_from_editscreen_matrix *
    editscreen_from_editworld_matrix

```

Then transform your objects using that matrix!
> 3 votes

---
Tags: opengl, 2d, mathematics, projection, perspective
---


# Question
Title: Simple Motor Vehicle Acceleration Function
So I have a simple 1D "racing" game, with a single button the player can press to max the gas pedal *and there is also some other stuff going on*.

I think acceleration should be highest somewhere at medium velocity (or medium RPM for each gear), and taper off towards maximum velocity, no? What is a good set of functions to model this?

Do I need to model RPM too? I'm not sure whether to model different gears too, but I thought they'd each follow more or less the same function.

# Answer
> 1 votes
I can't imagine a single dimension racing game could be very interesting. Anyway, I don't know anything about cars but you can make it as complicated as you'd like.

Basically you need a function that reaches a peak since cars will not indefinitely accelerate.

Some examples would be

sin(x), x = 0 to pi

ax^2 + bx = 0 for a \< 0 and b \> 0

x * e^(-(x - n)), x = 0 to n

Bessel Function of the first kind for n = 1 and x = 0 to ~3.85

You can be as complicated as you'd like with the function. Then to find the velocity and position at any given point take the anti-derivative with respect to time, once to find the velocity, and again to find the position. You don't necessarily need to do that last part you can model it anyway you like through trial and error which will likely need to happen anyway. If you'd like to go this route I'd suggest picking an easy function like the quadratic equation, the second example, as it's easy to work with and you'll find enough information on the interwebs to get a generic answer for both without having to do the calculus if you've not taken an introductory course in it.

**Edit:** I've thought about this a bit more and I think the easiest thing to do would be to use some type of piecewise function. This will give you a bit more control as to what's going on.

For example, x\*e^(x), x \<= max acceleration then when x = max acceleration x, x = max to 0.

Since this will update rather frequently, however you have that set up, then the result can just be added constantly to a velocity variable and the position updated accordingly. No need for calculus. And again this will give you a lot more control as you can more easily decide how quickly to accelerate and how quickly it will stop accelerating.

---
Tags: physics, racing
---


# Question
Title: What are the differences between a skybox and a skydome?
What are the differences/pros/cons between a skybox and a skydome?

# Answer
> 23 votes
If the textures are done correctly, ideally the two are indistinguishable.

Other than the obvious difference of one being a half sphere (sky dome):

And the other being a cube (sky box), the two only have a few differences.

The most flexible of the two is the sky dome. With the increased number of vertices, sky domes allow some more options. For example, coloring the vertices for different effects.

The easiest to implement of the two is the sky box. It's just a simple box, and very fast to draw with far fewer vertices.

Skybox

* Easy to implement
* Easy to code texture coordinates by hand
* Fast to draw
* Can have issues with perspective and corners
* Can be difficult to create textures that look smooth

Skydome

* Easier to create textures for (but much more difficult to apply)
* Slower to draw with far more vertices
* More flexible because of increased vertices
* Less likely to have perspective issues and there are no corners to worry about

# Answer
> 20 votes
A skybox is a cube that has the image of the sky projected onto its six faces so that it looks like a sky if the camera is placed in the exact center. I.e. each face of the triangle has 90 degrees of the view.

A skydome is a dome shaped bit of geometry that's rendered to look like a sky.

A skybox is more limited in terms of animation and has a fixed resolution.

A skydome, being constructed from real geometry, can have more detail where it needs (say the moon, or a city skyline) and less texture detail where it's not needed (like the plain sky background). A skydome can also be composed and animated from separate parts, to animate things like clouds and the motion of celestial bodies.

Using geometry for the sky also means you can get parallax effects. Say you've got your sky box modeled at 1/10th scale, just move the camera 1/10th of its translation when rendering the sky geometry. This way you can mix world geometry and sky geometry at vastly different scales without running into depth buffer precision issues.

In general, the term "skybox" has been used to mean anything that's used to render the sky separately from the world geometry. But traditionally, a skybox is a textured cube rendered at the origin to provide the illusion of a sky.

---
Tags: sky, skybox
---


title: How to implement rectangle selection?

text:
# Question
Title: How to implement rectangle selection?
I don't know if there is another term for it, but I mean this: You hold down a mouse button. A rectangle forms when you move the mouse around. The units inside the box get selected when you let go of the mouse button. I need this for a RTS style game I'm working on, but I don't know how to approach it.

I currently have functionality for selecting a unit, basically if you click within a certain area the unit is added to the list of selected units,

```
def mouseUp(self, button, pos):
    adjusted = self.coord_convert(pos)
    if button==1:
        for a in self.agent_list:
            if a.pos.get_distance(self.coord_convert_adjusted(pos)) < 16:
                self.selected.append(a)
            elif a in self.selected and a.pos.get_distance(self.coord_convert_adjusted(pos)) > 16:
                self.selected.remove(a)

```

The next step would be to allow for selecting multiple units at once by checking if they are inside a box, can you provide some guidance on how I should proceed?

Edit: To clarify, I'm asking how to create a box which starts at the position of MOUSEDOWN, and changes in size relative to mouse movement while holding the pressed button down, until let go.

# Answer
> 2 votes
For a rectangular selection, it would be a lot like your existing code.

```
def mouseDown(self, button, pos):
    self.selection_rectangle_start = self.coord_convert(pos)

def mouseMotion(self, pos):
    self.selection_rectangle_end = self.coord_convert(pos)
    self.selection_rectangle = calc_rect(self.selection_rectangle_start, self.selection_rectangle_end)
    for a in self.agent_list:
        if a not in self.selected and a.intersects(selection_rectangle):
            self.selected.append(a)
        if a in self.selected and not a.intersects(selection_rectangle):
            self.selected.remove(a)

```

`intersects` is just a simple overlapping rectangle check. Pygame provides `Rect.colliderect` for such purposes (http://www.pygame.org/docs/ref/rect.html#Rect.colliderect). `calc_rect` would check both the points to find the top/left/width/height and construct a valid rectangle from them.

# Answer
> 1 votes
I have to admit i am unfamiliar with python, but i think following steps seem appropriate:

1. Once the mouse is pressed down store the position it is currently at.
2. Start checking for a change in the mouse's position whenever the mouse is moved, or every X milliseconds.
3. If the mouse position has changed before the mouse is released then store the new mouse position in another variable.
4. Draw a rectangle from one position to the other.
5. When the mouse is released check each of your units x and y values to see if they are between the 2 positions.
6. Select each unit.

Hope this helps.

---
Tags: python, pygame, selection
---


# Question
Title: Per Instance Textures, and Vertex And Pixel Shaders?
How do you implement per instance textures, vertex shaders, and pixel shaders?

Given:
1. Two different model templates in Vertex Buffer, Square & Triangle 2. Instance Buffer with \[n\] instances of type Square or Triangle.

How do I add a Texture, VertexShader or PixelShader ID to the buffer data so that HLSL or the InputAssembly can determine which Shader to use at draw time?

A. How do I "Set" multiple Pixel and Vertex Shaders into the DeviceContext, and how do I tell DirectX to "switch" the Vertex Shader that is loaded at render time?

B. How many Shaders of each type, (Vertex, Pixel, Hull, etc), can I associate with model templates in the default Vertex Buffer?

C. Can I use some sort of Shader Selector in HLSL?

Related C++ Code

When I create an input layout, can I do this without specifying an actual Vertex Shader, or somehow specify more than one?

```
NS::ThrowIfFailed(
result = NS::DeviceManager::Device->CreateInputLayout(
NS::ModelRenderer::InitialElementDescription,
2,
vertexShaderFile->Data,
vertexShaderFile->Length,
& NS::ModelRenderer::StaticInputLayout
)
);

```

When I set the VertexShader and PixelShader, how do I associate them with a particular model in my VertexBuffer? Is it possible to set more than one of each?

```
DeviceManager::DeviceContext->IASetInputLayout(ModelRenderer::StaticInputLayout.Get());

DeviceManager::DeviceContext->VSSetShader(ModelRenderer::StaticVertexShader.Get(), nullptr, 0);
DeviceManager::DeviceContext->PSSetShader(ModelRenderer::StaticPixelShader.Get(), nullptr, 0);

```

# Answer
You can't draw with multiple vertex or pixel shaders at the same time. GPUs don't work that way. To render objects with different shaders, you sequentially set one shader, draw the objects for it, set another shader, draw its objects, etc.

```
for each (vertex, pixel) shader pair:
    set vertex shader in the device context
    set pixel shader in the device context
    set textures
    set constant buffers
    draw geometry for objects that use these shaders

```

That being said, it's possible to fold multiple shaders into one by using branches. For example, you could have a flag in your vertex format that says whether to use vertex shader A or B, where the code for A and B are actually both in one vertex shader and it uses an if-statement to decide which one to run. This may or may not be faster than having separate shaders and separate draw calls, depending on circumstances. Similarly, one can fold multiple textures into one by using a texture atlas or a texture array.
> 4 votes

---
Tags: directx, hlsl, directx11, fragment-shader, vertex-arrays
---