# Question
Title: How can I render the whole faces instead of only the vertices?
I'm doing my master thesis in comparing DX9 LoD with DX11 Tesselation LoD. Therefore I use a ShaderManager that calls either the shader for the DX9 implementation, where the model is exchanged by the appropriate model depending on the camera distance or the Tessellation Shader, which calculates the subdivision of the triangles depending to the camera distance.

The shader uses the regular vertex and pixel shader. The tessellation shader uses Vertex-, Hull-, Domain- and Pixelshader.

Since I implemented the tessellation shader in my project, the regular shader draws only vertices and not the wireframe or the faces. It renders the correct color of the vertices but no faces.

Regular Shader with only Vertices

This is what I had before:

How shader looked before tessellation modifications

* I tried to change the fillmode
* I reduced the shader code to a minimum
* I built the shadercode on the 4 stages instead just of the 2 stages
* I went back in revisions, to find some differences

but unluckily nothing helped.

Has someone had similar problems?

here is the vertex shader:

```
// Globals
cbuffer MatrixBuffer
{
    matrix worldMatrix;
    matrix viewMatrix;
    matrix projectionMatrix;
};

// Typedefs
struct VertexInputType
{
    float4 position : POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

// Vertex Shader
PixelInputType LightVertexShader(VertexInputType input)
{
    PixelInputType output;

    // Change the position vector to be 4 units for proper matrix calculations.
    input.position.w = 1.0f;

    // Calculate the position of the vertex against the world, view, and projection matrices.
    output.position = mul(input.position, worldMatrix);
    output.position = mul(output.position, viewMatrix);
    output.position = mul(output.position, projectionMatrix);

    // Store the texture coordinates for the pixel shader.
    output.tex = input.tex;

    // The normal vector for the vertex is calculated in world space and then normalized before being sent as input into the pixel shader.
    // Calculate the normal vector against the world matrix only.
    output.normal = mul(input.normal, (float3x3)worldMatrix);

    // Normalize the normal vector.
    output.normal = normalize(output.normal);

    return output;
}

```

and the pixel shader

```
// Globals
Texture2D shaderTextures[3]; // texture resource
SamplerState SampleType; // how pixels are written to the polygon face when shaded.

// LightBuffer holds the diffuse color and the direction of the light.
cbuffer LightBuffer
{
    float4 ambientColor;
    float4 diffuseColor;
    float3 lightDirection;
    float padding;
};

// Typdefs
struct PixelInputType
{
    float4 position : SV_POSITION;
    float2 tex : TEXCOORD0;
    float3 normal : NORMAL;
};

// Pixel Shader
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor1;
    float4 textureColor2;
    float4 alphaValue;
    float4 blendColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;

     // Get the pixel color from the first texture.
    textureColor1 = shaderTextures[0].Sample(SampleType, input.tex);

    // Get the pixel color from the second texture.
    textureColor2 = shaderTextures[1].Sample(SampleType, input.tex);

    // Get the alpha value from the alpha map texture.
    alphaValue = shaderTextures[2].Sample(SampleType, input.tex);

    // Combine the two textures based on the alpha value.
    blendColor = (alphaValue * textureColor1) + ((1.0 - alphaValue) * textureColor2);

    // Saturate the final color value.
    blendColor = saturate(blendColor);

    // **** Light **** //
    // Set the default output color to the ambient light value for all pixels.
    color = ambientColor;

    // Lighting equation: light intensity value is calculated as the dot product between the normal vector of triangle and the light direction vector.
    // Invert the light direction for calculations.
    lightDir = -lightDirection;

    // Calculate the amount of light on this pixel.
    lightIntensity = saturate(dot(input.normal, lightDir));

    // Check if N dot L is greater then 0. If diffuse Color is neg. it will substract away some of the ambient color.
    if(lightIntensity > 0.0f)
    {
        // diffuse value of the light is combined with the texture pixel value to produce the color result.
        // Determine the final diffuse color based on the diffuse color and the amount of light intensity.
        color += (diffuseColor * lightIntensity);
    }

    // Saturate the final light color. So it can not be greater than 1.
    color = saturate(color);

    // Multiply the texture pixel and the final diffuse color to get the final pixel color result.
    color = color * blendColor;

    //color = float4(1,1,1,1);

    return color;
}

```

and the InitializeShader of the Shader class

```
// This function is what actually loads the shader files and makes it usable to DirectX and the GPU.
bool Shader::initializeShader(ID3D11Device* device, HWND hwnd, WCHAR* vsFilename, WCHAR* psFilename)
{
    HRESULT result;
    ID3D10Blob* errorMessage;
    ID3D10Blob* vertexShaderBuffer;
    ID3D10Blob* pixelShaderBuffer;

    D3D11_INPUT_ELEMENT_DESC polygonLayout[3];
    unsigned int numElements;
    D3D11_BUFFER_DESC matrixBufferDesc;
    D3D11_SAMPLER_DESC samplerDesc;

    D3D11_BUFFER_DESC lightBufferDesc; // description variable for the light constant buffer.

    // Initialize the pointers this function will use to null.
    errorMessage = 0;
    vertexShaderBuffer = 0;
    pixelShaderBuffer = 0;

    // Compile the vertex shader code.
    result = D3DX11CompileFromFile(vsFilename, NULL, NULL, "LightVertexShader", "vs_5_0",
        D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL, &vertexShaderBuffer, &errorMessage, NULL);
    if(FAILED(result))
    {
        // If the shader failed to compile it should have writen something to the error message.
        if(errorMessage)
        {
            outputShaderErrorMessage(errorMessage, hwnd, vsFilename);
        }
        // If there was nothing in the error message then it simply could not find the shader file itself.
        else
        {
            MessageBox(hwnd, vsFilename, L"Missing Shader File", MB_OK);
        }

        return false;
    }

    // Compile the pixel shader code.
    result = D3DX11CompileFromFile(psFilename, NULL, NULL, "LightPixelShader", "ps_5_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, NULL,
                       &pixelShaderBuffer, &errorMessage, NULL);
    if(FAILED(result))
    {
        // If the shader failed to compile it should have writen something to the error message.
        if(errorMessage)
        {
            outputShaderErrorMessage(errorMessage, hwnd, psFilename);
        }
        // If there was  nothing in the error message then it simply could not find the file itself.
        else
        {
            MessageBox(hwnd, psFilename, L"Missing Shader File", MB_OK);
        }

        return false;
    }

    // Create the vertex shader from the buffer.
    result = device->CreateVertexShader(vertexShaderBuffer->GetBufferPointer(), vertexShaderBuffer->GetBufferSize(), NULL, &m_vertexShader);
    if(FAILED(result)){ return false; }

    // Create the pixel shader from the buffer.
    result = device->CreatePixelShader(pixelShaderBuffer->GetBufferPointer(), pixelShaderBuffer->GetBufferSize(), NULL, &m_pixelShader);
    if(FAILED(result)){ return false; }

    // Now setup the layout of the data that goes into the shader.
    // This setup needs to match the VertexType stucture in the ModelClass and in the shader.
    polygonLayout[0].SemanticName = "POSITION";
    polygonLayout[0].SemanticIndex = 0;
    polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[0].InputSlot = 0;
    polygonLayout[0].AlignedByteOffset = 0;
    polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[0].InstanceDataStepRate = 0;
    // The first 12 bytes are position and the next 16 bytes will be color
    polygonLayout[1].SemanticName = "TEXCOORD";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
    polygonLayout[1].InputSlot = 0;
    polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[1].InstanceDataStepRate = 0;
    // The third element for the normal vector that will be used for lighting.
    polygonLayout[2].SemanticName = "NORMAL";
    polygonLayout[2].SemanticIndex = 0;
    polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[2].InputSlot = 0;
    polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
    polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
    polygonLayout[2].InstanceDataStepRate = 0;

    // Get a count of the elements in the layout.
    numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

    // Create the vertex input layout.
    result = device->CreateInputLayout(polygonLayout, numElements, vertexShaderBuffer->GetBufferPointer(),
        vertexShaderBuffer->GetBufferSize(), &m_layout);
    if(FAILED(result)){ return false; }

    // Release the vertex shader buffer and pixel shader buffer since they are no longer needed.
    vertexShaderBuffer->Release();
    vertexShaderBuffer = 0;

    pixelShaderBuffer->Release();
    pixelShaderBuffer = 0;

    // in the vertex shader we currently have just one constant buffer so we only need to setup one here so we can interface with the shader.
    // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;

    // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
    result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
    if(FAILED(result)){ return false; }

    // Create a texture sampler state description.
    samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
    samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
    samplerDesc.MipLODBias = 0.0f;
    samplerDesc.MaxAnisotropy = 1;
    samplerDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
    samplerDesc.BorderColor[0] = 0;
    samplerDesc.BorderColor[1] = 0;
    samplerDesc.BorderColor[2] = 0;
    samplerDesc.BorderColor[3] = 0;
    samplerDesc.MinLOD = 0;
    samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

    // Create the texture sampler state.
    result = device->CreateSamplerState(&samplerDesc, &m_sampleState);
    if(FAILED(result)){ return false; }

    // Setup the description of the dynamic matrix constant buffer that is in the vertex shader.
    matrixBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    matrixBufferDesc.ByteWidth = sizeof(MatrixBufferType);
    matrixBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    matrixBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    matrixBufferDesc.MiscFlags = 0;
    matrixBufferDesc.StructureByteStride = 0;

    // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
    result = device->CreateBuffer(&matrixBufferDesc, NULL, &m_matrixBuffer);
    if(FAILED(result)){ return false; }

    // Setup the description of the light dynamic constant buffer that is in the pixel shader.
    // Note that ByteWidth always needs to be a multiple of 16 if using D3D11_BIND_CONSTANT_BUFFER or CreateBuffer will fail.
    lightBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
    lightBufferDesc.ByteWidth = sizeof(LightBufferType);
    lightBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    lightBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    lightBufferDesc.MiscFlags = 0;
    lightBufferDesc.StructureByteStride = 0;

    // Create the constant buffer pointer so we can access the vertex shader constant buffer from within this class.
    result = device->CreateBuffer(&lightBufferDesc, NULL, &m_lightBuffer);
    if(FAILED(result)){ return false; }

    return true;
}

```

