# Question
Title: "Line of sight" path across navigation mesh
I want to calculate the line of sight in a navigation mesh.

Consider the image below, the yellow line is the result of only A\* and the red line is the result of a line of sight" algorithm that uses the yellow line as input. Now the unit can move directly without “zig-zagging”.

What is an algorithm to calculate that "line of sight"?

# Answer
You are looking for a funnel algorithm.

Here you are a simple one

http://digestingduck.blogspot.com.es/2010/03/simple-stupid-funnel-algorithm.html

Basically, the algorithm identify edges as portals, and build a funnel that is tested against the vertex of the edges to check if they are inside funnel or not.

In step A the funnel is built with the start position and the portal crossed by yellow line.

In step B the next portal is checked, the upper vertex is inside the funnel, so the funnel upper line now pass though it. But the bottom vertex is out of the funnel because red line in under green line, so bottom line will not pass though it, it will continue passing through the bottom vertex of previous portal.

As you can check the funnel will be smaller, and smaller, until step F, where the funnel is not possible to be build, because red line makes a bad funnel, so the upper vertex is choosed as new start point and a new funnel would be build if the end point is not in that mesh.

Realize that this kind of algorithm lets a simple solution to the model size problem too, because you can consider that the portals are smaller by the 2xradius of your model.
> 7 votes

# Answer
There's a simple technique that can be used with generated paths using this line of sight idea. Basically, you want to walk the path, and at each node, "look back" two the *node before the last* to see if it's visible. If the node before last is visible, you can remove the last node (since you have line of sight between your current node and the node before last, the last node, being an intermediate node, is not required).

A Gamasutra article has the following pseudo code example:

```
checkPoint = starting point of path
currentPoint = next point in path
while (currentPoint->next != NULL)
if Walkable(checkPoint, currentPoint->next)
// Make a straight path between those points:
temp = currentPoint
currentPoint = currentPoint->next
delete temp from the path
else
checkPoint = currentPoint
currentPoint = currentPoint->next

```

This algorithm does as you want, where the `Walkable` function is essentially a line-of-sight function, but slightly improved to also include situations where the path is visible, but not walkable (i.e. pits, traps, restricted zones).
> 7 votes

---
Tags: ai, path-finding, navmesh
---


title: Run menu in gameloop or as activity?

text:
# Question
Title: Run menu in gameloop or as activity?
Currently I am running my menu (with buttons "new game" and "choose level") as an xml view of an activity, that then starts my gameactivity with custom view run on a gameloop. But Im starting to see some restrictions with this.

Would it be a terrible idea to let the menu be part of the gameloop and just add another state for it, like `gameState = MENU` ? and then render and update touch accordingly.

Does anyone have any experience with this and if so how did you choose to solve it?

# Answer
> 1 votes
It's better to set the menu in the game loop with your gameState = MENU.

Thus you won't have a waiting time between the moment when you have touched 'Play' and the moment when the game start.

As you said, separate menu from gameloop can bring some problems for the user experience.

You should use the game engine to render the Menu.

---
Tags: java, android, optimization
---


# Question
Title: How can I check for key releases between keyReleased callbacks?
Slick2D's `Input` class has a `isKeyPressed()` method that returns a boolean value according to whether the specified key has been pressed. I want to check if a key has been released in the same fashion.

I looked into adding a `KeyListener` to the input object, and overriding the `keyReleased()` method. However, because I am currently handling input in the `update()` method of my `BasicGame`, this would fracture my code by handling input in two different places, which I'd like to avoid.

# Answer
> 1 votes
So you've got **callbacks**, but you really want **state**.

Here's an adapter:

Every frame (or on callbacks), update an associative map (`HashMap` in Java lingo) that maps from key codes to a status of whether that key *was just pressed*, *is held down* or *was just released*.

```
// In a `GameState` class

game.onTick()
    // Turn "released" keys off and "pressed" keys "held"
    for k,status of keys
        if status is "pressed"  then keys[k] = "held"
        if status is "released" then keys[k] = null
        // otherwise stay the same

game.onKeyPressed(k)
    keys[k] = "pressed"

game.onKeyReleased(k)
    keys[k] = "released"

```

Then interrogate that map from everywhere else that cares.

In Java, it'll likely be faster and more readable by refactoring all the state `String`s to `Enum`s, but this is is the idea. Of course, implementing `getKeyReleased` is then a `HashMap`-access one-liner.

---
Tags: java, input, slick, keyboard
---


# Question
Title: Why do I get "function not supported" exceptions for OpenGL 3.2 functions using LWJGL?
I am currently having an issue trying to initialize a frame buffer using LWJGL. When I try to call GL32.glFramebufferTexture(int, int, int, int) it throws a "Function is not supported" error. I have checked to make sure that the function is supported on my system using an OpenGL Extensions Viewer.

Here is the exact error:

```
Exception in thread "main" java.lang.IllegalStateException: Function is not supported
at org.lwjgl.BufferChecks.checkFunctionAddress(BufferChecks.java:58)
at org.lwjgl.opengl.GL32.glFramebufferTexture(GL32.java:389)
at com.domain.name.graphics.GameWindow.startRendering(GameWindow.java:145)

```

Line 145 in GameWindow looks like:

```
GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, colID, 0);

```

colID is set as such:

```
colID = GL11.glGenTextures();

```

Any help would be very welcome.

System info & proof of function support:

# Answer
All your `import` does is bring the contents of those namespaces into scope.

It sounds like you probably didn't actually request an appropriately-versioned OpenGL context (that is, one with 3.2 support). To do so, you must provide context attributes requesting the desired version when you call `Display.create()`

```
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAtrributes = new ContextAttribs(3, 2)
    .withForwardCompatible(true)
    .withProfileCore(true);

try {
    Display.setDisplayMode(new DisplayMode(320, 240));
    Display.setTitle("Version selection");
    Display.create(pixelFormat, contextAtrributes);
} catch (LWJGLException e) {
    e.printStackTrace();
    System.exit(-1);
}

```
> 3 votes

---
Tags: opengl, lwjgl, macos
---


# Question
Title: GLSL - std140 uniform block - fields(vec, float, mat4) always 0.0
Ok,

First of all, if just use uniforms everthing works like it should. Switching to uniform blocks nothing goes, as all values look like 0.0. I tested this with various if-then-else stuff within the vertex shader and modifying the output color.

According to CodeXL 1.3(here the data is listed as VBO, but I think this is only cosmetic), GL.BindBuffer with GL.MapBuffer, or GL.GetBufferSubData there is really the proper data within my ubo but nonetheless the uniform block in the shader contains 0.0 only.

workflow:

```
    //Create UBO
    BufferUBOName = new int[2];
    GL.GenBuffers(2, BufferUBOName); // Generate the buffer
    BufferIndex = 0;

    GL.BindBuffer(BufferTarget.UniformBuffer, BufferUBOName[0]); // Bind the buffer for writing
    GL.BufferData(BufferTarget.UniformBuffer, (IntPtr)uboWorldData.SizeInBytes, IntPtr.Zero, BufferUsageHint.StreamDraw);  // Request the memory to be allocated
    GL.BindBufferRange(BufferRangeTarget.UniformBuffer, BufferIndex, BufferUBOName[0], IntPtr.Zero, (IntPtr)uboWorldData.SizeInBytes); // Bind the created Uniform Buffer to the Buffer Index

```

Creating and linking the shaders works fine and gives the following ouput :

```
GL   4.3
GLSL 4.30
Shader: basic_fs ok
Shader: basic_vs ok
ShaderProgram :hexgrid [ basic_vs, basic_fs ]
    Active Uniform Block : UboWorld
      Size         : 144
      BlockBinding : 1
      BufferPoint  : 0
        Name : UboWorld.time
          Type[n] : Float [4]
          Offset  : 0
        Name : UboWorld.screenwidth
          Type[n] : Int [4]
          Offset  : 4
        Name : UboWorld.screenheight
          Type[n] : Int [4]
          Offset  : 8
        Name : UboWorld.promat
          Type[n] : FloatMat4 [64]
          Offset  : 16
          matrix stride: 16
        Name : UboWorld.mvpmat
          Type[n] : FloatMat4 [64]
          Offset  : 80
          matrix stride: 16

    // Done after successful program linking
    uniformBlockIndices["ubodata"] = GL.GetUniformBlockIndex(shaderprog.Handle, "UboWorld"); // Gets the uniform variable Location
    if (uniformBlockIndices["ubodata"] != -1)
        GL.UniformBlockBinding(shaderprog.Handle, uniformBlockIndices["ubodata"], BufferUBOName[0]);

```

Then VBO / VAO are created and working fine, incl. drawing elements.

On UpdateFrame the UBO data will be processed like:

```
    GL.BindBuffer(BufferTarget.UniformBuffer, BufferUBOName[0]);
    GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, (IntPtr)uboWorldData.SizeInBytes, ref uboWorld);

```

The offsets are taken from the information after program linking and reading the various values for the UniformBlockActiveUniforms. I skip the output here as the struct should reflect it properly.

```
    [StructLayout(LayoutKind.Explicit)]
    struct uboWorldData
    {
        [FieldOffset(0)]
        public float time;
        [FieldOffset(4)]
        public Int32 screenwidth;
        [FieldOffset(8)]
        public Int32 screenheight;
        [FieldOffset(16)]
        public Matrix4 projectionMatrix;
        [FieldOffset(80)]
        public Matrix4 modelviewMatrix;

        public static readonly int SizeInBytes = 144;
    };

```

Vertex shader for testing:

```
    #version 400
    in vec3 in_position;
    in vec3 in_normal;
    out vec3 normal;
    out vec3 colortime;
    out vec3 colortimeubo;

    // These uniforms work
    uniform mat4 mvpmat;
    uniform mat4 promat;
    uniform float time;

    // This compiles fine. But always 0.0
    layout(std140) uniform UboWorld {
        float time;
        int screenwidth;
        int screenheight;
        mat4 promat;
        mat4 mvpmat;
    } w;

    const float pi = 3.1415;

    void main()
    {
      // This uses the UNIFORM FLOAT
      colortime = vec3(abs(sin(time * 360.0 * pi / 180.0)), 0.3, 0.3);
      // Here the uniform UboWorld
      colortimeubo = vec3(abs(sin(w.time * 360.0 * pi / 180.0)), 0.3, 0.3);

      normal = (mvpmat * vec4(in_normal, 0)).xyz;
      gl_Position = promat * mvpmat * vec4(in_position, 1);
    }

```

Any hints why w.time and also w.mvpmat or w.promat are always zero filled ???

# Answer
Here you are binding the buffer to the index `BufferIndex`:

```
GL.BindBufferRange(BufferRangeTarget.UniformBuffer, BufferIndex,
                   BufferUBOName[0], IntPtr.Zero,
                   (IntPtr)uboWorldData.SizeInBytes);

```

The problem probably lies in the following line:

```
GL.UniformBlockBinding(shaderprog.Handle, uniformBlockIndices["ubodata"],
                       BufferUBOName[0]);

```

Which should be:

```
GL.UniformBlockBinding(shaderprog.Handle, uniformBlockIndices["ubodata"], BufferIndex);

```
> 1 votes

---
Tags: opengl, c#, glsl, opentk
---


# Question
Title: Why is my FPS computation yielding higher numbers than I expect?
I have following code:

```
void Game::execute()
{
    isExit = false;
    init();

    double dt = 1.0 / 60.0;
    boost::timer timer;
    double accumulator = 0.0;

    boost::timer fps_timer;
    int fps = 0;
    while (isExit != true)
    {
        handleEvent();
        accumulator += timer.elapsed(); timer.restart();
        while (accumulator > dt)
        {
            accumulator -= dt;
            handleEvent();
            update(); // updating physics
        }
        if (fps_timer.elapsed() > 1.0) //if 1 second is elapsed
        {
            fps_timer.restart();
            m_fps = fps;  //m_fps - is result, which is rendered
            fps = 0;
        }
        else fps++;
        render(); // main rendering command
    }
}

```

And usually `m_fps` is equal 300-400. But I expect to see 30-60. Where I did wrong?

# Answer
you're incrementing fps as fast as possible, regardless if you called the following:

```
while (accumulator > dt)
{
    accumulator -= dt;
    handleEvent();
    update(); // updating physics
}

```

Try updating to the following:

```
while (isExit != true)
    {
        handleEvent();
        accumulator += timer.elapsed(); timer.restart();
        while (accumulator > dt)
        {
            accumulator -= dt;
            handleEvent();
            update(); // updating physics
            render();
            fps++;
        }
        if (fps_timer.elapsed() > 1.0) //if 1 second is elapsed
        {
            fps_timer.restart();
            m_fps = fps;  //m_fps - is result, which is rendered
            fps = 0;
        }
    }

```
> 1 votes

# Answer
Let's break down your code:

```
accumulator += timer.elapsed(); timer.restart();

```

On every tick, `accumulator` is incremented by the elapsed time of the previous tick.

```
while (accumulator > dt)
{
  accumulator -= dt;
  handleEvent();
  update(); // updating physics
}

```

Once `accumulator` is *more than* 1/60th of a second you tick your physics in "1/60th second" intervals until accumulator is under a 1/60th of a second. This is probably why you expect to have frame-limiting in your FPS computation. However:

```
if (fps_timer.elapsed() > 1.0) //if 1 second is elapsed
{
  fps_timer.restart();
  m_fps = fps;  //m_fps - is result, which is rendered
  fps = 0;
} else {
  fps++;
}

```

Your actual computation to increment the FPS counter happens *outside* that frame-limiting code, above. So you're computing the "unlocked" FPS rather than the locked one you are expected.

To fix this, you can move the `fps` increment inside the `while(accumulator...` loop.
> 1 votes

# Answer
Your fps is actually displaying correctly (as in, the number displayed is equal to the number of renders per second). Notice that you are calling `render()` and incrementing `fps` *outside* of the `while(accumulator > dt)` loop. This means that your `fps` variable is being incremented on every single cycle of the `while(!isExit)` loop. Another thing that I would like to point out, is that you are calling `render()` more than what you need to.

**To solve both of these issues**, You simply add another variable outside of your `while(!isExit)` loop. You can call it something like `shouldRender`. Then, inside of your `while(accumulator > dt)` loop, add the line `shouldRender = true`. Then, add the following block of code after your `while(accumulator > dt)` loop:

```
if(shouldRender)
{
    render();
    shouldRender = false;
    fps++;
}

```

Because you are now only rendering if an update has occurred during the current iteration of the `while(!isExit)` loop, the fps will now be capped to the number of updates per second.

One last thing. Instead of writing `while(isExit != true)`, you can simply write `while(!isExit)`. This doesn't really affect performance, but it makes the code a bit cleaner.

The resulting code should now look like this:

```
...
bool shouldRender = false;
while (!isExit)
{
    handleEvent();
    accumulator += timer.elapsed(); timer.restart();
    while (accumulator > dt)
    {
        accumulator -= dt;
        handleEvent();
        update(); // updating physics
        shouldRender = true;
    }
    if(shouldRender)
    {
        render();
        shouldRender = false;
        fps++;
    }
    if (fps_timer.elapsed() > 1.0) //if 1 second is elapsed
    {
        fps_timer.restart();
        m_fps = fps;  //m_fps - is result, which is rendered
        fps = 0;
    }
}

```
> 0 votes

---
Tags: c++, game-loop, frame-rate
---


title: Android Device Screen Flicker

text:
# Question
Title: Android Device Screen Flicker
I have made sudoku type game. I am about to complete my game in 2d. At present, my game run smoothly on higher configuration devices such as Sony Experia Sola, Samsung Note 2 and Google Nexus.

But it creates screen flickering problem in my HCL ME tablet. I don't what is problem going on. I notice that when I load prefabs then it start flickering problem. If I don't create any prefab then it don't flicker at all.

At present my development game resolution is 2048x1536. So friends I need support from your side. If you want any more detail then I will provide any time.

# Answer
I can able to resolve this problem by creating game using 2d toolkit. But using default Unity 2d I can't able to get success.

Basically I understand the problem was, In Unity 2d, each displayed texture occupy size in graphical memory of device. If same sprite loaded 10 times then texture atlas created 10 times for the sprite.

Using 2d toolkit, single sprite collection created created so there was no problem of loading same atlas multiple time. Here I share my general experience then I got from working some hours.

If you have any suggestion then please share it also.

**EDIT:**

Hey friends, I found another solution to resolve flickering problem. I pasted here to help other members. **Sprite Packaging** helps me to overcome this issue in native Unity 2d game development. For this I don't use **2d Toolkit** as I suggested above.

I got nice help from following tutorial section. Unity 2D Tutorial: Getting Started

In this **Sprite Packaging** explained nicely. I think above information provide enough information to solve this problem.
> 1 votes

---
Tags: unity, scene
---


# Question
Title: How do I make a character capable of walking on walls?
I am trying to get a character to move like a spider: Given a rising slope which a ball would normally not be able to roll up, the spider would slowly crawl up.

Similarly, given a mid-air rectangular platform, instead of falling down when reaching the edge, the spider would continue, wrapping over the edge and continue down the side and then underside of the platform (eventually walking around the perimeter of the platform).

I've looked into various Unity 2D components, with little success. :(

Most of my world's collision boundaries are marked by Collider 2D components (which work great with a simple ball affected by gravity, but less so with this spider character).

# Answer
> 48 votes
I was about to post a link to the Asteroid Base blog on the Walker enemy when I noticed karmington already linked to the Gamasutra article in a comment (unfortunately, the images in that version are now broken, but the content is identical to the blog post above which still works as of 2024).

It's probably worth giving this a bit more visibility and explanation as an answer in its own right though.

The trick is raycasts. These let your code scan along a line for a collision.

To get the Walker to align nicely to surfaces, they fire two rays down at the terrain, one from the Walker's left side and one from its right (red and yellow lines above).

From each RaycastHit2D object, you can get a normal vector pointing perpendicular to the surface (magenta and green lines). By averaging the normals from the two hits, you get a suitable orientation for your character that's reasonably reflective of the underlying terrain (cyan line).

You can apply a force down along this orientation line to keep the character stuck to the terrain (though this may cause some sliding if the friction is low), or manually position the character at the average ray intersection point as is done with the Walker.

You'll want to blend the character's orientation gradually to keep your character from vibrating or looking robotic (see how the normal changes sharply when the Walker crosses the corner, but the body moves smoothly).

If you have sharp corners in your terrain, you'll probably want to angle these rays inward slightly - so that if the spider walks past the edge of a 90-degree cliff, the overhanging ray will hit the cliff face.

The Asteroid Base team also shoot a short ray in the direction of the Walker's motion (not shown), which overrides the ray on that side if it hits terrain. That ensures the walker doesn't get stuck when walking into a 90-degree concave corner.

According to the docs, the 2D raycast differs from the 3D one in that it detects colliders within which the ray starts. That sounds fishy to me, but if your testing confirms this you'll want to use a layerMask to limit the rays to only detect climbable terrain colliders.

# Answer
> 3 votes
You will need custom code for this.

Basically you need to know what the closest object is, like the platform in question, and then find the closest edge, and the closest point on that edge, and then work out the spider's position and rotation from there.

It won't be easy to make it really nice, but it should be a good challenge to get it working at all.

---
Tags: 2d, unity, physics, game-mechanics
---


# Question
Title: Load single texture atlas for multiple sprite
Recently, I am developing sudoku game. For this, I have created multiple grid 9x9,12x12 and 15x15.

For this numbers are repeated so multiple sprite renderer are created and it load same number texture multiple time.

So I want single number loaded single time only no repetition texture occur in graphical memory.

Because of this problem I am facing following problem that I already posted.

Android Device Screen Flicker

I want suggestions to overcome this problem from your side.

# Answer
> -1 votes
I think, I have found answer for this question also. In edit section of answer, I have posted answer of this question.

Android Device Screen Flicker

At present I am not marking it as correct because I want suggestion from other developers also. So please share your knowledge regarding this.

---
Tags: unity, sprites, rendering, texture-atlas
---


title: parsing normals from OBJ problem

text:
# Question
Title: parsing normals from OBJ problem
my attempt at loading obj and calculating normals per vertex is not working:

```
                getline(OBJfile, line);
                istringstream iss(line);
                iss >> x >> y >> z;
                vData[vertexIndex].position = D3DXVECTOR3(x, y, z);
                vertexIndex++;

                D3DXVECTOR3 curNormal;
                D3DXVec3Normalize(&curNormal, &vData[normalIndex].position);
                vData[normalIndex].normal = curNormal;
                normalIndex++;

```

so it seems to load the first face and thats it. i had it loading meshes fine until i added normals.. i wasnt sure how to bind normals per vertex so i created a structure:

```
struct VertexData
{
D3DXVECTOR3 position;
D3DXVECTOR3 normal;
};

```

then for the indices i made a structure like so:

```
struct FaceType
{
int vIndex1, vIndex2, vIndex3; //vertex index per vertex per face
int nIndex1, nIndex2, nIndex3; //normal index per vertex per face
};

```

and loaded filled it like:

```
if (c == 'f')
        {
            getline(OBJfile, line);

            istringstream iss(line);
            iss >> v1 >> v2 >> v3;
            faces[faceIndex].vIndex1 = v1 - 1;
            faces[faceIndex].vIndex2 = v2 - 1;
            faces[faceIndex].vIndex3 = v3 - 1;

            faces[faceIndex].nIndex1 = v1 - 1;
            faces[faceIndex].nIndex2 = v2 - 1;
            faces[faceIndex].nIndex3 = v3 - 1;
            faceIndex++;
        }

```

yet again i believe it is only drawing the first face it find because when i run it and try loading a cube from an obj file, i only get an extremly elongated triangle... please someone come through for me... ive been working on this for days now and would LOVE to moveon and fully understand this process

# Answer
you are making the classic obj to opengl mistake, each int in the index relates to all data of each vertex in the buffers

you will want to duplicate the data on reading and fill a singular buffer see the code my answer on SO
> 1 votes

---
Tags: c++, directx10
---


# Question
Title: Algorithm for randomly generating reachable platforms
I want to randomly generate reachable platforms on the fly for a 2D game. Right now, I am just creating platforms at random x,y positions. Only 4 platforms can exist at once, so once the 5th one is generated the 1st one is removed (fifo).

So, I want to ensure that the player can jump from his current platform to at least one other at any given time.

I was thinking of using some variant of the distance formula to calculate the location of the next platform being generated. I was hoping someone could help me out with the **formula** for calculating the next platforms possible x,y positions.

The player variables I am assuming will be important are speedX, speedY, and gravity.

From here, I should be able to calculate the maximum distance to plug into the distance formula.

However, I am thinking that some variation of the distance formula that contains a variable for slope would be better in my case.

I want to ensure that the player will never get stuck on a platform with no where it can jump. Also, I want to ensure that platforms aren't generated on top of each other.

Formulas/images/code are a huge plus.

Here is how jumping is currently working.

```
Field speedY:Float = 4
Field GRAVITY:Float = .05

Method Update:Void()
    If KeyDown(KEY_SPACE) And not jumping Then
        dy=-speedY
        jumping = true
    EndIf

    If jumping
        dy += GRAVITY
        local tempY:Float = y + dy
        y = tempy
    Endif
End Method

```

Edit: I now understand that the formula is just the displacement of basic projectile motion.

Except, in my case, we don't care about cos/sin because the angle will always be the same.

# Answer
New Answer: Lets look at the image. The player (represented by a circle) can jump to the left or to the right. What makes the difference is how much time passes since the moment the play jumps until the moments she lands on another platform.

If we randomize a direction, either `left` or `right` and a value for time `t` than we can place a platform in that direction in the correct position.

let:

```
g = Gravity
vx, vy = speedX, speedY
x, y = currentX, currentY // either on the left or the right side of the platform

```

The equation is:

```
ypos = (g * t^2) / 2 + vy * t + y
xpos = vx * t + x

```

Again, all you need to do is randomize a value for `t` and compute the new position. Remember that ought to keep it small enough so the new platform is within the screen.

Old Answer: The general idea is checking how much distance you can cover on `x`-axis before reaching a certain `y` altitude (on the way down) that is too low for the platform you want to jump onto.

First, anything within the `x0`, `x1` bounds of the platform the player is standing on is reachable if it is bellow maximal jump height. If you are using gravity as a simple acceleration downwards then the time it takes a player to reach the peak of his jump is:

`t = speedY / GRAVITY`

This means the player will reach:

`OrigY + t * speedY / 2` at her peak (where `OrigY` is the altitude you jump from). This also means you can have a shot at reaching any platform that is that high if it's `t * speedX` units away on x-axis.

To figure out the equation for lower platforms maximal distance on `x`-axis, you need to remeber you can cover about `t * speedX` by the time you reach your maximal jump height and then begin to fall (`GRAVITY` takes over). Reaching a certain `y` that is `delta` bellow your max height will take:

```
(gt'^2)/2 = delta
t'^2 = (2 * delta) / g
t' = sqrt(2 * delta / g)

```

So if a point is `delta` bellow max height, it can be reached if it is less than `(t + t') * speedX` units away. The equation is:

```
speedX * ((speedY / GRAVITY) + sqrt(2 * delta / GRAVITY))

```

This is of course a "best pixel perfect jump ever" approximation. You may want to give the player a better chance by reducing her `speedY` and `speedX` to 80% or 90% when you compute. Also, it does not take into consideration the possibility of blocking platforms.
> 5 votes

---
Tags: 2d, mathematics, physics, procedural-generation, platformer
---


# Question
Title: GL ARB Shadow Ambient Extension is not supported
I'm trying to build a game engine with LWJGL under Java. I'm want to implement Shadowmapping, but I'm stuck with the tutorials from Oskar Veehoek (here, specifcally). When I try to use the shadow mapping OpenGL extension, I get the error:

> GL ARB Shadow Ambient Extension is not supported

What might be the source of this problem?

# Answer
> 2 votes
Take a look at the shadow mapping tutorials at this site. Another great tutorial can be found here.

I managed to implement shadow mapping for my LWJGL game without using any extensions and using only these two tutorials. The code can be transferred to Java pretty easily.

As far as i know, if you are using C++, only OpenGL 1.1 is guaranteed. Anything else needs to be loaded manually from extensions. LWJGL does this for you. You can find the corresponding functions in the GL30 etc. namespaces.

# Answer
> 0 votes
From the comments by the OP, this was the problem:

> nVidia Graphicscrad do not love FBO so you have to revamp this part and the Problem is solved!

---
Tags: lwjgl, shadows, shadow-mapping
---


# Question
Title: RenderTexture is not cleared after it was released
I want to create some image effect. I've written a script that draws a cube mesh at the render target and then copies the render texture at the screen. I don't want to render **anything** except Mesh(M) in my RenderTexture(rt):

```
    void OnRenderImage(RenderTexture src, RenderTexture dest)
    {
        RenderTexture rt = RenderTexture.GetTemporary(Screen.width / 1, Screen.height / 1 );

        Graphics.SetRenderTarget(rt);
        Graphics.DrawMeshNow(M, new Vector3(0.0f, 0.0f, -8.0f), Quaternion.identity);
        Graphics.Blit(rt, dest);

        Graphics.SetRenderTarget(null);
        RenderTexture.ReleaseTemporary(rt);
    }

```

Where M is `GameObject.CreatePrimitive(PrimitiveType.Cube).GetComponent<MeshFilter>().sharedMesh;`

When I moved my camera, I see this:

It seems like the RenderTexture didn't cleared itself when released. Or maybe I did something wrong? Please explain why this happened and how can I fix this.

# Answer
That is correct: RenderTextures are not necessarily cleared after being released or reacquired.

According to the documentation:

> You can not depend on any particular contents of the RenderTexture you get from GetTemporary function. It might be garbage, or it might be cleared to some color, depending on the platform.

If you want the RenderTexture to be cleared, then you'll need to clear it yourself after acquiring it.
> 5 votes

---
Tags: unity, effect, rendertargets
---


# Question
Title: Path finding to collect enough items before the fight with the enemy
So I have the following problem : a X by Y grid. On the grid there is a character and a monster and some items that give bonus points to the character's damage if picked and holes that must be avoided. The goal is to collect enough items to be able to defeat the monster, then navigate to the monster and fight it.

What kind of algorithm can be used to solve this problem?

# Answer
> 1 votes
1. Do I have enough damage to defeat the monster? If yes, go to 4.
2. Pathfind to every item, and travel to & pick up the one with the shortest path.
3. Go to 1.
4. Pathfind to the monster and defeat it.
5. End.

As others have said in the comments, A\* is the obvious approach for performing the pathfinding itself.

---
Tags: path-finding
---


title: Tile map propagating fire

text:
# Question
Title: Tile map propagating fire
I have a Model(I use the MVC pattern), that holds an 2D Array with Tile objects.

A tile object have a member, whether it burns or not, a member how long it takes until the neighboring tiles get fire too and a member with the elapsed time how long the fire already burns on this tile.

My problem is, that my only solution is, to iterate threw all tiles and check whether the tile burns. If yes, count down the elapsed time. Than check, whether the maximum time is reached and set the fire member of the neighboring tiles to true.

In small maps it works, but in bigger maps not(Too many computing power). Whats the fastest way to filter the burning tiles out of the array, so I can do logic with them ?

A idea from me was to create a extra list that holds a reference to burning tiles, but that's difficult, because the list can be get out of sync with the array(Because the MVC pattern the array is public so it can be modified without to change the list with the fire tiles).

I have problems to implement this. So maybe someone can show me a code example. Here my current state: I have a class Tile:

```
public class Tile
{
    public static final int TILE_NORMAL = 0;

    private int type;
    private boolean burning;

    public Tile(int type)
    {
        this.type = type;

        burning = false;
    }

    public int getType()
    {
        return type;
    }
    public void setType(int type)
    {
        this.type = type;
    }

    public boolean getBurning()
    {
        return burning;
    }
    public void setBurning(boolean burning)
    {
        this.burning = burning;
    }
}

```

Than I have a class TileMap, too:

```
public class TileMap
{
    private Tile[][] tiles;

    public TileMap()
    {
            // That's only provisionally, later loading from a file
        tiles = new Tile[2][2];
        tiles[0] = new Tile[2];
        tiles[1] = new Tile[2];

        tiles[0][0] = new Tile(Tile.TILE_NORMAL);
        tiles[1][0] = new Tile(Tile.TILE_NORMAL);
        tiles[0][1] = new Tile(Tile.TILE_NORMAL);
        tiles[1][1] = new Tile(Tile.TILE_NORMAL);

        tiles[0][0].setBurning(true);
    }

    public Tile[][] getTiles()
    {
        return tiles;
    }
    public void setTiles(Tile[][] tiles)
    {
        this.tiles = tiles;
    }
}

```

This class(TileMap) is placed into another class named "World". The world class is the big Model that contains all other models like players enemies .... To render the world I have a world renderer, that has a reference to the world object and every time I call the render method from the renderer, the renderer take for example the tile map from the world reference and iterate threw all tiles to draw them.

At last, I have a tile map controller. This class have a reference to the world, too. Every time the update method from it is called it do the logic for all world objects/models.

So now back to the actual question. How would you implement the event queue for the fire and maybe for such things like that? I am sorry and thanks for the patience :)

# Answer
I have found that a list of burning tiles was an adequate solution. Here's how I solved the problem you mentioned, which was that list references can become stale:

Each item stored in the list is a reference to an object that is somehow "aware" of its own state. You accomplish this with your `Tile.getBurning()` method. This allows your `TileMap` to implement something like this:

```
private List<Tile> burningTiles;
public void BurnTileAt(int x, int y) {
  getTileAt(x, y).setBurning(true);
  burningTiles.add( getTileAt(x, y) );
}
public void UpdateBurningTiles(float delta) {
  for (int i = burningTiles.length - 1; i >= 0; i--;){
    Tile t = burningTiles.get(i);
    // check that the Tile still belongs in this list (external changes)
    if (t.getBurning()) {
      // contrived code scenario which priority queue would struggle to solve.  :)
      t.burnTime -= ( this.getRoomOxygen() * t.getBurnSpeed() * delta );
      if (t.burnTime <= 0) {
        t.IgniteNieghbors();
        t.setBurning(false); //on the next pass, it will be removed.
      }
    } else {
      burningTiles.remove(i);
    }
  }
}

```

This code would depend on a few extra properties in your Tile class:

```
// public class Tile { ...
public int x, y;  // a Tile knows its own position
public float burnTime;
public static final float TOTAL_BURN_TIME;
public float burnSpeed;
public TileMap tileMap; // a Tile knows its container

public void setBurning(boolean burning){
  this.burning = burning;
  this.burnTime = TOTAL_BURN_TIME;
}

public void IgniteNeighbors(){
  tiles.add(tileMap.getTileAt(x - 1, y)).setBurning(true);
  tiles.add(tileMap.getTileAt(x + 1, y)).setBurning(true);
  tiles.add(tileMap.getTileAt(x, y - 1)).setBurning(true);
  tiles.add(tileMap.getTileAt(x, y + 1)).setBurning(true);
}
// ...

```

This should solve your problem of large maps; only the burning tiles need burning updates. And by removing tiles that have already burned through their timer, you can (feasibly) keep the list short enough to update each frame.

Just for fun, here's my prototype in which I faced this problem:

---

Aside, about your TileMap. By doing this:

```
private Tile[][] tiles;
public Tile[][] getTiles() { return tiles; }
public void setTiles(Tile[][] tiles) { this.tiles = tiles; }

```

You are gaining no encapsulation whatsoever. This is a semi-famous programming style opinion. But the real problem is that all your other code will still be tightly bound to that 2d array structure, so you won't be able to change it. If instead, you did this:

```
public getTileAt(int x, int y) { return tiles[x][y]; }

```

...you would have freedom to change implementation later. Performance would probably suffer if you iterated every tile this way. But you could expose other methods to operate on large chunks of the data all at once.
> 2 votes

# Answer
1. You should create a priority queue binary heap to keep track of burning tiles. The priority here is determined by the amount of time left until the event of interest occurs, in this case from what you asked I presume that is the time when the neighbouring tiles will be set ablaze.
2. You shouldn't loop and decrease the delta from each of them. You should pre-calculate the time in which the tile will set neighbouring tiles on fire in advance and save that time as the tiles priority value.
3. You should check if that condition is met with the tile of the highest priority (the one of the top of the heap). If that time was reached you delete it (from the heap). Then check the new (best) tile with the highest priority.

This is much more computationally efficient. Also, like Byte56 said, you could store pointers to tiles or do whatever workaround is needed to avoid the issue you describe with modifying the array. Besides, the array shouldn't be public, it should only be accessed with accessors.
> 4 votes

# Answer
Have you considered using an array list adding the co-ordinates as you go

```
Firelist Firea = ...
Firelist Fireb = ...

List<Firelist> Fires = new ArrayList<Firelist>();
lines.add(Firea);
lines.add(Fireb);
...

```
> 0 votes

---
Tags: java, tilemap
---


title: TopDown 2d player control

text:
# Question
Title: TopDown 2d player control
Whats the usual way to control a player in a top down game? We have to look in the direction of the mouse cause the player hold a torch.

My first try was:

* to to make it absolute like W move to screen top, A left, D right, S bottom... But it feels a kind of strange.
* second try was to make it relative to the player. So W is always straight forward, A and D is moving sideway and S is backwards. But i heard of my tester thats very hard.

So whats the better / right way for the movement in a top down game in that you can move in a another direction as you look?

# Answer
> 2 votes
I think the decision boils down to how important it is to let the player travel in noncardinal directions, versus how much patience you require of your players. The first option (let's call it **absolute directions**) is a lot easier than the second option (let's call it **relative directions**).

Most games that have what you describe - top-down, aim in the mouse's direction - have opted the **absolute** scheme: Crimsonland and Teleglitch to name just two. The control is very easy to pick up but you may notice that not having look direction match up with the move directions is a bit unnatural. In Crimsonland's case, it didn't matter because the game takes place in an open field. Teleglitch is a bit more clever; it rotated the map as you moved to different rooms so that most of the times rooms extend in cardinal directions. If you do take this approach, I'd suggest the following:

* Use plenty of open spaces, or
* Lay out rooms/corridoors in cardinal directions i.e. East-West, North-South

There aren't many games that use the **relative** scheme with mouse-look; actually I know of none that have been released. I've once made a game that used this scheme, and yes my testing has also shown it's hard to get used to.

I remember a few games in the 90's that used a similar scheme though, except instead of aiming with a mouse, you steered using keys/buttons. The Strike series was a notable example. My experience with this was that it's difficult to get used to, again. The main problem is that if you are travelling South, left and right are flipped.

If you do take this approach, I'd definitely suggest easing the player into it. Try a series of levels that make more involved uses of this control scheme:

1. Start with Northerly directions only, i.e. the player is only moving up the screen
2. Gradually add in East/West directions
3. Finally, add a few Southerly directions

---
Tags: movement, mouse, keyboard
---


# Question
Title: Derive direction in which a spot light emites its light from a projection matrix
First of all, sorry if my question sounds too basic or even makes no sense. I'm new with game development

I'm working with HPL1Engine, specifically, the lights parts. I need to know the direction in which a spot light emits its light. But the class that represents a spot light, doesn't have any direction vector.

So, I've been reading about lights in 3D engines, and I've detected in the class some other properties that I consider important. Like a projection matrix and angles (FOV and aspect). I'm trying to focus on the projection matrix (here, how the engine calculates it), but I'm not sure if I'm wasting my time.

Again, my goal is to know the direction in which a spot light emits its light (a vector), but I just have this matrix, and many other properties I don't relate with the spot direction calculation.

How could I know this direction from which I have (what the class provides me)?

Many thanks in advance.

# Answer
> 1 votes
You need the view matrix of the class (looks like you can retrieve it via GetViewMatrix()). Take a vec4 that points in the "default direction" (0 0 -1 most likely), e.g. (0 0 -1 0) and multiply it by the view matrix. This should give you the direction of the spot light in the x y and z components of the vec4.

This is assuming, though, that the view matrix here actually does what I assume it does, which is to shift the coordinate system such that its new z axis through the origin lines up with the "middle ray" of the projection cone.

# Answer
> 1 votes
You should be able to get the direction from the **view** matrix. The view matrix contains the axes of the spot light: the first collumn contains the x-axis ("side" vector), the second collumn contains the y-axis ("up" vector), and the third collumn contains the z-axis ("forward" vector). So grab the x, y and z values from the third collumn, and there you go. Depending on the coordinate system, you may need to negate the value, as per **TravisG**'s answer.

---
Tags: matrix, vector, lighting
---


# Question
Title: Is ArrayLists so slow that it is doomed to kill performance in Unity?
I was reading Which Kind Of Array Or Collection Should I Use?

The document states to use list for the most performance.

> "...They are the fastest array in unity. For this reason, built-in arrays are the best choice if you need the fastest performance possible from your code (for example, if you're targeting iPhone)...performs significantly faster than ArrayList."

I am inclined to use list besides performance issues as well because...

But it got me to wonder, since everyone seems to favor to make a degrading statement about ArrayLists, is ArrayLists *that* horrible? If so why does it even exist? Is it more of trace of supposedly deprecated codes?

# Answer
> 5 votes
Yes, `ArrayLists` are slow (relative). `ArrayLists` were part of the .NET framework before .NET 2.0 was released. .NET 2.0 brought us generics which are better for 'generic' collections. More specifically, `ArrayLists`' `.Add` method accepts objects causing boxing, whereas, a `List<T>` takes a predetermined type.. therefore, increasing performance.

For all practical purposes, the functionality of `ArrayList` in the current .NET Framework is for backwards compatibility with project using .NET Framework 1.0 / 1.1.

---
Tags: unity, performance
---


# Question
Title: How should I go about protecting my script files?
I am working on a small multiplayer game with a whole bunch of scripting components.

I know I can't store my files in plaintext otherwise anyone would be able to change the functionality of core parts of the game.

What is the best way to go about preventing this sort of "hacking?"

Would it just be best to develop the program using the script files then just copy the files into strings that are hardcoded in the program?

# Answer
If you store the script files on the client, in any form where you can eventually read them on the client, you can't "protect" them. They will always be open to exploitation, even when hard-coded into the game's executable or "encrypted" (as they must be decrypted to run).

You can prevent casual exploration by packing the files in some non-obvious format, but that isn't security against hacking either.

To prevent players from exploiting by altering scripts (or any other data), you have avoid placing trust in the client. Store everything you *can* on the server, transmitting commands to the clients (for scripts; this is how scripts in Guild Wars 2 work, for example). What you can't do exclusively on the server, make sure to *verify* on the server at least.

If you are making a peer-to-peer game, this is harder. Typically you'll want to employ "gossip"-based verification, where every connected peer (or some subset at random thereof) verifies actions and the results are compared to ensure they agree. You usually need to tune the heuristics involved to get a good play experience.
> 3 votes

---
Tags: java, multiplayer, scripting, lua
---


# Question
Title: OpenGL Reconstructing Position from Depth
I know this has been asked a lot of time before but none of those answers fixed my problem. I try to implement deferred shading and to do so I need to reconstruct the world space position from the depth. (Having a position texture in the gbuffer would be a waste of data)

**The calculation works fine for rotationing the camera (-\> moving the mouse) but as soon as I move the camera (-\> pressing wasd) they get weird.**

GLSL:

```
vec4 screenSpacePosition = vec4(pass_Texture * 2.0 - 1.0, texture(gbuffer_texture[2],     pass_Texture).r, 1);
vec4 worldSpacePosition = invertedViewProjection  * screenSpacePosition;
vec3 finalPosition = worldSpacePosition.xyz / worldSpacePosition.w;

```

gbuffer\_texture\[2\] is the depth attachment of OpenGL. invertedViewProjection is the matrix I used to render the scene inverted on the CPU.

# Answer
> 4 votes
The result sampled from `gbuffer_texture[2]` will be in the \[0, 1\] range, but in OpenGL, NDC space ranges from -1 to 1 along all three axes. (This is different from D3D, where the NDC space ranges from 0 to 1 along the z axis.)