Many thanks in advance! Jinx

# Answer
> 3 votes
If you're rendering points instead of triangles, your `IASetPrimitiveTopology` call may be at fault.

---
Tags: shaders, rendering, directx11
---


# Question
Title: How do you set event after a pawn takes damage?
How can I set event after bot/pawn takes damage in UDK? (possibly in Kismet?)

I need to do something similar to this: http://www.youtube.com/watch?v=gjRf5lTcWLY

# Answer
> 1 votes
Take a look at the pawn events, specifically the `TakeDamage` event. These are very similar to the actor events.

So you can extend the pawn and override `TakeDamage` to do what you want. Also, I believe you can access it through the UI as a pre-compiled event in Kismet.

---
Tags: udk, kismet
---


# Question
Title: Which game engine does "Ridiculous Fishing"(iOS) use?
Does it use game engine or just c++ libs? Its UI is concise and smooth.

# Answer
> 7 votes
It was made with openFrameworks and a custom library for spritesheet rendering, as told by Zach Gage (one of the developers) in the Ridiculous Fishing Reddit IAmA:

> I think the biggest tool I have is a very tiny library I wrote about 2 years ago with some help from my friend Ramsey Nasser. It's opensource here: https://github.com/stfj/ofxSpriteSheetRenderer although the docs aren't great.
>
> I use OpenFrameworks for all of the ease of getting setup in xcode and some of the event structure, but all of my openGL calls go through that custom library. It handles spritesheets (and on the fly created sprite sheets), rotation, batching, layers, antialiased shape and line drawing, etc. It's how we managed to have RF run so well even on super old devices

---
Tags: ios
---