So, you need to multiply the depth result by 2 and subtract 1 to convert the range to \[-1, 1\], just as you're doing already for the xy components of `screenSpacePosition`. Then you'll have the proper NDC position, and you can apply the inverse view-projection matrix as you're doing.

FYI, there are more optimized ways to do this that don't require a full matrix multiply per pixel. However, it's a good idea to get things working in a simple way first (which you're doing) before attempting more optimized approaches. Some optimizations that can be done are discussed in Matt Pettineo's Position From Depth article.

---
Tags: opengl, depth-buffer, deferred-rendering
---


# Question
Title: How to change colors of texture in lwjgl?
I have the following texture:

The black pixels are characters, the background is transparent. How do I change the black pixels of the characters to another color? I use this texture as a bitmap for text rendering in lwjgl. For example, is there a way to change the black pixels to red? I looked to shaders, but I don't know how to use shaders and what they does. I would appreciate an example. I also looked at this page.

But I don't really understand how to do it. I will really vote up your answer.

# Answer
What you're asking is probably possible, but I think the easiest thing to do would be to just make another texture with the desired effects. Then, when the time comes to modify the text, just switch the texture. This can be modeled with:

```
void update()
{
    // do updating stuff above
    if (condition)
    {
        textTexture = // Get texture here
    }
}

void draw()
{
    textTexture.bind()
    gl.Begin(Quads)
    {
        // Do drawing stuff here
    }
}

```
> 0 votes

---
Tags: 3d, textures, shaders, lwjgl, text
---


# Question
Title: XNA - Prevent Holding of Mouse Button as Part of an Input Handler Game Component
I'm using C# XNA 4.0 Refresh.

I'm working to create an InputHandler Game Component for my XNA game to handle all of the keyboard and mouse input.

I used SixOfElevens RPG Game Tutorial (Here - http://xnagpa.net/xna4/rpgtutorials/xna4rpgtutorial1.pdf) to create the InputHandler.

Currently, as shown in the guide it can handle keyboard input and has methods for performing an action when a key is down, pressed, or released.

I added mouse input into this InputHandler so that it gets the current and previous state of the mouse.

My problem though is that I can't figure out how to make working methods to perform actions when a mouse button is down, released, or pressed.

For example: With the keyboard input here is the section that handles performing and action when a key is released after being pushed.

```
public static bool KeyReleased(Keys key)
    {
        return keyboardState.IsKeyUp(key) &&
            lastKeyboardState.IsKeyDown(key);
    }

```

I've tried every way I could think of or find to get a similar thing working with the mouse.

I've seen this posting ( http://www.techpowerup.com/forums/threads/sample-code-c-xna-mouse-control-tip.57633/ ) and while it checking the button presses its doing it right at the moment when the action is to be performed. I need a way to pass it through the InputHandler and return it like the keyboard example shown above. Otherwise I'll be stuck having my keyboard input handled neatly and my mouse inputs handled messily all over the place.

Anyone out there know of a way to implement this like I need?

# Answer
You don't need to pass anything into a method. Much like you did for the keyboard in SixOfEleven's tutorial you would create mousestate fields like :

```
    private static MouseState mouseState;
    private static MouseState lastMouseState;

```

you would then (after the mousestates were initialized properly) access methods specific to each button or action instead of using the enums provided like those provided for your keyboard.

For example, I have a method that checks if the right mouse button is down and returns true or false.

```
    public static bool RightButtonDown()
    {
        return mouseState.RightButton == ButtonState.Pressed;
    }

```

Released is:

```
    public static bool RightButtonReleased()
    {
        return mouseState.RightButton == ButtonState.Released &&
            lastMouseState.RightButton == ButtonState.Pressed;
    }

```

Hope that helps.
> 2 votes

---
Tags: xna, c#, input, mouse
---


# Question
Title: Java Scrolling 2d Block game - Optimise my code?
I have a 2d game where you look down from above and can scroll up, down, left and right using a viewport and a much bigger map.

I have been having trouble drawing a rectangle around the block under the cursor but finally cracked it more through luck than anything else but ended up with this code. Can you help me optimise it and simplify it?

```
int blockwidth=gridsize-2;

//Draw coloured blocks
for (int x=0;x<sizex;x++){
   int thex=-(int)locationx+(x*gridsize);
        for (int y=0;y<sizey;y++){
        int they=-(int)locationy+(y*gridsize);
        //if (thex>-blockwidth && thex<800){
            g.setColor(new Color( tiles[x][y][1]));
            g.fillRect(thex,they,blockwidth,blockwidth);
        //}
    }
 }

```

Especially this piece

```
//Cursor co-ords updated
cursorx=(int)locationx+(int)GameInput.mousex;
cursorx=(int)cursorx/gridsize;
cursorx=-(int)locationx+(cursorx*gridsize);

//Draw on screen cursor
        g.setColor(Color.yellow);
        g.drawRect(cursorx,cursory,blockwidth,blockwidth);

```

# Answer
You have three coordinate systems, all using x,y.

1. The grid/block coordinates. Each block is gridsize X gridsize pixels.
2. The world coordinates. These are grid coordinates multiplied by `gridsize`.
3. The screen coordinates. These are world coordinates minus the camera position `(locationx,locationy)`

You're asking how to tidy up the code. I think the way to start is to be use a naming convention so that you know for each x,y variable, which of these three coordinates you're using. For example, you have `thex = -(int)locationx+(x*gridsize)`. The `x` here is in *grid* coordinates, `locationx` is the camera position in *world* coordinates, and `thex` is in *screen* coordinates. When you multiply grid coordinates by `gridsize`, you get world coordinates, so `x*gridsize` in world coordinates. When you subtract the camera position from world coordinates, you get screen coordinates, so `thex` is in screen coordinates.

Consider renaming your `x, y` to `grid_x, grid_y` and your `thex, they` to `screen_x, screen_y` and your `locationx, locationy` to `camera_x, camera_y`.

The second piece of code, dealing with cursors, is similarly transforming coordinate systems. The mouse position is in *screen* coordinates. The first line is finding the *world* coordinates for the cursor. Since we know that world - camera = screen, it follows from algebra that world = screen + camera. And that's what your code does: it adds the camera (locationx,locationy) to the screen (mouse) to get world coordinates (cursor): `cursorx=(int)locationx+(int)GameInput.mousex`

The second line there is `cursorx=(int)cursorx/gridsize`. What does it do? It's taking the *world* coordinates from the previous line and converting it into *grid* coordinates. We know that grid coordinates multiplied by `gridsize` is world coordinates. Therefore world coordinates divided by `gridsize` produces grid coordinates.

The third line there is `cursorx=-(int)locationx+(cursorx*gridsize)`. You're taking the grid coordinates from the previous line and multiplying by `gridsize`, so that produces world coordinates. You then subtract the camera location, so that produces screen coordinates.

So my suggestion for those three lines of code is to be clear about which coordinate system it is:

```
cursorx_world = (int)locationx + (int)GameInput.mousex;
cursorx_grid = (int)cursorx_world / gridsize;
cursorx_screen = -(int)locationx + (cursorx_grid*gridsize);

```

To make it even clearer, you might consider using a Point class that lets you handle both x and y at once, so that you don't have to duplicate this code. You could write methods such as `toWorld` and `toScreen` to make it easier to read this kind of code.

Optimization of this part of the code is unlikely to make any difference. I'd strive for clarity over microoptimizations. (Also, I don't see a way to make those three lines much faster.)
> 0 votes

---
Tags: java, 2d
---


# Question
Title: Unity3d - Monitoring which script is bound to which gameobject
How can we see the bounded scripts to gameobjects ? In a large project, it's hard to keep up monitoring by clicking each game object to see bounded scripts

# Answer
> 2 votes
If you want to see all the objects that are using a specific script, there are a few ways you can do that.

* Iterate through all the game objects and return a list at will. You can find all the objects of a certain type with:

(Where `myComponent` is the type of component you're interested in:

```
myComponent[] myComponents = FindObjectsOfType(typeof(myComponent)) as myComponent[];
Debug.Log("myComponent is attached to the following game objects: ");
foreach (myComponent comp in myComponents) {
    Debug.Log(comp.gameObject.Name);
}

```
* Create a script registry. Create a static class that contains a dictionary of scripts and their objects. For example:

Code to attach to some kind of scene object:

```
public static Dictionary<string, List<GameObject>> gameObjectsByScript
    = new Dictionary<string, List<GameObject>>();

public void AddScript(string scriptName, GameObject gameObject) {

    if(!gameObjectsByScript.ContainsKey(scriptName))
        gameObjectsByScript.Add(scriptName, new List<GameObject>());

    gameObjectsByScript[scriptName].Add(gameObject);
}

public List<GameObject> GetGameObjectsForScript(string scriptName) {
    if(gameObjectsByScript.ContainsKey(scriptName))
        return gameObjectsByScript[scriptName];
    else
        return null;
}

```

Then, in all the script `Start` functions you can add:

```
ScriptList.AddScript(this.GetType().Name, this.gameObject);

```

How you display the results is up to your personal preference. Maybe you want to just list them in the debug window, or you want to draw boxes around them, or whatever.

# Answer
> 0 votes
You can also right-click on a script in the Project view, choose "Find References in Scene", and it will give you a list of all GameObjects that use that Script in the Hierarchy view.

---
Tags: unity, gameobject
---


# Question
Title: in an ECS framework why are components indexed via their name rather than an Enum?
I have been reading through a number of discussions on ECS framework and very often I see components being referred to via name rather than through a string object such as an `enum` or a `struct`.

I'm starting to build a test implementation myself and feel as though they should have a strong type rather than a string so that I can pick the component I am looking for from a list rather than 'guessing' with a string.

As an example you will often see:

```
Entity.GetComponent("Position");

```

rather than:

```
Entity.GetComponent(ComponentTypes.Position);

```

# Answer
> 2 votes
ECS are especially good at data driven development and not hard coded by the programmer, this is why you see the usage pattern of string identifiers (in addition to the problems of merging multiple sources using enums and not colliding spaces).

Maps are pretty fast unless you're running thousands of them per frame, in which case something else needs fixing. Some people use a pre-compile step that wraps the string ("Position") with an identifier that turns it into a CRC at compile time so it runs even faster.

You can keep up a reference window with all your component strings, if you want to build entities in code.

# Answer
> 2 votes
I think that's because you want that the ECS can be used in multiple projects and can always be extended. If you use an `enum` in an ECS library, the user cannot create his own components without changing the library itself.

# Answer
> 0 votes
If you don't want to use the string like this it's easy to avoid it.

```
const string POSITION = "position";

```

Then you can use the const identifier to refer to the entity instead of the string itself. This could help reduce the amount of typos. The reasons why you want strings have already been provided by @Patrick Hughes. Like mentioned Hashes are fast and the memory access is unlikely to cause performance issues. There are ways to boost performance but using enums is not going to contribute to that and is against the purpose of ECS.

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


title: What does a Mesh consist of?

text:
# Question
Title: What does a Mesh consist of?
I have seen various implementations of mesh loaders in a few open source game engines. But all of them behave meshes differently. Is there a general definition for a mesh that explains what meshes have, what a submesh is, skeletons etc. I still can not understand the difference between a 3d model and a 3d mesh.

# Answer
> 3 votes
The reason for this is that there's no difference in general.

* A most basic model or mesh consists of vertices only. Vertices by itself can use different formats and as such may contain different data, for example they could optionally include color data, texture coordinates, and normal vectors. They might as well include data for animations, e.g. weights for skeleton animation and the like.
* These can be connected by edges, although edges are typically not stored as such (unless there are some kind of lines to be drawn).
* Sets of three or more vertices are used to form polygons (or n-gons). What's possible really depends on the actual engine or how it interprets/converts this data if needed. The most simple approach will accept polygons only.
* It's also possible for a model to include a skeleton with bones, but those might be stored in external files as well (e.g. to be shared between mutliple models).
* Submeshes are a technique to essentially store more than one mesh in one actual file or model/mesh. For example, a mesh could actually contain two sub meshes: One is visible, while the other is used for simplified collision detection (won't need as many details). Another possible use for this would be a navigation mesh that's not visible but used by bots for orientation.

In the end, there's no "best" approach or complete list. It always depends on your actual needs, which is also the reason for all those games using different formats, implementations or interpretations. For example, if you don't need skeletal animations, don't even worry about implementing skeletal animations. If you don't need submeshes, don't even think about them.

# Answer
> 2 votes
Might be wrong but here's my idea of what is what.

There are two things here: the general, most basic meaning and the concrete implementation. The most basic meaning should be the same in every game/graphics engine but there's a multitude of possible implementations.

A mesh is a set of vertices that create a shape of a model. They're either ordered in an array or by a set of indices in a specific topology so that a graphics card "knows" how to render them.

But the definition of a vertex is closely connected to the shader (concrete implementation) and may vary hugely. It can be as just the bare vertex position, it can be position, texture coordinate and normal (most common one, I guess) but it can be more complex: position, tex coord, second tex coord, normal, tangent, bitangent, vertex color and some arbitrary parameter that a user made up.

Also, a Mesh class in a game engine may have lots of convenience functionalities to handle/render/update/etc... the mesh as well as some additional data.

A model, in my understanding, is a whole renderable object that consists of a mesh, material (shader), optional animations, bones and other things. Again - the basic meaning is the same but there are multiple possible implementations that hugely depend on the concrete engine and intended usage.

---
Tags: 3d, models, mesh
---


# Question
Title: Efficient way to check collision with potentially hundreds of objects
I am trying to make a top down shooter that could potentially have hundreds of objects at once at one point. I need to check collision with projectiles, walls, and enemies. I am currently using ArrayLists which probably won't suffice later on and was wondering if someone had a good method or knows a good method for checking all of those objects at once. This is going to be a game for smartphones and is built in java. Any ideas would be great or if you could point me in some direction that would be fantastic.

Thanks in advance!

# Answer
When I've got huge worlds where enemies can move freely, I tend to create and 2D-array representing e. g. 8x8 tile chunks (I've you're not using tiles, than just take the base unit) and whenever enything is moving, I put a pointer to that object into the specific part of the array the moving thing has been moved into. When doing collusion, I simply do the collusion for object A, I just check intersection with all the other objects in the specific cell of the array and eventually the adjected ones, too.
> 1 votes

# Answer
Using chunks like user2241553 suggested is a valid approach. But when you have some algorithm skill, you might want to store any immovable objects in a 2d-tree. A 2d-tree is a binary tree where nodes with even depth are sorted by x-coordinate and nodes with odd depth by y-coordinate. Searching for objects in such a tree which are inside a specific area takes only logarithmic time.

2d trees don't perform that well for objects which move, because whenever an object changes its position it needs to be removed and re-inserted.
> 0 votes

---
Tags: java, libgdx, memory-efficiency
---


# Question
Title: Is this the correct way to detect ray-sphere intersection?
I have this java function that should return a true or false for any sphere passed to it if they intersect. However it seems to end being true a lot of the time when it shouldn't and false sometimes when it should be true.

It is possible however that i am passing incorrect data to the function. This was done with jPCT so the object SimpleVector is a vector with 3 variables.

```
public Boolean sphereIntersect(SimpleVector rayOrigin,SimpleVector rayDirection, SimpleVector sphereOrigin, float sphereRadius )
{
        SimpleVector Q = new SimpleVector(sphereOrigin);
        Q.sub(rayOrigin);

          float c = sphereOrigin.length();
          float v = Q.calcDot(rayDirection);
          float d = sphereRadius*sphereRadius - (c*c - v*v);

          if (d < 0.0){
              System.out.println("False");
          return false;
          }
          System.out.println("True");
          return true;

}

```

# Answer
Replace

```
float c = sphereOrigin.length();

```

with

```
float c = Q.length();

```
> 2 votes

---
Tags: java, android, raycasting, intersection
---


title: Collision Detection in a big map?

text:
# Question
Title: Collision Detection in a big map?
So I've been wondering lately... on games like pokemon (on ds and gba), How did they handle the collision of all those tiles in the map? Should all those collision checks running in the background slow down the game? Do they have it where the collision activates from a certain distance? Do they have a player event where the player is next to a tile that is not able to be walked on? If it is not possible to know the answer, could you give me a solution to that problem?

I guess what I am really asking is how to handle collision of almost every tile in a big map.

# Answer
> 3 votes
Well, in most handheld Pokemon games, moving objects can only move within a grid. So, each character can only occupy tiles in the grid, and they cannot rest between tiles. If there's an occupied tile where something wants to move, then it will simply not move to that tile in the grid. Collision checks only need to occur when something moves.

In a game where objects are not locked to a grid like this. I'd imagine that they'd only check for collisions with tiles that are onscreen, and maybe even only with tiles close to the moving object.

# Answer
> 0 votes
To detect collision against any possible tiles/obstacles, you first calculate the object's desired movement and where position on the tile map that movement would cause the object to end up if immediately applied.

You then perform a lookup of the tile map (generally via a 2D array representation) of the object's desired position along the x and y axes, and obtain the tile information. If it's a collidable tile, you alter the desired movement appropriately to prevent moving.

To summarize, you essentially look ahead to the position the object wants to move in, and determine if it can move there or not.

This excellent article by Rodrigo Monteiro goes into great depth on how to implement 2d platformers, but can be adjusted for top-down games as well. http://higherorderfun.com/blog/2012/05/20/the-guide-to-implementing-2d-platformers/

# Answer
> 0 votes
As for many things within game programming you only calculate what you need to calculate and discard the rest. For collision detection on a tilebased game it is as simple as just checking the tile you or any entity wants to move too, if that tile has a blocking flag you disallow moving to that location.

It is likewise for the tiles you see on screen, only those that you visually see will get calculated and rendered the others will be discarded. You would not load the gameover screen until it is needed right?

Same goes for NPC's, if they do not need to move outside the screen then do not calculate that, if you do want some variation off screen you just calculate a couple of tiles outside the screen.

The same rules apply for modern (FPS) games, you put many parts of a level inside invisible blocks, if you cannot see that block from your current location and angle you do not render it. Only if the player is within a block you need collision detection on the objects within that same block, first you check the collision with a simple cube or sphere around the player and if something hits that boundary you go check for mesh/object collision which is very expensive.

---
Tags: collision-detection
---


# Question
Title: HTML5 Quintus button click doesn't work in local
If you try to run this example http://html5quintus.com/docs/ui.html, you'll be able to click the buttons, but you won't if you download a local copy of the example and click the index file (without using a web server).

I know I need to run the code in a web server and not by just double clicking on the files when I have a .json file, but I can't understand the reason why also the click doesn't work (it does not require resource loading).

Maybe there's a simple modify I can apply to the example code or to the libs to make it work... Any suggestion? Thank you!

EDIT

I don't see any JS error:

# Answer
I found the problem. The example in http://html5quintus.com/docs/ui.html relies on a previous version of the engine. With the newer (the one you can download from gitHub) it doesn't work... To fix the example look at this issue segnalation: https://github.com/cykod/Quintus/issues/102.
> 0 votes

# Answer
Please use Developer Tools in your favourite browser to diagnose your problems.

In this particular example, file tries to load JS files, as well as images, and if image wont be loaded it will throw an exception:

```
Uncaught Error Loading: enemy.png quintus.js:1782

```

Which stops JS execution, that is why nothing is coming up. But if you use Web Server with all media it requires - it will be fine.
> 0 votes

---
Tags: html5, quintus-engine
---


title: OpenGL ES object rotation around z axis

text:
# Question
Title: OpenGL ES object rotation around z axis
I have an object on my screen which is presented rotated and panned, But i have 2 problems regarding the z axis rotations. It's a bit tricky to explain so i uploaded 2 videos to describe each problem.

1) Reverse rotation : After rotating the object around the x axis, the z rotations are being reversed and not as it should be.

2) Wrong Z axis rotation : Again, After rotating the object around the x axis, i'm trying to rotate the object around the z axis and the rotation results in a different axis rotations.

I do believe the video's describe the problems well.

**EDIT: Second attempt**

As kindly explained by the user @Fault, i understood the problems i was facing with. So i tried to solve those by just rotating the projection matrix around the z axis, which seemed to be working, but it doesn't.

Since i am rotating the model's axis, I get this **problem (video)**. the issue appears in the 23'd seconds, while i'm demonstrating how it works. As can been seen, when the z rotation causes a wrong x and y rotations.

I do understand that i must likely have to move these rotations to world view and not model view, the thing is i'm not really sure how to do that.

Here is the relevant code:

Render function:

```
{
...

    CC3GLMatrix *projection = [CC3GLMatrix matrix];
    float h = 4.0f * self.frame.size.height / self.frame.size.width;
    [projection populateFromFrustumLeft:-2 andRight:2 andBottom:-h/2 andTop:h/2 andNear:4 andFar:100];
    [projection rotateByZ:zRotationEnd];
    glUniformMatrix4fv(_projectionUniform, 1, 0, projection.glMatrix);

    [modelView populateFromTranslation:_currentPan];
    [modelView rotateBy:_currentRotation];

    glUniformMatrix4fv(_modelViewUniform, 1, 0, modelView.glMatrix);
...
}

```

X and Y rotations:

```
- (void) rotateAroundX:(float) x andY:(float) y newRotate:(BOOL) isNewRotate
{
    if (isNewRotate) {
        rotationStart = CC3VectorMake(0.0, 0.0, 0.0);
    }

    int rotationDirection = ceil(zRotationEnd/90);
    if (rotationDirection % 4 == 2 || rotationDirection % 4 == 3) {
        rotationEnd.x = rotationEnd.x - (x-rotationStart.x);
        rotationEnd.y = rotationEnd.y - (y-rotationStart.y);
    } else {
        rotationEnd.x = rotationEnd.x + (x-rotationStart.x);
        rotationEnd.y = rotationEnd.y + (y-rotationStart.y);
    }

    rotationStart.x = x;
    rotationStart.y = y;
    _currentRotation = CC3VectorMake(rotationEnd.y, rotationEnd.x, 0);
    NSLog(@"Current x is: %f y is: %f z is: %f",_currentRotation.x,_currentRotation.y,zRotationEnd);

}

```

Z rotations:

```
- (void) rotateAroundZ:(float) z newRotate:(BOOL) isNewRotate
{
    if (isNewRotate) {
        zRotationStart = 0;
    }
    zRotationEnd = zRotationEnd - (z - zRotationStart);
    zRotationStart = z;
}

```

And the vertex shader:

```
attribute vec4 Position;
attribute vec4 SourceColor;

varying vec4 DestinationColor;

uniform mat4 Projection;
uniform mat4 Modelview;

attribute vec2 TexCoordIn;
varying vec2 TexCoordOut;

void main(void) {
    DestinationColor = SourceColor;
    gl_Position = Projection * Modelview * Position;
    TexCoordOut = TexCoordIn;
}

```

I would really like to get this right, so any help will be appreciated.

Cheers!

# Answer
Since you have already solved the first problem, I will only address the second problem

The code you have does not really show where you generate the model, view & projection matrices, so it is difficult to exactly pin-point the problem position for you

You should maintain separate View & Projection matrices. If you use a library such as glm, which is fully compatible with iOS, you can easily calculate your view matrix

```
glm::vec3 cameraPosition = glm::vec3(cam_x_position, cam_y_position, cam_z_position);
glm::vec3 cameraTarget = glm::vec3(cam_x_target, cam_y_target, cam_z_target);
glm::vec3 cameraUp = glm::vec3(0,0,1);
glm::vec3 cameraDirection = glm::normalize(cameraPosition-cameraTarget);
glm::vec3 cameraRight = glm::cross(cameraDirection, cameraUp);
glm::mat4 view_matrix = glm::lookAt(cameraPosition, cameraTarget, cameraUp);

```

and your projection matrix

```
float lens_angle = 45.0f;
float aspect_ratio = 1.0 * (window_width / window_height);
float near_clipping_plane = 0.1f;
float far_clipping_plane = 100.0f;
glm::mat4 projection_matrix = glm::perspective(lens_angle, aspect_ratio, near_clipping_plane, far_clipping_plane);

```

PS: GLM is also Opensource, so if you want to take a look at how it is implemented and do it yourself, you can definitely do so

When you have your view & projection matrices (which are indifferent for your entire world) the thing you want to be modifying per each model is, as you'd expect, the model matrix

```
glm::mat4 Entity::getPositionMatrix() {
    return glm::translate(glm::mat4(1.0f), position);
}

glm::mat4 Entity::getRotationMatrix() {
  glm::mat4 rotation_x = glm::rotate(glm::mat4(1.0f), x_angle, glm::vec3(1.0f, 0.0f, 0.0f));
  glm::mat4 rotation_y = glm::rotate(glm::mat4(1.0f), y_angle, glm::vec3(0.0f, 1.0f, 0.0f));
  glm::mat4 rotation_z = glm::rotate(glm::mat4(1.0f), z_angle, glm::vec3(0.0f, 0.0f, 1.0f));
  glm::mat4 rotation = rotation_x * rotation_y * rotation_z;
  return rotation;
}

glm::mat4 Entity::getModelMatrix() {
    return getPositionMatrix() * getRotationMatrix();
}

```

And then simply pass in the model matrix (along with view & projection matrices) to the vertex shader, and you can do the multiplication there (bonus speed boost for multiplying on the GPU might occur)

```
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

....

//in shader body
mat4 mvp = projection * view * model;
gl_Position = mvp * vec4(vertex_position, 1.0);

```

This way, you will update your x, y & z angle rotations (around their respective axes) in as you'd expect them in the model space (If I understand correctly, feeding them in from the pan / rotation gesture values), and the matrix calculation / multiplication will handle the translation for you

Hope this helps

If you wanna take a more full look at this code in action, you can checkout a small sandbox I'm building (for other purposes really) that has this code in action
> 1 votes

---
Tags: opengl, opengl-es, cocos2d-iphone, rotation, cocos3d
---


# Question
Title: How can I add and subtract convex polygons?
I have two 2D convex polygons **overlapping each other**. I am looking for an algorithm to **subtract** and **add** them. The result must be a single concave polygon or (even better) a set of biggest convex ones forming the concave result (e.g. triangles).

(**Left:** The initial overlapping polygons. **Middle:** The resulting concave polygon after adding. **Right:** A set of convex polygons forming the concave result. Here it would be better to get convex polygons bigger than a triangle for performance reasons. An subtraction of the two overlapping polygons would lead to the same picture as on the left but with the overlapping area not being part of the resulting polygon.)

How can I do this?

# Answer
TL;DR You need to implement boolean operations using BSP trees.

Well, it seems we are talking about Constructive Solid Geometry here. I have implemented CSG on a commercial level so I know a thing or two about it.

The classic paper about CSG is called Merging BSP Trees Yields Polyhedral Set Operations, to be honest it's too much to explain here, but briefly speaking the algorithm deals with polygon(s) that lay on the same plane as a binary space partitioning, basically constructing a BSP tree from each polygonal mesh. The second step is to merge those BSP trees; you simply take one tree and insert it into the other. The algorithm then proceeds to explain how to deal with each leaf node for dividing and substracting the nodes, nodes that are not needed in the final shape will be removed, others will be given the appropriate parent.

**But wait!** That paper is basically speaking about polygonal meshes and 3D planes, NO?

The algorithm can be generalized into any dimension, so in your 2D case it's easy to use line segments instead of plane as the binary partitions. So each polygon will be converted into a BSP tree than the two will be merged. Finally you traverse the resulting tree to generate the final polygon,

Note that this algorithm and CSG in general doesn't deal with rendering and mesh faces directly and isn't really rendering ready, so you need to extract the faces of the final BSP trees. I also find ray tracing an easier approach for rendering the CSG result, you only need the rays to traverse the tree instead of extracting and actually *splitting* the faces (remember we only deal with binary partitions).

Regarding numerical robustness. It's good to note that there are two types of geometric computations,

* Those that are based on construction, you **construct** a shape based on the result of a previous operation. For example `y = sqrt(x)` and then use `y` in a new operation. This is called construction; the problem is that numerical errors will accumulate quickly.
* Alternatively there are **operations that use predicates** instead, essentially instead of using construction you simply ask whether a condition is true/false and use the same value in different operation. Classic tests include incircle and the orientation test; this is also suspect to numerical errors especially if you use single or double precision but will usually give a much better results. other solutions that vary on speed and accuracy exist. Here is one of the recent papers that avoid construction by using a plane based geometry to give accurate results. I will also quote from the paper:

> The concept of plane-based representation of polygonal meshes was first described by Sugihara and Iri \[SI89\]. This kind of representation provides one important advantage when it comes to tasks that involve changing the topology of solids represented by meshes like the evaluation of Boolean expressions: no new primary geometry information has to be constructed to obtain the resulting polyhedron

And finally I would like to add, if you like to start your BSP CSG implementation I would recommend starting on BSP Faqs.
> 9 votes

# Answer
Going by your example:

Pick a starting vertex on polygon A, and then start checking for intersecting edges clockwise (or counterclockwise). If there isn't an intersection, add the previous vertex to your resulting polygon. If there is an intersection, add the point at which they intersected to your resulting polygon, and then start iterating over polygon B, in the same winding order. Do the same thing, again swapping to polygon A if an intersection occurs.

Once you've accumulated all the vertices for the new polygon, perform a triangulation algorithm on it. The ear clipping method is easy to implement, but there are faster options out there.

Important: ensure the vertex you start at isn't inside the other polygon (check this article for point in polygon tests).

Iterating over each edge, to check for an intersection would be an O(n^2) algorithm. You could speed it up by first finding the vertices that are inside the other polygon, as the edges linked to those vertices will be the intersecting ones.
> 1 votes

# Answer
If you want a **concave** polygon, just pick the closest edge between the two input polygons, and add two new edges:

**Convex** gets slightly more complicated:

One approach is iterative in that it adds vertices from the second polygon to the first, one at a time, evolving the first polygon into a container that encompasses everything.

Basically:

* Iterate through the second polygon's vertices.
* For each vertex V, iterate through the first polygon's edges:
* Find a "range" of edges that all **face** the vertex
* take the outer pair of vertices that define that range, and remove all edges in the range that connects them
* Draw two new segments from those outer vertices to the new vertex (from the second polygon), making sure that the new edges face the correct direction.
* Proceed to the next vertex from the second polygon

Here's a diagram illustrating the process for the first vertex:

A faster method is to find the list of edges on each polygon that do not face the other polygon, remove everything else, and connect the endpoints of the remaining line strips to each other.

Perhaps someone else can chime in with some subtraction advice.
> 0 votes

---
Tags: algorithm
---


# Question
Title: How can I apply an outline effect in Unity?
I want to apply an outline effect for several objects on the scene. Nope, the standard outline shader from the toon-shader package don't met my criteria. I want to create an effect like this:

To implement this effect I want to:

1) Render all my selected objects into a texture, taking the depth into attention. So if my selected object is occluded by another objects it must be displayed in my render texture, like this:

2) Render the scene.

3) Blur my render texture and then copy all non-null (null is empty scene) and non-one (1 is the object itself) to the screen to make it look like this:

So, I have the question: How can I render the separate objects to the texture, taking care about occluders (depth)? Yep, I know about `Graphics.SetRenderTarget` `Graphics.DrawMeshNow`, but I also need to take care about the depth, because without it, it will look like this: Please help, I feel stuck.

# Answer
> 3 votes
The Unity team published a nice slide deck at SIGGRAPH 2011 with a whole palette of special effects that can be achieved with depth. These are low-cost when using deferred rendering, but still available when using forward rendering at the cost of a pass to create the depth texture.

Their outline effect is described on slides 46-47, and should be possible to adapt to your needs.

Instead of the Sobel Filter on depth as they suggest, just read the depth buffer at the current fragment position. If it agrees with the depth of the fragment you're rendering (within a rounding tolerance), it's your object, so output 1. If it's substantially closer, it's an occluder, so output 0. (You can also choose to output 1 only for fragments adjacent to the edges, leaving the interior 0 if you prefer)

After that, you can continue with the approach you've described above.

---
Tags: unity, rendering, effect
---


# Question
Title: ECS how to access multiple components (not the same one) in a system?
I'm implementing a basic entity component system from http://entity-systems.wikidot.com/rdbms-with-code-in-systems#java in C++, but I don't quite understand how I could do multiple components (not the same component. I don't see a need to have 2 of the same components yet) in a system. In an inherited System, for example, MovementSystem, I want it to be able to act on all entities that have a position component and a velocity component. However, in my code, I would do

```
std::vector<Component *> positionComps = entityManager->GetAllComponentsOfType(POSITION_COMPONENT);
std::vector<Component *>::iterator it = components.begin();
for (; it != positionComps; it++) {
    PositionComponent *pos = dynamic_cast<PositionComponent *>(it);
    pos->x += velo->x;
}

```

I don't know how I could get the velocity component in there, as it is looping through the position components. I could get all of components of type velocity inside that loop and have a nested loop, but that would be bad on the performance. Also, how would you know which component goes with which? There is a function of GetAllEntitiesPossessingComponent which returns a list of integers so I can later then get the specific component of the entity and check if the entity has the two components. Also, if the component returned was NULL, I would have to check in the system before I do anything if it's NULL or not. But all of this doesn't seem right.

I COULD merge PositionComponent and VelocityComponent into one and then act on that in the system, but that wouldn't help me with future components.

# Answer
You need to iterate on entities, not components. Each system maintains a list of all the entities that have *all* the components that system needs to do its thing. In your example, the system is your MovementSystem. The MovementSystem maintains a list of all the entities that have a Position and Velocity component. Then, when it's time to work, it just iterates on those entities. For each iteration it will fetch the Position and Velocity components from the entity, and use those in its calculation. See here for more details.

It's easy to maintain a list if you have your systems notified when an entity has a component added or removed. They can just check their bit mask against the entity mask. If you don't want to maintain a list, you need to make a `GetAllEntitiesPossessingComponents` that takes a bit mask defining the components to retrieve.
> 1 votes

---
Tags: c++, entity-system
---


# Question
Title: How to play a video on a TV model inside a game?
I am new to Unity3D. I need to know how can I play news when I switch on a TV using any scripting language in Unity3D ?

# Answer
If you want to play a video on the TV screen, you would use Movie Texture (just have it render on a game object that you set active to true or false whenever a button is pressed. Keep in mind that Movie Texture is a Pro Only feature.

If you want to simply animate a set of sprites, the Animated Texture solution Arthur Wulf White proposed is the way to go.
> 1 votes

---
Tags: c#, unity, javascript, unityscript
---


# Question
Title: C# XNA - How to create a menu with bools and textures?
I thought I could use `bools` to be able to select options in my menu. But the options should be textures. To show that an optino is selected I have 2 textures like this:

```
[----Menu Screen----]
 [  >  Option1  <  ] Option1 = Start Game
 [     Option2     ] Option2 = Options
 [     Option3     ] Option3 = Exit
[----Menu Screen----]

```

So the `>` and `<` are the textures I'm using to show the user that he has selected an option. I have the following code:

```
enum gameStates
{
    gameLoading,
    mainMenu,
    gameOptions,
    levelSelect,
    gamePlaying,
    gameOver,
}
gameStates CurrentGameState = gameStates.gameLoading;

```

And maybe using `bools` like this may work?

```
// gameStates.mainMenu bools
bool startGameSelected = true;
bool optionsSelected = false;
bool exitSelected = false;

```

`Update()` method:

```
    switch (CurrentGameState)
        {
    // gameStates.gameLoading here...

    // gameStates.mainMenu:
            case gameStates.mainMenu:
if (startGameSelected)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                        {
                            CurrentGameState = gameStates.levelSelect;
                        }
                    }
                    if (optionsSelected)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                        {
                            CurrentGameState = gameStates.gameOptions;
                        }
                    }
                    if (exitSelected)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                        {
                            this.Exit();
                        }
                    }
                    if (startGameSelected)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Up))
                        {
                        exitSelected = true;
                        optionsSelected = false;
                        startGameSelected = false;
                        }

                        if (Keyboard.GetState().IsKeyDown(Keys.Down))
                        {
                        startGameSelected = false;
                        exitSelected = false;
                        optionsSelected = true;
                        }
                    }
                    if (optionsSelected)
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Up))
                        {
                            startGameSelected = true;
                            exitSelected = false;
                            optionsSelected = false;
                        }
                        if (Keyboard.GetState().IsKeyDown(Keys.Down))
                        {
                            exitSelected = true;
                            optionsSelected = false;
                            startGameSelected = false;
                        }
                    }
                    if (exitSelected)
                    {
                       if (Keyboard.GetState().IsKeyDown(Keys.Up))
                       {
                           optionsSelected = true;
                           exitSelected = false;
                           startGameSelected = false;
                       }
                        if (Keyboard.GetState().IsKeyDown(Keys.Down))
                        {
                            startGameSelected = true;
                            exitSelected = false;
                            optionsSelected = false;
                        }
                    }

```

`Draw()` method:

```
switch (CurrentGameState)
        {
    // gameStates.gameLoading here...

    // gameStates.mainMenu:
            case gameStates.mainMenu:
    // Draw the startGame button
         spriteBatch.Draw(startGameTexture, startGamePosition, Color.White);
                // Draw the exitGame button
         spriteBatch.Draw(exitGameTexture, exitGamePosition, Color.White);
                // Draw the gameOptions button
         spriteBatch.Draw(gameOptinonsTexture, gameOptionsPosition, Color.White);
                // Draw the ">" and "<" arrows
         if (startGameSelected)
         {
             spriteBatch.Draw(redArrowTexture, new Vector2(280, 320), Color.White);
             spriteBatch.Draw(greenArrowTexture, new Vector2(484, 320), Color.White);
         }

```

But for some strange reason it seems this won't work any suggestions?

# Answer
Given that only one item can be selected at a time, it would be better to store the index of the selected item (possibly as an `enum`, for clarity - you can cast between an enumeration and an `int`), rather than using a mess of Booleans.

That way you can:

* Move through the menu with `++` and `--`
* Detect that the selected item has gone out of range, use the `%` operator to implement wrapping
* Use a `select` statement to select an appropriate action to take when activating the selected menu item
* Use a single `Draw` statement to draw your selection cursor textures, use simple maths to calculate their position based on which item is selected
> 1 votes

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


# Question
Title: Play video from StreamingAssets folder in Windows Media Player?(Unity 3D)
I can play video which is there in my StreamingAssets folder. But is there a way in which I click a button and the same video gets played in the Windows Media Player. I researched a lot on this but could not find any solution.

This is the code for playing video normally,

```
   using UnityEngine;
using System.Collections;

public class VideoDemo : MonoBehaviour
{

public string filePath;
public string result;

void Start() {
    filePath = System.IO.Path.Combine (Application.streamingAssetsPath, "Demo.mp4");
    result = "";

}

void OnGUI() {
if(GUI.Button(new Rect(10,10,100,30),"Click Me"))
    {
        StartCoroutine(Example());
    }
}

IEnumerator Example ()
{
    if (filePath.Contains ("://")) {
        WWW www = new WWW (filePath);
        yield return www;
        result = www.text;

    } else
    {
        result = System.IO.File.ReadAllText (filePath);

    }
}

  }

```

Kindly share some ideas.

# Answer
> 1 votes
If you want to simply let windows open the default program for a file, this should do:

```
System.Diagnostics.Process.Start(@"file path");

```

If you want more control over what program opens and what arguments are passed, you can use this:

```
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Program Files\... path to windows media player";
proc.StartInfo.Arguments = "\"" + file_name + "\"";
proc.Start();

```

---
Tags: unity, windows, video
---


title: Rotating image around a given point

text:
# Question
Title: Rotating image around a given point
Im trying to simulate shadows in a 2d RPG, So far I can make the shadows but i cant blit them properly, Im trying to rotate them according to where the "sun" is (just a position)

I have looked at other questions, they say to move the center of the image to the point rotate it then move it back so that what I'm trying to do

here is my code to rotate it:

```
def rotate(self, shadow, rect):
    copy = rect.copy() #get copy of rect
    angle = degrees(atan2(self.center[0]-self.sun[0], self.center[1]-self.sun[1]))-180 #get angle from "sun" to center of screen

    if angle < -180:
        angle += 360

    angle /= -5

    rect.center = copy.midbottom #move rect to rotation point
    shadow = rotate(shadow, -15) #rotate -15 as a test
    rect.center = copy.center # move it back

    return shadow, rect #return the image and rect to blit them

```

when the angle is negative it seem like its working and I get this result (which isnt really what I want):

but when I rotate it positively:

so I think I'm doing this totally wrong! I've been trying to figure it out for awhile now, I think I'm blitting it wrong, or not at the right state

# Answer
> 1 votes
I don't know pygame and how blitting works there but it seems that you translate `rect` but rotate `shadow`. Are you sure that's right?

Also, for this kind of effect I'd use a shear transformation rather than a rotation.

---
Tags: mathematics, rotation, rpg, pygame
---


# Question
Title: Blending semi-transparent images while not stacking their alphas
In libgdx/OpenGL ES I want to render multiple semitransparent textures while keeping the alpha still semi transparent. For example If I render a 0.5 alpha circle on top of another 0.5 alpha circle, alpha should remain 0.5, output alpha should be maximum value of input alpha and destination alpha.

I looked a bit, it looks like `glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX)` should do the trick, but it is not GL\_MAX operator is not available for OpenGL ES. Weirdly, it works when I use integer value for (0x8008) but I guess I can't trust that :D

How can I achieve such an effect?

# Answer
I believe GL\_ONE\_MINUS\_SRC\_ALPHA is what you are looking for.

If you are using a SpriteBatch you can enable blending like this:

```
batch.enableBlending();
batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

```

Otherwise you can call the OpenGL functions directly:

```
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

```
> 1 votes

# Answer
Depending on the device(s) you are targeting, you may be able to use `GL_MAX`. It is defined in the gl2ext.h header file. You should check that the device supports the extension called `GL_EXT_blend_minmax` (it sounds like the device you are using does support it).
> 1 votes

---
Tags: opengl, libgdx, alpha-blending
---