# Question
Title: Collision in PyGame for spinning rectangular object.touching circles
I'm creating a variation of Pong. One of the differences is that I use a **rectangular structure as the object which is being bounced** around, and I use **circles as paddles**. So far, all the collision handling I've worked with was using simple math (I wasn't using the collision "feature" in PyGame). The game is contained within a 2-dimensional continuous space.

The idea is that the rectangular structure will spin at different speed depending on how far from the center you touch it with the circle. Also, any extremity of the rectangular structure should be able to touch any extremity of the circle. So I need to keep track of where it has been touched on both the circle and the rectangle to figure out the direction it will be bounced to.

I intend to have basically **8 possible directions (Up, down, left, right and the half points between each one of those)**. I can work out the calculation of how the objected will be dislocated once I get the direction it will be dislocated to based on where it has been touch. I also need to keep track of where it has been touched to decide if the rectangular structure will spin clockwise or counter-clockwise after it collided.

Before I started coding, I read the resources available at the PyGame website on the collision class they have (And its respective functions). I tried to work out the logic of what I was trying to achieve based on those resources and how the game will function. The only thing I could figure out that I could do was to make each one of these objects as a group of rectangular objects, and depending on which rectangle was touched the other would behave accordingly and give the illusion it is a single object. However, not only I don't know if this will work, but I also don't know if it is gonna look convincing based on how PyGame redraws the objects.

Is there a way I can use PyGame to handle these collision detections by still having a single object? Can I figure out the point of collision on both objects using functions within PyGame precisely enough to achieve what I'm looking for?

P.s: I hope the question was specific and clear enough. I apologize if there were any grammar mistakes, English is not my native language.

# Answer
I think pygame doesn't have complex functions to get collisions. But now to your question:

You can just calculate the angle between your ball and the paddle and use this for the direction of bouncing.

Maybe I do something really silly but this function will work for calculating the angle:

```
#returns angle and distance between two points
def angle_distance(x1,y1,x2,y2):
   distance = ((x1 - x2)**2 + (y1 - y2)**2)**0.5*pos_neg(y1 - y2)
   try:
      angle = math.acos((x1 - x2)/distance)/math.pi*180 + 180*(y1 - y2 >= 0)
   except ZeroDivisionError:
      angle = 0
   return angle,abs(distance)

#returns -1 or 1 if value is negative or positive
def pos_neg(value):
   return ((value >= 0)*2-1)

```

I hope this will help. If you want some more kollision stuff, also for rotated rectangles, just ask.
> 0 votes

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


# Question
Title: How can I make smoother upwards/downwards controls in pygame?
This is a loop I use to interpret key events in a python game.

```
# Event Loop
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
        sys.exit()
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_a:
            my_speed = -10;
        if event.key == pygame.K_d:
            my_speed = 10;
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a:
            my_speed = 0;
        if event.key == pygame.K_d:
            my_speed = 0;

```

The 'A' key represents up, while the 'D' key represents down. I use this loop within a larger drawing loop, that moves the sprite using this:

```
Paddle1.rect.y += my_speed;

```

I'm just making a simple pong game (as my first real code/non-gamemaker game) but there's a problem between moving upwards \<=\> downwards. Essentially, if I hold a button upwards (or downwards), and then press downwards (or upwards), now holding both buttons, the direction will change, which is a good thing. But if I then release the upward button, then the sprite will stop. It won't continue in the direction of my second input.

This kind of key pressing is actually common with WASD users, when changing directions quickly. Few people remember to let go of the first button before pressing the second. But my program doesn't accommodate the habit.

I think I understand the reason, which is that when I let go of my first key, the KEYUP event still triggers, setting the speed to 0. I need to make sure that if a key is released, it only sets the speed to 0 if another key isn't being pressed. But the interpreter will only go through one event at a time, I think, so I can't check if a key has been pressed if it's only interpreting the commands for a released key.

This is my dilemma. I want set the key controls so that a player doesn't have to press one button at a time to move upwards \<=\> downwards, making it smoother. How can I do that?

# Answer
What I always use is something like the following:

```
# somewhere outside the main loop
inputMap = [False, False]

# somewhere inside the main loop
for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_a:
            inputMap[0] = True;
        if event.key == pygame.K_d:
            inputMap[1] = True;
    if event.type == pygame.KEYUP:
        if event.key == pygame.K_a:
            inputMap[0] = False;
        if event.key == pygame.K_d:
            inputMap[1] = False;

# recalculate speed based on current input state
my_speed = 0
if inputMap[0]: my_speed -= 10
if inputMap[1]: my_speed += 10

```

Things become easier when you store the "state" of your input, and recalculate the speed each frame given the current state.

If you're not keen on clearing `my_speed` every frame, you could tweak it like this:

```
if inputMap[0]: my_speed = -10
if inputMap[1]: my_speed = 10
if not inputMap[0] and not inputMap[1]: my_speed = 0

```
> 1 votes

# Answer
In pygame you can check the unbuffered key state (not PRESSED/RELEASED events, but whether a key is CURRENTLY pressed) like so:

```
keys = pygame.key.get_pressed()
my_speed = 0
if keys[pygame.K_a]: my_speed -= 10
if keys[pygame.K_d]: my_speed += 10

```

Code is not tested, but should work nonetheless. Like this it will block when pressing both buttons (which IMO is what it should do) and move again when you release either of them.
> 0 votes

# Answer
Maybe the easiest way is to write an own class for this:

```
class buttons():
   def __init__(self):
      self.Wpressed = False
      ...
   def get_state(self,pygame):
      for event in pygame.get_event():
         if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w: self.Wpressed = True
            ...

```

Call get\_state() every frame and set the moving speed of your sprite:

```
my_speed = 0
if mybuttons.Wpressed: my_speed = -10
...

```
> 0 votes

---
Tags: python, input, pygame, keyboard
---


title: Collision detection performance problem

text:
# Question
Title: Collision detection performance problem
Using python and pygame I've built a collision detection system according to the instructions in this YouTube tutorial.

This is updated 40 times per second and controls movement and collision detection between some number of "agents", which are circles, each with a radius of 20:

```
for a in self.agents:
    dir = a.target - a.pos
    if dir.length >= 3:
        dir.length = 3
        a.pos = a.pos + dir

for a in self.agents:
    for a2 in self.agents:
        if a==a2: continue
        d = a.pos.get_distance(a2.pos)
        if d<40:
            overlap = 40 - d
            dir = a2.pos - a.pos
            dir.length = overlap/2
            a2.pos= a2.pos+dir
            a.pos= a.pos-dir

```

This looks and works great, as long as the number of agents is below 100. A higher number of agents will cause the pygame frame rate to drop. I left out some code which increases movement speed and pushback for a selected agent, but I don't think it has any consequence for the issue.

How can I make the code more efficient? For instance, would it help to make it so agents only check the distance of other nearby agents, say within a circle 4X the size of the agent, instead checking the complete list in every iteration of the code. Or is it better to change the method all together?

# Answer
> 8 votes
You're checking each agent against every other agent more than once. For example, consider a simple list of 3 agents, there should only 3 checks, you're checking 9 times, and that gets much worse with larger numbers. At 100 you're checking 10,000 times instead of 5,050.

When you iterate like you're doing, the comparison happens like this:

```
A1->A1 //Ignored
A1->A2
A1->A3
A2->A1 //Already checked
A2->A2 //Ignored
A2->A3
A3->A1 //Already checked
A3->A2 //Already checked
A3->A3 //Ignored

```

You need to check against the agents using a for loop. The inner for loop should start just after the agent being checked in the outer for loop.

```
for (int i = 0; i < agents.size(); i++) {
  for (int j = i+1; j < agents.size(); j++) {
    //Test
  }
}

```

The number of checks can be calculated by:

```
1+2+3+4+5+6+...+N-1

```

Otherwise written as:

```
(N(N+1)/2)-N

```

Its a Triangular number minus N (since we're cutting out the tests against self).

You should see significant improvements there, beyond that, spatial partitioning will help reduce the number of checks needed.

# Answer
> 8 votes
You might want to divide your world into segments/ a grid so that you only check collision for agents that are relevant. Agent A thats on the other side of the screen will NOT collide with B on te opposite side. So why check collision? Google for Spatial partitioning / quadtrees /spatial hashing.

I googled some for you:
Quadtrees
Grid

Also your second forloop should start at a1+1. Because all the previous agents were already checked And need no checking. This also eliminates the need of

```
if a1 == a2 : continue

```

Because it starts one index ahead of a1.

# Answer
> 4 votes
Here are some tips, from simple to more complex. All these optimizations can be used together. The more complex optimizations will probably yield greater performance improvements, but add them only if the simple ones are not enough:

* Prune out redundant tests as suggested by Jovan and Byte56. This will roughly half the number of tests, thus doubling performance.
* Eliminate expensive, unneeded calculation. Calculate only the distance^2 between agents, not the distance. Distance requires an expensive square root operation. Then instead of comparing to the sum of the radii, compare to the (sum of the radii)^2 (change 40 to 1600 in your case).
* Reduce the time each test takes even further by using simpler bounding box tests. This will eliminate relatively expensive multiplication operations for simple addition. This might produce "false positive" collisions because squares can overlap corners when circles don't. If you don't like this you can confirm these collisions by testing distance/radii only after the bounding box test says there is a collision.
* Prune out even more collision tests by partitioning agents into groups that you can assume will not collide. Grids are one method. Binary Space Partitions or Quadtrees are more advanced methods.

Collision Detection, Getting the most out of your collision tests by Dave Roberts is a great introductory tutorial on these topics and even introduces a simple axis-sorting method to prune redundant collisions tests that hasn't been mentioned, yet.

# Answer
> 2 votes
> This looks and works great, as long as the number of agents is below 100

```
for a in self.agents:
    for a2 in self.agents:
        if a==a2: continue
        d = a.pos.get_distance(a2.pos)
        if d<40:
            overlap = 40 - d
            dir = a2.pos - a.pos
            dir.length = overlap/2
            a2.pos= a2.pos+dir
            a.pos= a.pos-dir

```

That'll do it. You're veering on O(N^2) operation there.

> How can I make the code more efficient? For instance, would it help to make it so agents only check the distance of other nearby agents, say within a circle 4X the size of the agent, instead checking the complete list in every iteration of the code.

Yup. The general idea is known as *Hierarchical Collision Detection*.

One basic, popular approach is to use tiles/grid. It's fairly simple to keep track of what tile your *agent* is on, and check the surrounding tiles for collisions.

Another approach is to group the *agents* that are close to each other using a bounding primitive. There's several ways to do this, but for best results you should try to minimize the amount of empty space in your bounding object, by calculating what axis your agents are on and fitting the bounding primitive.

Take a look at the Minimum Bounding Rectangle. Object-Oriented Bounding Boxes are also popular.

# Answer
> 0 votes
For big "worlds" it could be a solution to create something like a network of rectangles over the whole "world". (I am not allowed to post an image)

Check if a circle collides with the part of the network from before. If they don't collide, check for all network's parts if the circle collides and save its value in a attribute of the circle. Also update a networks attribute which holds the colliding circles.

For circle-cirlce-collision just check the circles which collide the same part of the network. If the distance between most circles is not too small, this can extremely decrease the time needed for collision.

If you didn't understand my discription for the network or if you need a code example just feel free to ask.

---
Tags: collision-detection, python, pygame
---


title: Help developing grid maps

text:
# Question
Title: Help developing grid maps
I have been working with Tiled and Cocos2d lately but am having problems understanding how Im suppose to be doing the maps.
Tiled is not an image editor, so I create my tileset in Gimp. However it seems impossible for me to get grid lines that are the same as Tiled and so I dont know prior to importing the image (into Tiled) where the grid lines will be.

See the image below. Both Tiled and Gimp's grid lines are set to 32px however the grid lines are nothing alike between the two programs

How can I get the grid lines to match so that I can draw stuff knowing how many tiles it will take. Is there a better program for creating tileset or another way to do it?

# Answer
It seems that the grid lines in Tiled are 64px, not 32. If you look at the top-left 'thing', it occupies 128px according to Gimp (and therefore takes up 4 grid spaces across, as expected). However, in Tiled it only uses up 2 grid spaces across. This leads me to believe that actually, the Tiled map editor uses a 64px by 64px grid, not a 32x32 one.
> 3 votes

---
Tags: tiles, tilemap
---


# Question
Title: A controlled trapezoid transformation with perspective projecton
I'm trying to implement a controlled trapezoid transformation in Adobe Flash's ActionScript using the built-in perspective projection facility. To give you an idea of how the effect looks like:

https://i.stack.imgur.com/Pa1T0.jpg

I've been searching for a solution for a few days now and, apart from the tessellation alternative which produces poor quality results, no one has tried to employ perspective projection to achieve this effect. It's maybe because it requires solving some math, which is something I hope you could help me with.

So Flash uses a simple frustum model with a viewpoint, projection plane, and `focal length`, which is the distance from the viewpoint to the projection plane.

https://i.stack.imgur.com/1WmGa.jpg

There is also fieldOfView but it should be of no importance as its meaning appears to be overridden by focalLength (at least it's value makes no difference in my ActionScript experiments as long as the focal length is specified).

The rectangular piece of graphics is located right on the projection plane so that the middle point of its top edge is located in the projection center. To achieve the effect, the rectangle is rotated by some `angle`.

(Sorry, the forum wouldn't let me post more links to the drawings. Could anyone please edit it to put the last 2 imaged referred at the end of the source right here.)

\<\>

The question is, what should be the values of `focal length` and `angle` so that `new height` and `new bottom width` satisfy some given values that are desired for the effect? Or speaking mathematically:

Given:

* a frustum with `focal length`
* a rectangle with its `width` and `height`, which is pinned to the projection plane (z=0) of so that the midpoint of the rectangle's top edge is located right in the projection center of the frustum
* the needed `new height` and `new bottom width` of the rectangle after it's rotated and projected onto the projection plane

Unknowns to be found and applied to the perspective projection in order to get the desired `new height` and `new bottom width`:

* the `focal length` of the frustum
* the `angle` of rotation

If I missed out any other parameters or added any redundant ones, please correct me.

Also, is it possible to control the effect just by the angle with which the sides of the rectangle should be projected on the projection plane (the angle between the projected rectangle's side and its top edge) provided that the `new height` remains some constant value?

# Answer
> 1 votes
In a perspective projection, the projected size of any feature varies inversely with its depth (distance from the camera, measured along an axis through the center of projection). For instance an object twice as deep will appear half as large on-screen.

Because of this, you can work out the desired ratio of depths of the top and bottom edges of the trapezoid given the ratio of their lengths. If the top edge is half as long as the bottom edge, it must be twice as deep (given that they're really the same length in 3D space). If you've fixed the top edge at z = 0, you should be able to choose the depth of the bottom edge, and the focal length, to get the desired ratio of their depths. (Depth here is z + focalLength, according to your diagram.)

I would probably fix a standard value of focalLength, like 1.0, and calculate from that. Then you can do a bit of trigonometry to figure out the necessary vertical scaling and rotation to apply to your rectangle to manipulate it so that its bottom edge moves to the desired depth and height on screen.

(I suppose you *could* do it the way you suggested, by manipulating the camera's focalLength and the angle of the rectangle - but it seems much more natural to me to keep focalLength fixed and manipulate the angle and height of the rectangle.)

---
Tags: 3d, mathematics, flash, geometry, frustum
---


# Question
Title: How wise is this multithreading architecture?
I'm rewriting a game engine I wrote in an attempt to parallelize as much as possible. I'm considering making properties which may be accessed from multiple threads all use accessors which use boost scoped\_locks to avoid race conditions.

So then this way, say I have a character with base class CharacterBase. The X/Y/Z coords of the character are controlled through accessors with scoped locks. The main loop has 3 threads running, one to process physics, one to process rendering and one to process user input etc.

This will result in scoped\_locks basically being everywhere and explicitly required by design when users are extending the engine. I am planning on making this open source so I'm wondering if there are any significant flaws or draw-backs in this design either from a technical perspective or end-user perspective (for those extending the engine). Thanks!

# Answer
You propose running each separate "system" in parallel. The problem with this is that you will have to lock every single piece of shared state. CLARITY EDIT: When you have two parallel operations using all of the same data, lock contention and synchronization is going to slow things down so that you're not gaining many benefits from the parallelization.

The key to multithreading a game engine is to realize that many systems perform SIMD-like operations, where a single operation is performed over a large number of game objects. One example is adding each object's acceleration to its velocity, and then adding its velocity to its position. When something like this is happening, you can spread the workload over multiple threads. You'll see huge performance increases when parallelizing CPU-intensive operations like pathfinding or collision checking.

This is better because it doesn't require locking the game state and does not introduce any problems relating to synchronization or racing. In fact, your main loop does not really need to change at all!
> 15 votes

---
Tags: c++, opengl, opengl-es, multithreading, user-experience
---


title: D3DXCreateEffect Performance

text:
# Question
Title: D3DXCreateEffect Performance
Current performance analysis shows that D3DXCreateEffect is called many times with different shaders. Between each call, the D3DCompile DLL is being loaded and unloaded. Is there an easy way to keep that DLL loaded, i.e. by holding a CComPtr to some resource or something similar?

# Answer
What about just loading the DLL yourself using LoadLibrary and then calling FreeLibrary when you are done? From my understanding this will prevent the DLL from actually loading when anything else calls LoadLibrary on it so long as you are loading the exact same dll.

Per MSDN: The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count.
> 1 votes

# Answer
Honest answer - this isn't a performance problem - loading and unloading DLLs is something that Windows does on an *extremely* regular basis. You don't need to worry about it, unless you're calling it at runtime (in which case you have a design problem rather than a performance problem that you must solve).

You're much better off focussing your energies on things that actually are problems.
> 1 votes

---
Tags: directx, performance, directx9
---


# Question
Title: Is there a good comprehensive walk-through of deriving the math for 3D model rendering that starts from scratch?
I'd like to fully understand the math of rendering a 3D model in a 2D perspective.

I always find tutorials that are in terms of the APIs used to do the math for you, and not the math itself.

I'd like to understand it from the standpoint of geometry as opposed to linear algebra if possible. What I mean is, I'd like to be able to visualize what the matricies stand for in the 3D model and/or 2D image which is the result of rendering.

Is there a definitive source or sources I can consult for this?

# Answer
There are some old books like : -3D Math Primer for Graphics and Game Development (namely this)

You can get yourself an ebook. Just make a little search. Of course I would suggest the legal way :) .

Next you can search for software rendering. The topics you would like to read about are :

* Matrices (rotation, translation, projection, multiplying)
* Rasterization (that's a topic not many people dare to venture into
* bilinear filtering, trilinear filtering (and others)
* Quaternions
* Z buffer , visibility checking
* Occlusion querries

By the time you learn all about it, you will know what to learn next .
> 2 votes

---
Tags: 3d
---


# Question
Title: Love2D : Problem rotating image in a SpriteBatch
I'm working on a falling blocks type of game with triangular pieces. I'm using a `SpriteBatch` to accumulate and remember the pieces and their locations.

**The problem** is that when I rotate a *scaled `Image`* of the triangle, I get unexpected results, that is the origin of the sprite rotation is wrong -- but if I rotate a full-size image (no scaling) it works fine. The sprite should rotate from the center of the image (x + xScale * imgWidth / 2) and (y + yScale * imgWidth / 2). When xScale and yScale == 1, everything is fine. But as soon as it scales down to a fraction of the original size, the origin seemingly freaks out to weird sizes. Here's some code to inspect:

```
function love.load()
    img = love.graphics.newImage("triangle.png")
    sb = love.graphics.newSpriteBatch(img, 1024)
    imgWidth = img:getWidth()
    imgHeight = img:getHeight()
    x = 250
    y = 250
    xScale = 0.4
    yScale = 0.4
    xOrig = (xScale * imgWidth / 2)
    yOrig = (yScale * imgHeight / 2)
    angleDirection = 0
    id = sb:add(x, y, math.rad(angleDirection), xScale, yScale, xOrig, yOrig, 0, 0)
end

function love.update(dt)
    if love.keyboard.isDown(" ") then
        angleDirection = angleDirection + 180
        if angleDirection >= 360 then
            angleDirection = 0
        end
    end
    sb:set(id, x, y, math.rad(angleDirection), xScale, yScale, xOrig, yOrig, 0, 0)
end

function love.draw()
    love.graphics.draw(sb)
end

```

Now, to see the problem in action, run the preceding code. Change the `xScale` and `yScale` to a **1** to see the rotation work properly. Thanks in advance for any suggestions you have.

# Answer
> 1 votes
When setting the origin of a scaled image, use the original dimensions of the image instead of the final scaled size. For instance to set the origin to the center of a 200x200 image, you would use 100x100 even if it is scaled as the 'add' and 'set' functionality scale those values internally.

Glad I could help ;)

---
Tags: sprites, rotation, lua, love2d
---


# Question
Title: Pixel perfect collision detection between sprite and animated sprite
I am trying to make a collision between a sprite and an animated sprite. The animated sprite is the main character of the game. The problem I am facing is that when another sprite collides with the main character, it collides with the transparent bounding area around the character. How should I perform collision detection between the actual pixels of the character and any other obstacle sprite?

# Answer
> 2 votes
If your game need real world collision detection then you have to use box2d provided by andengine then after you do not have to worry about the collision. Because body for your different shapes have been created.

EDIT : For the purpose of pixel perfect collision detection the following link can help you that I think.

http://qwerjk.com/pixel-perfect/

In which they show demo and also provide example.

# Answer
> 2 votes
AndEngine Collision Extension: https://github.com/MakersF/AndEngineCollisionsExtension This is an extension that aims to bring different collision methods (perfect or approximations) to AndEngine GLES2

Supported Collision Methods: Pixel-Perfect Collision (supports: translation, scale, rotation, screw) It also support pixel-perfect collision between pixel-perfect shapes and retangular shapes, without the need for the latter to be a pixel-perfect shape. Alpha values different from 0 (you set the threshold that identify if a pixel is solid or not) You ca unse the utils methods to check the performances in your app or to output the collision mask to check if it is what you need

---
Tags: android, collision-detection, sprites, andengine
---


# Question
Title: How do I detect pixel-level collision using andEngine?
I'm developing a game for Android using andEngine, and I need to detect collisions only when two objects visually collide (not in blank space of the image). In J2ME, I'm able to do that using `helicopterSprite.collidesWith(buildingSprite, true)`.

However, andEngine only has `helicopterSprite.collidesWith(buildingSprite)`. What is the equivalent method for andEngine? How do I invoke pixel-level collision?

# Answer
> 2 votes
As of 14 June, 2011 andEngine hasn't added support for pixel-perfect collisions (taking transparent pixels) into account natively, as the developer's comment(as linked by 3nixios) states:

> "Sorry my post was a little misleading, transparent pixels are not taken into account. Though, when working with the PhysicsBox2DExtension, you can create a Body that has the outline of your actual Sprite content." -- Nicolas Gramlich

As he mentions, you can use Box2D physics in conjunction with andEngine to provide pixel-perfect collision detection.

# Answer
> 1 votes
This might be what you're looking for.

http://micah5.com/2011/05/30/pixel-perfect-collision-detection-for-andengine.html

# Answer
> 0 votes
Build your own bodies/fixtures/joints? This would easily allow you to make whatever body type (i.e. two separate boxes instead of one).

You could also get the bitmap of each when collision happens, and test the overlapping parts for an alpha of 0? This is effective and I have used it very easily, but it is EXTREMELY COSTLY as far as calculations for each collision. Would work with a single element using it to find collisions on a FEW other elements, but many collisions will destroy your FPS.

Here's my discussion on the AndEngine community about two specific ways I went about it: here.

# Answer
> 0 votes
AndEngine Collision Extension: https://github.com/MakersF/AndEngineCollisionsExtension This is an extension that aims to bring different collision methods (perfect or approximations) to AndEngine GLES2

Supported Collision Methods: Pixel-Perfect Collision (supports: translation, scale, rotation, screw) It also support pixel-perfect collision between pixel-perfect shapes and retangular shapes, without the need for the latter to be a pixel-perfect shape. Alpha values different from 0 (you set the threshold that identify if a pixel is solid or not) You ca unse the utils methods to check the performances in your app or to output the collision mask to check if it is what you need

---
Tags: collision-detection, android, andengine
---


# Question
Title: Drawing lots of tiles with OpenGL, the modern way
I'm working on a small tile/sprite-based PC game with a team of people, and we're running into performance issues. The last time I used OpenGL was around 2004, so I've been teaching myself how to use the core profile, and I'm finding myself a little confused.

I need to draw in the neighborhood of 250-750 48x48 tiles to the screen every frame, as well as maybe around 50 sprites. The tiles only change when a new level is loaded, and the sprites are changing all the time. Some of the tiles are made up of four 24x24 pieces, and most (but not all) of the sprites are the same size as the tiles. A lot of the tiles and sprites use alpha blending.

Right now I'm doing all of this in immediate mode, which I know is a bad idea. All the same, when one of our team members tries to run it, he gets very bad frame rates (~20-30 fps), and it's much worse when there are more tiles, especially when a lot of those tiles are the kind that are cut into pieces. This all makes me think that the problem is the number of draw calls being made.

I've thought of a few possible solutions to this, but I wanted to run them by some people who know what they're talking about so I don't waste my time on something stupid:

TILES:

1. When a level is loaded, draw all the tiles once into a frame buffer attached to a big honking texture, and just draw a big rectangle with that texture on it every frame.
2. Put all the tiles into a static vertex buffer when the level is loaded, and draw them that way. I don't know if there's a way to draw objects with different textures with a single call to glDrawElements, or if this is even something I'd want to do. Maybe just put all the tiles into a big giant texture and use funny texture coordinates in the VBO?

SPRITES:

1. Draw each sprite with a separate call to glDrawElements. This seems to involve a lot of texture switching, which I'm told is bad. Are texture arrays maybe useful here?
2. Use a dynamic VBO somehow. Same texture question as number 2 above.
3. Point sprites? This is probably silly.

Are any of these ideas sensible? Is there a good implementation somewhere I could look over?

# Answer
> 26 votes
The fastest way to render the tiles is packing the vertex data into a static VBO with indices (as glDrawElements indicates). Writing it into another image is totally unnecessary and will only require a lot more memory. Texture switching is VERY costly, so you will probably want to pack all tiles into a so called Texture Atlas and give each triangle in the VBO the right texture coordinates. Based on this, it should not be a problem to render 1000, even 100000 tiles, depending on your hardware.

The only difference between Tile rendering and Sprite rendering is probably that sprites are dynamic. So for the best, yet easy accomplishable, performance you can just put the coordinates for the sprite vertices into a stream draw VBO each frame and draw with glDrawElements. Also pack all textures in a Texture Atlas. If your sprites rarely move, you could also try to make a dynamic VBO and update it when a sprite moves, but that's total overkill here, as you only want to render some sprites.

You can look at a small prototype I made in C++ with OpenGL: Particulate

I render about 10000 point sprites I guess, with an average fps of 400 on a usual machine (Quad Core @ 2.66GHz). It is CPU capped, that means that the graphics card could render even more. Note that I don't use Texture Atlases here, since I only have a single texture for the particles. The particles are rendered with GL\_POINTS and the shaders compute the actual quad size then, but I think there is also a Quad Renderer.

Oh, and yes, unless you have a square and use shaders for texture mapping, GL\_POINTS is quite silly. ;)

# Answer
> 4 votes
Even with this number of draw calls you shouldn't be seeing that kind of performance drop - immediate mode may be slow but it's not *that* slow (for reference, even dear-old Quake can manage several thousand immediate-mode calls per frame without falling down so badly).

I suspect that there is something more interesting going on here. The first thing you need to do is invest some time in profiling your program, otherwise you stand a huge risk of rearchitecting based on an assumption that may result in zero performance gain. So run it through even something as basic as GLIntercept and see where your time is going. Based on the results of that you'll be able to tackle the problem with some *real* info about what your primary bottleneck(s) is/are.

# Answer
> 2 votes
Okay, since my last answer kinda got out of hands here is a new one wich is maybe more useful.

---

**About 2D-Performance**

First some general advice: 2D isn't demanding for current hardware, even largely unoptimized code will work. That doesn't mean you should Intermediate Mode though, atleast make sure you don't change states when unnecessary (for example don't bind a new texture with glBindTexture when the same texture is already bound, a if check on the CPU is tons faster than a glBindTexture-call) and not to use something so totally wrong and stupid as glVertex (even glDrawArrays will be way faster, and isn't any more difficult to use, it's not very "modern" though). With those two very simple rules the frame time should be atleast down to 10ms (100 fps). Now to get even more speed the next logical step is batching, e.g. bundling as many draw calls into one, for this you should consider implementing texture atlases, so you can minimize the amount of texture binds and thus increase the amount of rectangles you can draw with one call to a large amount. If you now aren't down to about 2ms (500fps) you are doing something wrong :)

---

**Tile maps**

Implementing the drawing code for tile maps is finding the balance between flexibility and speed. You can use static VBOs but that won't work with animated tiles or you can just generate the vertex data each frame and apply the rules I explained above, thats very flexible but by far not as fast.

In my previous answer I had introduced a different model in which the fragment shader takes care of the whole texturing, but it was pointed out that it requires a dependent texture lookup and thus might not be as fast as the other methods. (The idea is basically that you upload just the tile-indicies and in the fragment shader you calculate the texture coordinates, meaning that you can draw the whole map with just one rectangle)

---

**Sprites**

Sprites require a lot flexibility, making it very hard to optimize, aside from those discussed in the "About 2D-Performance" section. And unless you want ten thousands of sprites at the screen at the same time it's probably not worth the effort.

# Answer
> 0 votes
If all-else fails...

Set-up a flip-flop drawing method. Only update every other sprite at a time. Though, even with VisualBasic6 and simple bit-blit methods, you can actively draw thousands of sprites per frame. Perhaps you should look into those methods, as your direct method of just drawing sprites seems to be failing. (Sounds more like you are using a "rendering method", but trying to use it like a "gaming method". Rendering is about clarity, not speed.)

Chances are, you are constantly redrawing the whole screen, over and over. Instead of just redrawing only the changed areas. That is a LOT of overhead. The concept is simple, yet not easy to understand.

Use a buffer for the virgin static background. This is never rendered itself, unless there is no sprites on the screen. This is constantly used to "revert" where a sprite was drawn, to undraw the sprite in the next call. You also need a buffer to "draw on", which is not the screen. You draw there, then, once all drawn, you flip that onto the screen, once. That should be one screen-call per all your sprites. (As opposed to drawing each sprite on the screen, one at a time, or attempting to do it all at once, which will make your alpha blending fail.) Writing to memory is fast, and does not require screen-time to "draw". Each draw-call will wait for a return signal, before it attempts to draw again. (Not a v-sync, an actual hardware tick, which is a lot slower than the wait-time that RAM has.)

I imagine that is part of the reason you only see this issue on one computer. Or, it is falling back to software rendering of ALPHA-BLEND, which all cards do not support. Do you check to see if that feature is hardware supported, before you attempt to use it? Do you have a fallback (non-alpha-blend mode), if they do not have it? Obviously, you don't have code which limits (number of things blended), as I assume that would degrade your game content. (Unlike if these were just particle-effects, which are all alpha-blended, and thus, why programmers limit them, as they are highly taxing on most systems, even with hardware support.)

Lastly, I would suggest to limit what you are alpha-blending, to only things which need it. If everything needs it... You have no choice but to demand your users have better hardware requirements, or to degrade the game for the desired performance.

# Answer
> -1 votes
Create a sprite sheet for objects and a tile set for terrain like you would in other 2D game, there's no need to switch textures.

Rendering tiles can be a pain because each triangle pair needs their own texture coordinates. There's a solution to this problem however, it's called **instanced rendering**.

As long as you can sort your data in a way so that, for example, you can have a list of grass tiles and their positions, you can render every grass tile with a single draw call, all you have to do is provide an array of model to world matrices for each tile. Sorting your data this way shouldn't be an issue with even the simplest scene graph.

---
Tags: opengl
---


title: XNA Health Bar continually decreasing

text:
# Question
Title: XNA Health Bar continually decreasing
As per the Health bar tutorial on ... http://www.xnadevelopment.com/tutorials/notsohealthy/NotSoHealthy.shtml

I have set up the above, how do I make it decrease by 1 health per second?

I want to create a mini survival game, and this is an important factor.

Where am i going wrong? I want it to visibly decrease every second.

```
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Audio;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.GamerServices;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;
    using Microsoft.Xna.Framework.Media;

    namespace Health
    {
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    Texture2D healthBar;
    int currentHealth = 100;
    float seconds;
    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        healthBar = Content.Load<Texture2D>("HealthBar");

        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        currentHealth = (int)MathHelper.Clamp(currentHealth, 0, 100);

        seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (seconds >= 1)
        {
            currentHealth -= 1;
        }
        seconds = 0;

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, healthBar.Width, 44), new Rectangle(0, 45, healthBar.Width, 44), Color.Gray);
        spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, (int)(healthBar.Width * ((double)currentHealth / 100)), 44), new Rectangle(0, 45, healthBar.Width, 44), Color.Red);
        spriteBatch.Draw(healthBar, new Rectangle(this.Window.ClientBounds.Width / 2 - healthBar.Width / 2, 30, healthBar.Width, 44), new Rectangle(0, 0, healthBar.Width, 44), Color.White);
        spriteBatch.End();

        base.Draw(gameTime);
    }
}
    }

```

Cheers!

# Answer
You could do this using a float.

At the top of your `Game1.cs`, add:

```
float timer = 0f;

```

Then in `Update`:

```
timer += gameTime.ElapsedGameTime.Milliseconds;
if (timer >= 1000) // Your time, in milliseconds
{
    mCurrentHealth -= 1;
    timer -= 1000;
}

```
> 3 votes

# Answer
The reason YOUR code doesn't work is this:

```
seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
    currentHealth -= 1;
}
seconds = 0;

```

You reset seconds every frame, so it can NEVER be \>= 1. seconds = 0; should be inside your if. THat would fix it. Like this:

```
seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
    currentHealth --;
    seconds = 0;
}

```

However, I have a more elegant solution to your problem, if you want your HP-bar to decrease smoothly;

replace:

```
int currentHealth = 100;

```

with:

```
float currentHealth = 100;

```

Replace

```
seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (seconds >= 1)
{
    currentHealth -= 1;
}
seconds = 0;

```

with

```
//DeltaTime = Change in time. (delta means "change in" in physics/maths)
//This is always usefull in physics calc etc, so keep it and pass to other objects update instead of gametime:
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;

if (currentHealth > 0)
    currentHealth = Math.Max(0f, currentHeath - deltaTime);
else
    Die();

```
> 0 votes

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


# Question
Title: How do I adjust the origin of rotation for a group of sprites?
I am currently grouping sprites together, then applying a rotation transformation on draw:

```
private void UpdateMatrix(ref Vector2 origin, float radians)
{
     Vector3 matrixorigin = new Vector3(origin, 0);
     _rotationMatrix = Matrix.CreateTranslation(-matrixorigin) * Matrix.CreateRotationZ(radians) *  Matrix.CreateTranslation(matrixorigin);
}

```

Where the origin is the Centermost point of my group of sprites. I apply this transformation to each sprite in the group.

My problem is that when I adjust the point of origin, my entire sprite group will re-position itself on screen.

How could I differentiate the point of rotation used in the transformation, from the position of the sprite group? Is there a better way of creating this transformation matrix?

**EDIT**

Here is the relevant part of the Draw() function:

```
Matrix allTransforms = _rotationMatrix * camera.GetTransformation();

spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, allTransforms);

for (int i = 0; i < _map.AllParts.Count; i++)
{
    for (int j = 0; j < _map.AllParts[0].Count; j++)
    {
       spriteBatch.Draw(_map.AllParts[i][j].Texture, _map.AllParts[i][j].Position, null, Color.White, 0, _map.AllParts[i][j].Origin, 1.0f, SpriteEffects.None, 0f);
    }
}

```

This all works fine, again, the problem is that when a rotation is set and the point of origin is changed, the sprite group's position is offset on screen.

I am trying to figure out a way to adjust the point of origin without causing a shift in position.

**EDIT 2** At this point, I'm looking for workarounds as this is not working. Does anyone know of a better way to rotate a group of sprites in XNA? I need a method that will allow me to modify the point of rotation (origin) without affecting the position of the sprite group on screen.

**EDIT 3** I think if I was able to reset the screen coordinates to (0,0) at my sprite position, it would essentially allow me to re-position the origin without movement. I essentially need a way to set the current position/rotation, then start from scratch. Does anyone know if it is possible to make my sprite the new screen origin?

MOVING ORIGIN WITHOUT A ROTATION:

MOVING ORIGIN WITH A ROTATION (notice how it shifted upwards):

# Answer
I've got this implemented on my world editor. I can group sprites together and rotate them or scale them as a group around an arbitrary origin (which in my case is also the center of the group). I use something like this:

```
// Origin should be supplied in World-Space
void RotateGroup(IEnumerable<Sprite> sprites, Vector2 origin, float angle)
{
    Matrix transform =  Matrix.CreateTranslation(-origin.X, -origin.Y, 0f) *
                        Matrix.CreateRotationZ(angle) *
                        Matrix.CreateTranslation(origin.X, origin.Y, 0f);

    foreach(Sprite sprite in sprites)
    {
        sprite.Position = Vector2.Transform(sprite.Position, transform);
        sprite.Rotation += angle;
    }
}

```

I simply call this method when I want to rotate my group as a whole, and the method calculates a new position and rotation for each sprite in order to give the illusion that they are changing as a group.

Most importantly, I don't pass any special matrix to my drawing function. Each sprite still has its own individual position, rotation and origin which are independent from them being in a group or not.

This means that the group's origin is conceptual, and simply changing that value won't mess up with your sprites. The value is only used when rotating the group in order to specify where the pivot should be, but not when drawing.

In sum, the only matrix you should be passing to SpriteBatch.Begin is your View matrix, nothing else. Each sprite should be drawn according to its individual properties, and if you'd like to rotate them as a group, play around those properties, not around the drawing code.
> 6 votes

# Answer
Try changing

```
spriteBatch.Draw(_map.AllParts[i][j].Texture, _map.AllParts[i][j].Position, null, Color.White, 0, _map.AllParts[i][j].Origin, 1.0f, SpriteEffects.None, 0f);

```

to

```
spriteBatch.Draw(_map.AllParts[i][j].Texture, _map.AllParts[i][j].Position + _map.AllParts[i][j].Origin, null, Color.White, 0, _map.AllParts[i][j].Origin, 1.0f, SpriteEffects.None, 0f);

```

The second argument is where the point of origin should be located so if you change the point of origin from the default 0,0 you have to compensate for that.
> 0 votes

# Answer
Wait, you want to rotate all sprites at once.. then change the origin to texture.width and texture.height... and dont change it.. just change the actual rotation of the sprite.. and do this for all of the sprites.. and set the rotation of all sprites as a single float variable.. trust me it works!!
> 0 votes

---
Tags: xna, sprites, matrix
---


# Question
Title: UML Class Diagrams for 2D platformer Games?
I have to develop a small arcade game in C++ for a college assignment using a 2D Game Engine my teacher coded. What would be the best way to make a UML class diagram for it? It's very basic stuff but I feel like I don't have the experience to make proper decisions on how to organize the classes. Seeing some examples of Class Diagrams from like Super Mario or any platformer would be perfect. For example would it be better to make a "Level" class where I load the bitmaps and handle the collisions, and then call this one in the main class, or just load my level stuff directly from my main class? Thanks in advance!

# Answer
> 0 votes
Software design is not an exact science. There's no *"the right way"* to do something as complex (and vague) as a 2D platformer game. **Didn't your teacher show any examples of UML?** You should think about this as any other software (or complex system). A nice UML diagram should answer these basic questions:

**What are your entities and what are the possible interactions between these entities?**

Try following a top-down approach - going from the abstract, high level elements towards the small details.

> "I don't have the experience to make proper decisions on how to organize the classes."

I think this is the point of your homework. If you never try to implement what you've been taught, your education was just a waste of time and money.

---
Tags: c++, 2d, collision-detection, architecture, platformer
---


title: Travelling in a 2D grid

text:
# Question
Title: Travelling in a 2D grid
I have a 2D grid (x,y coordinates) where each cell corresponds to each pixel of the interface that I am working with and I have a point A(x1,y1). Now I need to travel around in the grid, and I wont just move this single point, but would like to move a bunch of points together. Now what do you think is the best figure that I shall move, i.e. a circle with a predefined radius, or a square with a fixed side.

Also, once I decide upon the figure, I need to know, what all points are there in the figure, given a specific central point, and work with those points too.

I was thinking that a square would be a better idea, since I'll just have to check the if the difference of the coordinates of the point to be checked from the central point is less than side/2.

But I've heard that calculations with circle are not bad either.

Kindly suggest,

# Answer
> 2 votes
1. Write a method that draws the "bunch of points" around the central point.

```
public void DrawMyPoints(Point center)
  {
     float radius = 10.0;
     MyPreferredGraphicsLib.DrawCircle(center, radius);
     //Draw a circle or a square, for example.
     //Most graphics libraries have dedicated methods for basic geometrical shapes.
  }

```
2. Every time you move the center point, clear the screen and redraw all the points:

```
public void MoveMyPoints(Point newCenter)
  {
     MyPreferredGraphicsLib.ClearScreen(); //Usually automatic in anything post-Pascal.
     DrawMyPoints(newCenter);
  }

```

---
Tags: path-finding, performance, grid
---


title: CPU usage, game loop and sleep()

text:
# Question
Title: CPU usage, game loop and sleep()
I've read about this topic on numerous discussion sites, but I can't seem to find a clear definitive (up-to-date) answer, and hopefully this will me some more insight:

I've read the excellent game loop time article on Fix your timestep!, but it dosn't take any consideration of the CPU usage, so it will run at 100%. My question then, is it BAD to run at 100% CPU in your game loop?

* If no, why? for example what about gaming on battery-driven devices like laptops? what about computer temperatures/fans/etc, and other windows applications?
* If yes, why dosn't the article mention it, because surely that would impact it significantly? what is the best way to fix this on desktops/PC - is there only the unreliable sleep()? How would it affect the game loop suggested by the article?

# Answer
Running at 100% CPU is ***not necessarily*** bad. On the other hand, it can be quite a significant problem. Basically, it depends on what you're running on and how you're running it. It would be best to view a couple of scenarios to show this:

### Scenario 1

* On a dedicated gaming machine, with only the game open

In this case, it is a *very good* idea to use as much as possible of the CPU for your game. It'll end up running faster, and it won't be stealing CPU from anything that needs it (the system processes will still get what they need, don't worry about that).

### Scenario 2

* On a computer also being used for word, the internet, a couple of Youtube videos (like in that Chrome ad), etc.

In this case, using all of the CPU for your game will cause the user to eject the disk, snap it in two (ignoring the fact that they could get a refund), chuck it in a fire, and then flame your forums. Joking aside, it is **never** a good idea to use all of the CPU if there's a likelihood that the user will be doing something else with their computer at the same time.

An important thing to consider as well is whether the target has a single or a multi-core computer. With a single-core computer, your game could take up **all** of the processing power, causing everything else to grind to a halt. On the other hand, with a multi-core computer, unless you're making full use of both cores, it should cause **no** problem - you'll be taking up one core, but there will be more for the other applications.

At the end of the day, it depends on these sort of issues as to whether using 99% of the CPU time is a good or a bad thing. Intrinsically, it isn't, but there can be cases where it is. Just remember that (on a computer, anyway - games consoles are a different species), it is often up to the machine to virtually allocate CPU time to different applications.
> 6 votes

---
Tags: c++, architecture, game-loop
---


title: How to create levels (tile maps)

text:
# Question
Title: How to create levels (tile maps)
I am new to game programming and I am having so much hard time learn on my own. My goal is to make a game with different levels.

so far my plan:
i have 2 classes
1 - main.java
2 - level\_01.java
3 - more levels if i want

in my level\_01.java:
1- make 2d array of map(done)
2- Do i need to store the make in arraylist or list?????
3- print in paint method?

```
public class level_01 extends levels
{
    private int map01[][] = {{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                             {2,2,2,2,2,2,2,0,0,2,2,2,2,2,2}};

    //Is a good idea to store this map in list or arraylist?
    //if yes should I use ArrayList or list?
    //or should i just print the right now?

```

# Answer
> 2 votes
If you're having this problem, maybe it's time to load maps from files. Create a Level class and have it load data from file. Typing levels into external files is much more flexible than creating a separate class for each level.

Two approaches are fairly simple (and commonly used):

* create a level1.txt file, in a format similar to the Java code you posted. You can edit in Notepad.
* create a level1.png file (yes, an image!), where each pixel represents a type of tile (pure red maps to tile type 0, pure green to tile type 1 etc). You can load it and read each pixel, similarly to reading a text file. You can edit in a paint-like graphics editor; the advantage is, it's really easier to "see" what's going on in an image, and paint is a better tool for this than notepad (because you can use a mouse). As weird as this sounds, it's a pretty decent approach (used for instance by Legend of Grimrock).

If this sounds to complicated for you, maybe you should try enhancing your general programming skills. Game programming is pretty complex, so it's usually a bad idea to learn programming through gamedev. Try doing some more algorithmic exercises, code kata or general Java tutorials.

# Answer
> 1 votes
You could use an editor tool.

Tiled comes to my mind. It allows you to create your map in a graphical interface and save it to a file. You just need to learn how to load and work its format into your game.

# Answer
> 0 votes
Hardcoding levels is OK during the early stage of development, but in the long run it will be inadequate. You will soon realize that it is a good idea to separate programming from game content.

Instead of using an own class for each level, you should rather use one generic Level class which takes a filename in the constructor and loads the map layout from a file.

Regarding the data structure to store your map data in your level class: You will find that you frequently access tiles by index, so using a two-dimensional array or two-level nested ArrayLists should be the best choice.

There is, however, a special case where a HashMap or a multidimensional tree might be better: When you have very large but sparse levels. Levels which span a very large area, but most of it is empty. In that case arrays would be very memory-inefficient, because they would have to waste space for all the empty areas.

For editing the level files themself, you should use a what-you-see-is-what-you-get editor. It's much more productive than entering the pure numbers and then loading the map in the game to see how it actually looks. Especially when your map format grows more complex and is more than just a single layer of map tiles. You could write your own map editor, or you could use an existing map editor like the free, open source editor Tiled.

When you program your own editor, you can have the map files be exactly how you want them, but when you use a 3rd party program like Tiled you either have to write a parser which is able to read the map format or write an export plugin which creates files in your preferred format. But that's ususally still a lot more work than writing your own mapping application from scratch. Unless you have very special requirements for your map editor and lots of manpower to spare, you should better use an existing solution.

---
Tags: tiles
---


# Question
Title: What operations should be multithreaded?
I wonder what game operations should be multithreaded, and which should always run on the main thread.

The most expensive operations I could come up with are:

* loading a level
* loading resources (for each level or at game initialization)
* updating game world (weather, liquids, chain reactions, lots of small entities, etc.)
* downloading from game server (level files, custom resources, player saves, object states, etc.)
* occasional heavy methods (large screenshots, per-pixel calculations, full world update)

Which of those operations should be threaded, and which should not? Which of them can be threaded most effectively by using as many threads as the host supports?

Or is it better to split some of these operations into blocks and execute each frame, bit by bit, without threading, and without causing frame drops?

# Answer
> 4 votes
Threading implies concurrency. Think of a logical flow. What would you like to happen in parllel and which actions should only occur AFTER something happens.

Modern computer architectur benefits from parallel computing. Either on CPU cores or the GPU.

In my humble opinion :

* I don't know if multithreading disk usage improves perfomance and loading times a lot (please try and let me know :D )
* On the other hand using data from the Internet should be absolutely parallelised. One doesn't depend on the other(much ;) )
* "updating game world" this is where parallelism shines. Like I said before, paralelised computation is better
* "occasional heavy methods" same. Sometimes you might wish to distribute the tough computation among a couple of frames if you can. You don't always need to keep everything as fast as the FPS

# Answer
> 3 votes
All operations that are performed over a large set of data, with each operation working independently from one another will benefit from parallelization. Here are some common examples of such tasks:

* Collision checking
* Pathfinding
* Constraint solving
* Particle simulation
* Joint pose interpolation

Some tasks, like pathfinding, are better suited to the CPU because algorithms like A\* involve a lot of dynamic branching. When you are performing particle simulation or joint pose interpolation, you can offload this work to the GPU because each operation is identical except for the data.

# Answer
> 2 votes
It really depends. You're likely to gain the most benefit by performing *operations with no data interdependence on each other* in parallel, but as with anything you should profile beforehand (and afterwards) to make sure you're getting the most benefit from your efforts.

For example, to give some concrete advice regarding one of your examples, loading data:

If you can factor your resource loading into independent chunks, this can be beneficial. However, you'll want to investigate whether or not you're already disk-bound. If the slow part of your loading operations is reading from the disk (more likely with non-SSDs, such as platter drives or optical media) you may not improve your situation. Similarly, if the ultimate destination of the data you read from the disk isn't independent, you should verify that the synchronization cost of installing all the loaded data into it isn't a bottleneck.

At work we all have SSDs in our development machines, and content containers store their data independently in memory, so switching our toolchain to a multithreaded loading system did have significant performance implications (a 600% improvement in load times). But your mileage may vary.

Similar caveats apply to other operations, such as game logic updates. If you can organize the problem into discrete chunks of computation that don't depend on eachother, you can probably see some benefit from a concurrent model. But if you find yourself having to employ lots of locks or other thread synchronization primitives, chances are you're actually trying to parallelize the serial part of the task and will introduce more overhead than you'll remove.

You want to approach concurrency at the large scale, not the small one. Think about splitting operations into multiple concurrent tasks on the scale of "loading data" and "per frame game updates." Generally, looking at the scale of "this big screenshot function" is too small to be useful -- thus, your "occasional heavy method" category of operations is not likely to gain much benefit. Screenshots are inherently serial, except for the actual disk IO portion (covered earlier in our discussion of loading), per-pixel operations are already best handled by the GPU, and I don't think a "full world update" is an "occasional heavy method" but rather a synonym for what was discussed previous regarding updating the game world.

---
Tags: multithreading
---


title: Moving a sprite diagonal?

text:
# Question
Title: Moving a sprite diagonal?
I wonder how I should increase and decrease the value of `xPos` and `yPos` to be able to move a sprite object diagonal and in different angles?

```
canvas.drawBitmap(image, xPos - (image.getWidth() / 2), yPos - (image.getHeight() / 2), null);

```

# Answer
> 3 votes
Casper gave a good answer, but you can also use *sin* and *cos* to move your sprite at a certain angle:

```
sprite.x += sin(angle) * amount;
sprite.y += cos(angle) * amount;

```

Of course, depending on what Sine and Cosine functions you're using, you may have to enter the angle in *radians/degrees*. Seeing as you're using Java, java.lang.Math comes with all the functions you'll need.

For more about *sin* and *cos*, look at this.

# Answer
> 1 votes
How about just working it out?

Assuming a coordinate system where 0, 0 is top-left. Defining our object's coordinates as being 0, 0 (x, y).

```
object.x += 50;
object.y += 50;

```

would move the object 50 pixels diagonally towards the bottom right corner.

---
Tags: java, android, game-mechanics
---


# Question
Title: How do I apply pixel shader to specific sprite in XNA 4.0 in a spritesort FrontToBack?
I have a set of sprite drawn in FrontToBack sortmode. In XNA 4.0, the effect must be as an input argument of `Begin()` function of `SpriteBatch`. However, If I reinvoke the function, then the sprite sorting is lost. Therefore, I have to find a way to implement the pixel shader within the `Begin()` and `End()` for specific texture drawn. I tried to use `effect.CurrentTechnique.Passes[0].Apply(),` but no pixel was shaded when I invoke this. On the other hand, if I put effect as an argument, then all of the sprites would be effected. Therefore, is there any convenient way to approach this?

By the way, what I am trying to do is to provide an overlay on an isometric tile using some kind of masking. Therefore, I want to draw such masking and programmatically change it to optional color.

Something like this (from final fantasy tactics):

I am not sure if pixel shader is the right way to approach it, but then I have to tackle the fact that I want to be able to specify optional color dynamically. Other than that, I really want it to animate, which I might approach this by creating several grayscale animated masking and saturate it using pixel shader.

# Answer
Changing effects and effect parameters in a single batch doesn't work unless if you're using the SpriteSortMode.Immediate. This happens because the sprite batch waits until you call spriteBatch.End() before starting the drawing.

It seems like you would like to use the spritebatch because you want to sort the sprites before drawing. If you manually sort the sprites and then draw them all using SortMode.Immediate you can use effect.CurrentTechnique.Passes\[0\].Apply() anywhere between .Begin() and .End().
> 3 votes

# Answer
This link might help you out with the issue:

http://msdn.microsoft.com/en-us/library/bb313868(v=xnagamestudio.31).aspx
> 1 votes

---
Tags: xna, sprites, isometric
---


title: How to get a smooth dimming with SSAO?

text:
# Question
Title: How to get a smooth dimming with SSAO?
I implemented SSAO in my game based on the tutorial at gamerendering.com. But the results I get are disappointing. Instead of a smooth effect as seen in the nvidia demos, my implementation causes either squashy dark noise or results in a huge performance hit for all the blurring.

This is my scene without SSAO applied.

And this is how the result looks.

For now I use the same code as provided in the example I linked above. How can I improve the result of the ambient occlusion shader? A lot of blurring seems to be very slow on the GPU. I would like to get a result similar to this by Nvidia. How do they do that?

# Answer
SSAO is frequently implemented with noisy sampling, plus a bilateral filter to smooth things out while preserving sharp edges. The tutorial only mentions this in passing in the second paragraph, so perhaps you missed it:

> This SSAO term is saved to the red channel to the texture. This result must be blurred before combined with the original scene render. The blur can for example be a bilateral blur.

From your screenshots, it appears you've implemented the base SSAO effect, but without the bilateral filter. There was a SIGGRAPH course on bilateral filtering in graphics that you might want to check out for additional information.
> 5 votes

---
Tags: opengl, shaders, glsl, ssao
---


title: DirectX11 without window attached?

text:
# Question
Title: DirectX11 without window attached?
I just wonder, if it's possible to initialize and use DX11 or DX9 for offscreen rendering only - meaning with no attached window. My intention is to do some GPU benchmarking before opening actual window. In this benchmarking some test scene is rendered, but should not be visible. (Actually depending on the benchmark score different windows are opened)

# Answer
Yes. You can initialize the Direct3D device using `D3D11CreateDevice`, which requires no window. You simply do not create a swap chain at all. You can still create offscreen render targets and draw to them in the usual way. Instead of calling `Present` on the swap chain, you can call `ID3D11DeviceContext::Flush` to kick the GPU with the work you've queued up.

If you later want to create a window, you can destroy the device and recreate it with `D3D11CreateDeviceAndSwapChain`, or you can create a swap chain and attach it to the existing device with `IDXGIFactory::CreateSwapChain`. (The `IDXGIFactory` is a separate COM object that needs to be created with `CreateDXGIFactory` first.)
> 20 votes

---
Tags: c++, directx11
---


# Question
Title: General Sequence of Events for a 2D shooter
I'm having some trouble understanding ways to sequence events in my game. Assume the game is data driven, what is the best way to control the events?

Do I have some sort of EventSequencer that loads all the possible events for a level and the enemies? If so, would it be a list of events that I 'fire' off one at a time into the game engine and when the event is completed or finished, remove the event and fire the next one?

My thoughts were similar to the above questions: Build an event sequencer that manages what event is running and loads the proper event (enemy wave, boss battle, etc)...

I'm just not sure if this is a good idea.

# Answer
> 2 votes
Based on your example "events", I would probably use a state machine with rules on which state can come next. You can be in EnemyWave state, and as soon as the last enemy is killed switch to BossBattle state. A simplistic code fragment might look like this

```
class EnemyWave : State
{
    void main()
    {
        // Game logic for handling the enemy wave
    }
    State nextState()
    {
        if(allEnemiesDead)
        {
            return new BossBattle();
        }
        else
        {
            return this;
        }
    }
}

mainLoop()
{
    // Game logic goes here

    // State specific logic
    currentState.Main();

    // More game logic

    // Ask state for next state
    currentState = currentState.nextState();
}

```

If the game is data driven, then your nextState condition would be driven by your data, and your game logic for the particular state just gets swapped in.

---
Tags: xna, architecture
---


# Question
Title: Shouldn't fragment lighting have the same effect as vertex lighting with only ambient and diffuse lights?
With infinite light source and only ambient and diffuse lights — no specular light, it seems the rendering results of vertex lighting and fragment lighting should be the same, because all the lighting calculations are linear and it means calculation-then-interpolation and interpolation-then-calculation should be the same. However, the actual results are still not exactly the same, with fragment lighting still smoother. What did I misunderstand? Or is it just because of loss of arithmetic precision during calculation-then-interpolation?

Code of fragment lighting:

```
// Vertex shader

attribute vec4 Position;
attribute vec3 Normal;

uniform mat4 Projection;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

varying vec3 EyespaceNormal;

void main(void)
{
    EyespaceNormal = NormalMatrix * Normal;
    gl_Position = Projection * Modelview * Position;
}

// Fragment shader

varying mediump vec3 EyespaceNormal;

uniform highp vec3 LightPosition;
uniform highp vec3 DiffuseMaterial;
uniform highp vec3 AmbientMaterial;

void main(void)
{
    highp vec3 N = normalize(EyespaceNormal);
    highp vec3 L = normalize(LightPosition);
    highp float df = max(0.0, dot(N, L));

    lowp vec3 color = AmbientMaterial + df * DiffuseMaterial;

    gl_FragColor = vec4(color, 1);
}

```

Code of vertex lighting:

```
// Vertex shader

attribute vec4 Position;
attribute vec3 Normal;

uniform mat4 Projection;
uniform mat4 Modelview;
uniform mat3 NormalMatrix;

uniform highp vec3 LightPosition;
uniform highp vec3 DiffuseMaterial;
uniform highp vec3 AmbientMaterial;

varying lowp vec3 Color;

void main(void)
{
    highp vec3 EyespaceNormal = NormalMatrix * Normal;

    highp vec3 N = normalize(EyespaceNormal);
    highp vec3 L = normalize(LightPosition);
    highp float df = max(0.0, dot(N, L));

    Color = AmbientMaterial + df * DiffuseMaterial;

    gl_Position = Projection * Modelview * Position;
}

// Fragment shader

varying lowp vec3 Color;

void main(void)
{
    gl_FragColor = vec4(Color, 1);
}

```

# Answer
> 6 votes
Vector normalization is not linear, and this is sufficient to make the difference.

Imagine normals as points on the unit sphere; then linear interpolation cuts across the interior, rather than moving along the surface, and this means that an interpolated normal will not correspond to any possible surface orientation (it will have a magnitude less than 1). Normalizing the normals after interpolation restores a reasonable result.

Nathan Reed got the link there first but this question at Math.SE is what I had in mind for more formal information on the topic.

---
Tags: lighting
---


title: Complex collisions in pygame

text:
# Question
Title: Complex collisions in pygame
I've seen many tutorials for simple rectangle or circle-based collision detection with pygame.

But how can I do more complex collisions with arbitrary polygons?

Is the only option pixel-based collision detection?

# Answer
Short answer: yep. :P

Long answer: rectangle collisions are built into Pygame. Circle collisions are simple math. Use Box2D for anything more complicated.
> 2 votes

# Answer
Have a look at pylygon.

> a polygon object with rotation and collision detection methods.

It's rather lightweight compared to a full blown physics library, and collision detection is as simple as:

```
r = obj1.C - target_pos
results = obj1.raycast(obj2, r, self_theta = obj1_rotation)
if results:
    # collision
else:
    obj1.move_ip(*-r) # move the object

```
> 0 votes

# Answer
I have developed a function for the collision of a circle and a rotated rectangle. Not very complex but this is everything I need for collision:

```
#requieres math imported, width, height of rect,
#angle between rect and point to collide with, rotation angle of rect
def rect_distance(b_side_x,b_side_y,angle_b_p,b_angle=0):
   w1 = angle_b_p - b_angle
   w1 %= 360
   w_b = round(math.atan(b_side_x/b_side_y)/math.pi*180)
   if (w1 > 90 - w_b and w1 < 90 + w_b) or (w1 > 270 - w_b and w1 < 270 + w_b):
      distance = round(b_side_y/2/math.sin(w1*math.pi/180))
   else:
      distance = round(b_side_x/2/math.cos(w1*math.pi/180))
   return abs(distance)
#returns distance between middle and side of a (rotated) rect under an angle

```
> 0 votes

---
Tags: collision-detection, pygame
---


# Question
Title: Collision detection against large arbitrarily shaped textures
What is the most effecient way to do collision detection on strangely shaped textures in XNA? Here is an example texture:

As you can see, it is far from a perfect square. I want the player to collide with the brown parts and pass through the transparent ones.

How do I create a bounding box that wraps around irregular terrain? Should I create many smaller bounding boxes instead?

# Answer
> 2 votes
Don't be discouraged, what you're trying to do is very possible and has been used in several shipped games; I haven't tried such an approach myself, but I know at least two people who have managed to get such a system working.

This paper describes how to get smooth well-behaved collision information (penetration depth and surface normal) from bitmap data. http://imrtechnology.ngemu.com/downloads/tutorial.pdf

Alternately, you could generate/calculate a distance field texture which gives, for each pixel, the distance to the closest point on the surface of the solid. Once you have a distance field, you can very easily collide circles against it. This thread covers some ways to generate distance fields: How can I generate signed distance fields (2D) in real time, fast?

# Answer
> 0 votes
Look at spatial hierarchies like quadtrees or binary space partitioning (BSP) trees.

These data structures are independent of C#/XNA. The basic idea is like what you mentioned: They involve many small bounding boxes. However, you don't have just a list of small bounding boxes, but instead build a tree structure where every node of the tree represents a bounding box and every branch of that node represents *even smaller* bounding boxes.

For example, a quad tree works like this: Start out with one giant bounding box. Insert your objects (for example your pixels) into it. After a certain treshold it will split into 4 smaller bounding boxes. And this continues on. The wikipedia article demonstrates it well.

Instead of checking, say, the bounding box of your character, against each pixel in your texture you check it against the biggest bounding box for your image, then the smaller ones contained by it and so on, until you finally you will arrive at a node in your tree that contains only a few pixels to check against, which you can do efficiently.

---
Tags: xna, collision-detection, xna-4.0
---


title: Theory behind worm like movement?

text:
# Question
Title: Theory behind worm like movement?
I don't want code or anything that will make this too easy for me, but I'm just starting the development of a little game and I want to add worms to it, I want the worms to be Terraria like. My current idea is to make the worm be composed of multiple entities, one being the head and the rest parenting each other leading downwards from the head. However, this in my opinion sounds inefficient and might be lag inducing when there are a large number of worms in the entity map. Does anyone have any other theories on how I can implement a worm- like movement?

Terraria worm video: http://www.youtube.com/watch?v=PhFR8bDQA5w

# Answer
> 1 votes
Well you aren't quite far from the famous approach for Snake like games. Let the worm be represented as an array of segments. Head being the 0 element of array. Head should controll the movement of the body while each segment would follow its predecessor.

---
Tags: movement
---