# Question
Title: Problem Implementing Texture on Libgdx Mesh of Randomized Terrain
I'm having problems understanding how to apply a texture to a non-rectangular object. The following code creates textures such as this:

from the debug renderer I think I've got the physical shape of the "earth" correct. However, I don't know how to apply a texture to it. I have a 50x50 pixel image (in the environment constructor as "dirt.png"), that I want to apply to the hills. I have a vague idea that this seems to involve the mesh class and possibly a ShapeRenderer, but the little i'm finding online is just confusing me.

Bellow is code from the class that makes and regulates the terrain and the code in a separate file that is supposed to render it (but crashes on the mesh.render() call). Any pointers would be appreciated.

```
public class Environment extends Actor{
      Pixmap sky;
      public Texture groundTexture;
      Texture skyTexture;
      double tankypos; //TODO delete, temp
      public Tank etank; //TODO delete, temp
      int destructionRes; // how wide is a static pixel
      private final float viewWidth;
      private final float viewHeight;
      private ChainShape terrain;
      public Texture dirtTexture;
      private World world;
      public Mesh terrainMesh;

      private static final String LOG = Environment.class.getSimpleName();

      // Constructor
      public Environment(Tank tank, FileHandle sfileHandle, float w, float h, int destructionRes) {
        world = new World(new Vector2(0, -10), true);
        this.destructionRes = destructionRes;
        sky = new Pixmap(sfileHandle);
        viewWidth = w;
        viewHeight = h;
        skyTexture = new Texture(sky);
        terrain = new ChainShape();
        genTerrain((int)w, (int)h, 6);

        Texture tankSprite = new Texture(Gdx.files.internal("TankSpriteBase.png"));
        Texture turretSprite = new Texture(Gdx.files.internal("TankSpriteTurret.png"));
        tank = new Tank(0, true, tankSprite, turretSprite);
        Rectangle tankrect = new Rectangle(300, (int)tankypos, 44, 45);
        tank.setRect(tankrect);

        BodyDef terrainDef = new BodyDef();
        terrainDef.type = BodyType.StaticBody;
        terrainDef.position.set(0, 0);
        Body terrainBody = world.createBody(terrainDef);

        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = terrain;
        terrainBody.createFixture(fixtureDef);

        BodyDef tankDef = new BodyDef();
        Rectangle rect = tank.getRect();
        tankDef.type = BodyType.DynamicBody;
        tankDef.position.set(0,0);
        tankDef.position.x = rect.x;
        tankDef.position.y = rect.y;
        Body tankBody = world.createBody(tankDef);

        FixtureDef tankFixture = new FixtureDef();
        PolygonShape shape = new PolygonShape();
        shape.setAsBox(rect.width*WORLD_TO_BOX, rect.height*WORLD_TO_BOX);
        fixtureDef.shape = shape;

        dirtTexture = new Texture(Gdx.files.internal("dirt.png"));
        etank = tank;
      }

      private void genTerrain(int w, int h, int hillnessFactor){
            int width = w;
            int height = h;

            Random rand = new Random();
            //min and max bracket the freq's of the sin/cos series
            //The higher the max the hillier the environment
            int min = 1;

            //allocating horizon for screen width
            Vector2[] horizon = new Vector2[width+2];
            horizon[0] = new Vector2(0,0);
            double[] skyline =  new double[width]; //TODO skyline necessary as an array?

            //ratio of amplitude of screen height to landscape variation
            double r = (int) 2.0/5.0;

            //number of terms to be used in sine/cosine series
            int n = 4;
            int[] f = new int[n*2];

            //calculating omegas for sine series
            for(int i = 0; i < n*2 ; i ++){
                f[i] =  rand.nextInt(hillnessFactor - min + 1) + min;
            }

            //amp is the amplitude of the series
            int amp =  (int) (r*height);
            double lastPoint = 0.0;
            for(int i = 0 ; i < width; i ++){
                skyline[i] = 0;

                for(int j = 0; j < n; j++){
                    skyline[i] += ( Math.sin( (f[j]*Math.PI*i/height) ) +  Math.cos(f[j+n]*Math.PI*i/height) );
                }

                skyline[i] *= amp/(n*2);
                skyline[i] += (height/2);
                skyline[i] = (int)skyline[i]; //TODO Possible un-necessary float to int to float conversions
                tankypos = skyline[i];
                horizon[i+1] = new Vector2((float)i, (float)skyline[i]);
                if(i == width) lastPoint = skyline[i];
            }
            horizon[width+1] = new Vector2(800, (float)lastPoint);
            terrain.createChain(horizon);
            terrain.createLoop(horizon);

                    //I have no idea if the following does anything useful :(
            terrainMesh = new Mesh(true, (width+2)*2, (width+2)*2,
                    new VertexAttribute(Usage.Position, (width+2)*2, "a_position"));
            float[] vertices = new float[(width+2)*2];
            short[] indices = new short[(width+2)*2];
            for(int i=0; i < (width+2); i+=2){
                vertices[i] = horizon[i].x;
                vertices[i+1] = horizon[i].y;
                indices[i] = (short)i;
                indices[i+1] = (short)(i+1);
            }
            terrainMesh.setVertices(vertices);
            terrainMesh.setIndices(indices);
      }

```

Here is the code that is (supposed to) render the terrain.

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    // tell the camera to update its matrices.
    camera.update();

    // tell the SpriteBatch to render in the
    // coordinate system specified by the camera.

    backgroundStage.draw();
    backgroundStage.act(delta);

    uistage.draw();
    uistage.act(delta);

    batch.begin();
    debugRenderer.render(this.ground.getWorld(), camera.combined);
    batch.end();

    //Gdx.graphics.getGL10().glEnable(GL10.GL_TEXTURE_2D);
    ground.dirtTexture.bind();
    ground.terrainMesh.render(GL10.GL_TRIANGLE_FAN); //I'm particularly lost on this
    ground.step();
}

```

# Answer
Well, you need to do a lot of things in order to texture random terrain. At this point, you don't even have texture coordinates in your vertices. But assuming you can implement all those other required steps, the general method is simple.

1. Use a texture mode that wraps both X and Y (in libgdx,`Texture.TextureWrap.Repeat`)
2. Make the texture coordinates proportional to world position of the vertex.

(Now that I think of it, it might be possible to use "excessive cleverness" to avoid the texture coordinates, and program your shader to sample the texture based on the vertex world position. But somehow that seems like a generally bad idea.)

---

Some of my implementation:

```
private Mesh MakeMesh(float[] heights) {

    // SEGMENT_WIDTH = magic number for space between heights

    float[] verts = new float[10 * heights.length];

    for (int i = 1; i <= (heights.length); i++){

        verts[10 * i - 10] = (i - 1) * SEGMENT_WIDTH;
        verts[10 * i - 9] = heights[i - 1];
        verts[10 * i - 8] = 0;
        verts[10 * i - 7] = (i - 1);
        verts[10 * i - 6] = 0;

        verts[10 * i - 5] = (i - 1) * SEGMENT_WIDTH;
        verts[10 * i - 4] = 0;
        verts[10 * i - 3] = 0;
        verts[10 * i - 2] = (i - 1);
        verts[10 * i - 1] = heights[i - 1] / SEGMENT_WIDTH;
    }

    short[] indices = new short[6 * heights.length];

    for (short i = 1; i < heights.length; i++) {
        indices[6 * i - 6] = (short) (i * 2 - 2);
        indices[6 * i - 5] = (short) (i * 2 - 1);
        indices[6 * i - 4] = (short) (i * 2 - 0);
        indices[6 * i - 3] = (short) (i * 2 - 1);
        indices[6 * i - 2] = (short) (i * 2 - 0);
        indices[6 * i - 1] = (short) (i * 2 + 1);
    }

    mesh = new Mesh(Mesh.VertexDataType.VertexArray,
        true, verts.length / 5, indices.length,
        VertexAttribute.Position(), VertexAttribute.TexCoords(0));
    mesh.setVertices(verts);
    mesh.setIndices(indices);

    return mesh;
}

```

And drawing:

```
public void draw(Matrix4 worldView){

    texture.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat);
    texture.bind(0);

    shader.begin();
    shader.setUniformMatrix("u_worldView", worldView);
    shader.setUniformi("u_texture", 0);
    mesh.render(shader, GL20.GL_TRIANGLES);
    shader.end();
}

```
> 1 votes

---
Tags: textures, box2d, libgdx, terrain-rendering
---


# Question
Title: Why is an engine like Unity3D emphasized over a native library like OpenGL for beginners?
I am just a beginner in 3D games, my preferred platform is Android. I posted a question in some other forum about "What to use: OpenGL or Unity3d?" They all emphasized Unity3D and using its built-in features and tools, which I would have to code myself if I were to use OpenGL. But then someone says most of the complex games require custom engines. Why would I use an engine like Unity3D over OpenGL?

# Answer
> 29 votes
I think you've answered this question yourself already. You said *"I'm just a beginner in 3D games"*. Further you said *"... Unity3D and using it's built in features and tools, which I would have to code myself if I were to use OpenGL"*.

Essentially this means if you're using OpenGL alone, you're going to be writing a game engine, then, potentially years later, writing your game. If you want to focus on a game, utilize the resources available to you to get you as close to that goal as possible. Using a game engine is the best way focus your efforts on creating a game, instead of writing all the stuff required to create a game.

See this related question: What's the difference between a Library and an Engine and this one What is a game framework versus a game engine?

# Answer
> 27 votes
**Because beginners, by definition, don't know what they're doing**.

OpenGL has a **huge** learning curve. Sure, you can issue a few glBegin commands, get all excited about putting some triangles on the screen, then go off the deep end with something more complex that you're nowhere near ready to take on yet. That's not a great way to learn. An analogy (slightly exaggerated) might be learning some basic high-school physics then being put in charge of the Large Hadron Collider. It's not sink-or-swim, it's swim-or-leave-a-large-radioactive-hole-in-the-ground.

It's assumed that most people asking the "I want to make a game, what should I use?" question actually *do want to make a game* (otherwise they would have asked a different question, surely?) So the answer is tailored to the question, and using a pre-existing toolkit, framework or engine is one way of helping them achieve that ambition without becoming distracted by agonizing over whether a UBO or glUniform calls is preferable for updating a single matrix.

This is all about taking one step at a time, making the learning process easier, and giving you something rewarding at the end of it. Trying to learn how to make a game *and* how to properly use a mature and powerful 3D API *at the same time* is probably too much for a beginner. This is like the Dunning–Kruger effect minus the negative connotations. You don't know what you don't know, so you don't really have any kind of realistic picture of exactly what you'd be taking on.

On the other hand if your objective is to learn OpenGL, then you don't actually want to make a game! You want to learn OpenGL, and doing it in the context of making a game may be a fun way of learning, but making a game is a means to an end, not an end in itself (and certainly not the only way of learning OpenGL). You'll probably never release it, and you'll almost definitely look back on it in a few years time and be horribly embarassed by some of the stupid things you did.

# Answer
> 21 votes
It really depends on what you want to get out of this project. If your main goal is to focus on game design, then you're probably better off with a pre-built engine, because that will get you to the game-making part a lot quicker. If your goal is to learn about the programming portion of making games (especially if you're trying to prepare for a job in the industry), then you'll probably find working with OpenGL will be a more valuable experience. Keep in mind that neither of the preceding statements are true 100% of the time.

There really is no rule when deciding on this sort of thing. Most of the responses you hear in that sort of question are opinions, and very few of those will be completely relevant to your own project and skill set.

# Answer
> 5 votes
The difference is simple. Unity is a carriage with four round wheels that can get you places. OpenGL is sawdust that you could set up a shop and potentially use to mould an improved and more modern carriage and wheels. That is if you invest many hours of your time into learning what the people before you have done first.

Your goal as a beginner should be to first study existing carriages and their designs. There is not point in throwing everything out the window and starting from scratch. First learn what *already* exists and get a thorough knowledge of it. If you don't, how do you know of it's limitations and if you don't know the limitations, how could you break through them? What is the point in making something mediocre that is useless and being ignorant to all the vibrant existing tools that are already available?

imho the steps of a fledgling game dev are:

1. Master a modern framework / Engine and get a deep understanding of it (This will also help you learn of the different aspects of game design, graphics and OpenGL are not all there is).
2. Make a small game with it and learn more in the process.
3. Organically encounter obstacles and limitations in the engine.
4. Learn more about the subject.
5. Work to improve the areas that you deem needs improving.

Working solo on your own on making something that has already been made will not make you a valuable developer to anyone because you will not be productive in truth or a good learner for that matter, you will just copy existing bits of code and maybe learn to read and understand them. As the old Pokemon saying goes, "It's not very effective...".

The worst part is that this kind of approach is not easy to keep up with because there is not gratification in it so you are running on raw will power which has been scientifically proven to be a limited resource to human beings. You need to do something that provides daily gratification or your will probably not be able to keep it up.

So to sum things up, an Engine is emphasized because you can get things done with an Engine and you are far more likely to succeed that way. Even great game creators relied on someone else’s previous work and such is the nature of progress. You need to understand the big picture and know how to play with the Lego pieces provided by others before you make your own custom Lego pieces.

# Answer
> 4 votes
Assuming your goal is to create a game, the guy who talked about custom engines being *required* was wrong. If anything, complex games require a mature engine that's been designed, implemented, optimized, tested and is maintained by professionals who have been in the industry for long - or one that can match their quality (at least for the purposes of a given game), if that's possible.

Large game developers do build in-house engines, but they still reuse them heavily for their future games. But keep in mind that their budgets and team sizes and lots of other factors are vastly different than independent developers' - it may make much more business sense for them to build their own engine, even if existing ones don't fall short technologically.

Of course, there's still the misconception, because a lot of features don't exist out-of-the-box in existing engines, that they can't be implemented in that engine at all, but that's usually inaccurate.

Keep in mind that some of the most innovative modern games, like Portal and Antichamber, were built using existing engines. Some rather complex online games, like Aion and TERA were built using existing engines. Some of the most visually beautiful games, like Bioshock Infinite and Thief, were built using existing engines. And, of course, some weren't. But the point is: nothing I've ever seen really *required* a custom engine.

On the other hand, if your goal is to learn concepts of graphics programming, of course OpenGL is the way to go. But even then, keep in mind that being familiar with a few existing engines will help you tremendously with understanding what you're doing and what you should be aiming for.

---
Tags: opengl, android, unity
---


title: Connecting players in an Online TCG

text:
# Question
Title: Connecting players in an Online TCG
I've been developing single player games for a while now and I have decided to start working on a online PC(and maybe mobile) TCG. The design is almost complete and I can cover most of the code as far as single player goes.

My question is:

Do I have to implement some sort of server-client model in order to make it possible for two player to get in a match together?

# Answer
> 2 votes
Every network application requires some system to act as a server. There are two ways to implement a multiplayer game:

1. **peer-to-peer** \- in every match, the machine of one player acts as a server, the others as clients.
2. **client-to-server** \- there is a dedicated server application all players connect to but which doesn't play itself. It is either hosted by you or by ambitioned community members.

Note that even in a peer-to-peer model it can be very useful to have a central server for matchmaking purposes. Without a central matchmaking server it is very difficult for players to find opponents. They would need to use some other communication plattform to manually exchange IP addresses.

The advantage of a peer-to-peer architecture is that it is a lot more convenient for you as a game publisher, because you don't have to buy, host and maintain a gameserver (or even many all around the world when your game becomes very successful). But unfortunately there is a problem which might be extremely important especially in the context of a trading-card game: Peer-to-peer allows the players to cheat.

When you have a central server which manages the game-state, you can make cheating really difficult. When a player tries to make an illegal move, the server can reject it and not forward it to the other players. The server can also withhold any information from the clients the player isn't supposed to know, like what cards the opponent has on their hand or which card they will draw next. When the client knows about these things or even decides them, a determined hacker can find a way to manipulate the game.

Also, a trading card game implies that each player owns an inventory of individual cards and can obtain more cards through trading, playing or other means (like micro-transactions). When that's the case, you definitely want to keep track of the inventory of each player on a central server. When the clients manage their inventory themself, it won't take long until players figure out which file to edit to get any card they want. This would pretty much ruin multiplayer for any players who want to play honestly and would ruin your business model when it's based on micro-transactions.

And no, there is nothing you can do about that. You can obfuscate your inventory files through encryption or store hashes and checksums of the state of the file to detect manipulation, but you need to store these somewhere where the players can access them. The only way to get the players hands off of their game state is to save it out of reach on a server. A pure peer-to-peer model should only be considered for games which do not require any form of persistence between matches.

---
Tags: multiplayer, server, online, card-game, client
---


# Question
Title: gl_VertexID values when calling glDrawElements
I am struggling a bit to understand the values that `gl_VertexID` primitive contains when the vertex shader is executed.

I have the standard modern rendering pipeline, in which after setting up shaders, buffers, etc I call the code below to render a mesh

```
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, auxMesh->indicesBuffer);
    glDrawElements(GL_TRIANGLES, auxMesh->numIndices, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```

In the vertex shader I want to manually access to the current vertex being rendered retrieving it from the original buffer (I know this sounds nonsense, but I need to do this for a reason), therefore I pass the vertex buffer as the texture buffer `u_tbo_tex` and I access to the actual coordinates as follows:

```
vec3 vertex_1 = texelFetch(u_tbo_tex, gl_VertexID + 0).xyz;
vec3 vertex_2 = texelFetch(u_tbo_tex, gl_VertexID + 1).xyz;
vec3 vertex_3 = texelFetch(u_tbo_tex, gl_VertexID + 2).xyz;

```

And the values of these vertex `vertex_1`, `vertex_2`, `vertex_3` make perfect sense.

However, I can't really understand what values `gl_VertexID` got in each iteration. Is `gl_VertexID` sequentially assigned following the range of `[0...auxMesh->numIndices]`. Or are the values increased `+3` at every iteration because I am drawing triangles?

I need to understand this because I am interested in calling `textureFetch(u_tbo_tex, i)` where `i` is a arbitrary triangle in my mesh (or whatever `i` needs to be to access an arbitrary triangle), but I can't find the right way to access to it.

# Answer
`gl_VertexID` is the literal index value of the vertex that is being processed.

In the case of non-indexed geometry an implicit increasing index were assigned to each vertex being processed.

The Vertex Shader runs on individual vertices without knowledge of adjacency or the kind of primitive being processed. If you're using indexed geometry, a shared vertex will likely be processed fewer times than it's used.

As a tangent, Geometry Shaders have, given the right primitive type, some knowledge of adjacency but probably not enough to solve the problem at hand.

If you wish to identify the triangle you're in, consider using unindexed geometry as the mapping to triangle ID and vertex ID is a matter of division and modulo by 3.

Edit: removed term "vertex processing" which has wider meaning and mentioned GS
> 4 votes

---
Tags: opengl, shaders, glsl, vertex-buffer
---


title: Algorithm to zoom a plotted function

text:
# Question
Title: Algorithm to zoom a plotted function
I'm making a game in android and I need plot a function, my algorithm is this:

```
    @Override
    protected void onDraw(Canvas canvas) {
        float e = 0.5f;
        //from -x axis to +x evaluate f(x)
        for (float x = -z(canvas.getWidth()); x < z(canvas.getWidth()); x+=e) {
                 float x1,y1;
                 x1 = x;
                 y1 = f(x);
                 canvas.drawPoint((canvas.getWidth()/2)+x1, (canvas.getHeight()/2)-y1, paintWhite);
        }
        super.onDraw(canvas);
    }

```

This is how it works. If my function is, for example f(x)=x^2, then z(x) is sqrt(x). I evaluate each point between -z(x) to z(x) and then I draw them. As you can see I use the half of the size of the screen to put the function in the middle of the screen. The problem isn't that the code isn't working, actually plots the function. But if the screen is of 320\*480 then this function will be really tiny like in the image below. My question is: how can I change this algorithm to scale the function?. BTW what I'm really wanting to do is trace a route to later display an animated sprite, so actually scale this image doesnt gonna help me. I need change the algorithm in order to draw the same interval but in a larger space. Any tip helps, thanks!

Current working result

Desired result

**UPDATE:** I will try explain more in detail what the problem is. Given this interval \[-15...15\] (-z(x) to z(x)) I need divide this points in a bigger interval \[-320...320\] (-x to x). For example, when you use some plotting software like this one. Although the div where is contain the function has 640 px of width, you dont see that the interval is from -320 to 320, you see that the interval is from -6 to 6. How can I achieve this?

# Answer
> 1 votes
Like Anastasios mentioned, you would be better off creating a "virtual coordinate space" for yourself, compute everything in this virtual space, and then when drawing, convert to pixel coordinates.

Basically, for the horizontal axis, you could create a function that converts from virtual coordinates \<=\> pixel coordinates. In c++ pseudo-code it would be something like this:

```
int virtualToScreenX(float vx) {
  return floorf(((vx - virtualMinX) / (virtualMaxX - virtualMinX)) * physicalWidth);
}

float screenToVirtualX(int sx) {
  return virtualMinX + (sx / (float)physicalWidth) * (virtualMaxX - virtualMinX);
}

```

You could then do the same for your Y axis, by substituting the appropriate variable names. These could be optimized by pre-computing and caching some of the terms, and converting divisions by pre-computed terms to multiplications. Be-ware that you might have to re-compute cached terms if your window changes dimensions.

You should also care about aspect ratio. To do this, you pick your "main" axis, usually Y, and then you scale your virtual ranges on the other axis by this aspect ratio.

Like so:

```
const float virtualMinY = -1.0f;
const float virtualMaxY = 1.0f;

const float aspect = physicalWidth / (float)physicalHeight;

const float virtualMinX = -1.0f * aspect;
const float virtualMaxX = 1.0f * aspect;

```

Now, your function or sprite path will always look right, no matter what the aspect ratio is.

It looks like you don't really want to zoom, but anyways, for completeness, all you need to do to implement zoom, is to scale your virtual coordinate ranges (virtualMinX, virtualMaxX, virtualMinY, virtualMaxY) by your zoom factor.

To zoom in 3x, your zoom factor is 1.0f / 3.0f. To zoom out 5x, it is 5.0f;

(remember to recompute any cached values after changing zoom levels)

# Answer
> 0 votes
Just find what the value will be when f(x) is out of your screen vertically. Then, scale the screen to that x value.

So, just start at the middle of your function and find when the f(x) value is out of your bounds of your screen and scale it to there.

# Answer
> 0 votes
If you want to "scale" the function you should change your input range ( or in mathematical terminology the domain of the function ). I advise you to make your domain irrelevant to the screen size. Also in order to make your display irrelevant of the the screen size you should use normalized coordinates ( e.x \[-1...1\] or \[0...1\] ). Screen coordinates normalization is very easy, you just divide your coordinates with the size of the screen.

---
Tags: android, mathematics, html-canvas
---


# Question
Title: Determine if a set of tiles on a grid forms an enclosed shape
Given a set of tiles on a grid, I want to determine:

* If the tiles make an enclosed figure
* If the tiles make an enclosed figure when you count the sides of the board as an edge of the figure
* If either of the previous two statements are true, which additional tiles fall inside the enclosed figure the initial tiles form.

The player will begin by pressing down on one tile, then dragging their finger to other tiles to create a chain of same-colored tiles. I will check as I go to see if the next tile is valid. Ex. If the player begins on a red tile, their only next valid move is to an adjacent red tile (diagonals **do** count). When the user lifts their finger, I need to be able to check for the 3 items above.

So my initial thought was that, since I was checking for the validity of the *chain* each time I went, when the player lifted their finger I could check if the first and last tiles were adjacent. (I already know they're the same color.) If they were adjacent I had a hunch that I'd made an enclosed figure, and I was going to come here to try and see if I was missing something big, and to get some kind of logical/mathematical proof that my hunch was correct (or an example proving it incorrect.)

But that's when I thought of item number 2: I also have to account for chains which use an edge of the board as a side of the enclosed figure. In that case, the first and last items in the chain would *not* be adjacent, but I would still have an enclosed figure. So now I'm back to square one, a bit.

What can I do with this chain of grid coordinates to figure out if they make an enclosed figure or not? And once I *do* know I have an enclosed figure, what's the best way to get an additional list of all tiles that fall inside its bounds?

Above I've drawn pictures of what I expect the 4 possible results of this test can be.

1. The chain does not make an enclosed figure.
2. The chain does make an enclosed figure.
3. If you count the sides of the board as an edge (or more than one edge) of the figure, the chain does make an enclosed figure.
4. The chain does make an enclosed figure, but there are extra data points (validly selected by the user as part of the chain) which are not a part of the figure that is created.

Case 4 is the trickiest, because you'd have to extract the "extra" chain links to find the enclosed figure and the pieces that fall inside it (but not around the "unenclosed" area).

So... Anyone have an idea of a good way to solve this, or just a starting point for me? I'm kind of going in circles at this point and could use another set of eyes.

# Answer
> 4 votes
**1. Detecting a loop of tiles**

The problem seems similiar to detecting a cycle (loop) in a graph, see here or here.

* The set of nodes `V` of that graph `G=(V, E)` are the tiles,
* an edge `e = (v1, v2)` exists between two different nodes, if the tiles are direct or diagonal neighbours

**2. Handling the screen border case**

The screen border consists of those imaginary tiles which would form a one tile wide rim around the screen of visible tiles.

According to your specification part of the screen border would form an implicit part of a closed loop. Just to detect a closed loop, it would be sufficient to extend the graph `G` to a graph `G'`by honoring the connection via this rule:

* another edge exists between any two different nodes, if the two tiles are each positioned directly near the border of the screen

Thus tiles at (0,0) and (1,0) would be part of a closed loop, together with the "border tiles" (-1,0), (-1,-1), (0, -1), (1, -1).

**3. The inner part of a looped area**

I would go into a similiar direction to what user *Arthur Wulf White* suggested:

Limiting the set of tiles we have to examine by the bounding box of the loop tiles.

Then using a flood fill to select all tiles within the bounding box which are either exterior or interior to the closed loop. It can only be one of those two cases. Which one we have to find out afterwards.

Extending the bounding box by one tile in each direction would be a good idea as well, yielding the `extbb`, so we just end up with one connected set of exterior points, in case we started the flood fill with an exterior tile.

Once we have the flood fill area, we would calculate its bounding box as well, the `ffbb`. In case we started with an exterior tile, it should be identical to the extended loop bounding box.

```
ffbb == extbb

```

In case we started with an interior tile, it should yield a distinctly smaller bounding box, because the loop tiles have to be sandwiched in between both bounding boxes.

```
ffbb < extbb

```

The initial starting tile for the flood fill could be any tile within the `extbb` which is a free tile. Maybe picking one randomly is the best approach.

If I would know before that the interior is smaller than the exterior, I would start around the center of mass of the loop points which is in the interior for many areas (counter example: C shaped area), otherwise on the border of the `extbb`. But I have no idea how to estimate this.

**Final remarks**

Normaly I would say a simple walk starting from some tile and keeping a list of visited tiles would be sufficient to detect a cycle, but that screen boundary condition might yield a more complicated graph, so you should be on the safe side with a graph algorithm.

Below is an example where the interior is not connected, on the other hand the cycle detection should find two loops in that case, one should get discarded.

# Answer
> 0 votes
Your intuition is right, assuming that the chain ends as soon as the user tries to select a tile they have already selected. In that case, the shape in general looks like a lasso, in your picture (4). If they can keep swiping, then they can draw many loops, and things get more complicated. What you want to do is answer the points-in-polygon question.

First, we need to define the problem. I am going to assume that the situation looks like (2), i.e. any tail has been stripped off, and the end connects back to the start, so that each tile has exactly one "predecessor" and exactly one "successor" in the chain (where the predecessor of the successor of tile X is always tile X). Further, if you follow "successors" for long enough, you eventually get back to where you started. You can use Gurgadurgen's suggestion to detect whether the loop actually crosses back on itself at any point. Assuming you end the user's input when it does, it will look like some series of nodes in a line, followed by a loop. You can strip the line off the get the loop.

Now we, for each row do the following:

1. Start at the left edge, and keep track of a boolean for each tile which tells whether we are IN or OUT. Start OUT.
2. If the current tile is part of the chain, look at both the successor and the predecessor (which must be adjacent). If either is strictly above (i.e. north, north east, or north west of the current tile), set the current tile's state to the opposite of the tile to its left. Otherwise, set it to the same as the tile to the left. Goto 4.
3. If the current tile is not part of the chain, set the tile to the state of the title to its left. Goto 4.
4. The tile one to the right is now the current tile. Goto 2.

Now take all the tiles which are IN, add in the tiles on the border (including a tail if you stripped it earlier or not, your choice), and call that the region.

If you want to allow the user to use borders, remember that this does not define and IN/OUT on the board, but just divides it into two parts. You could select the smaller region, for example, or require the user to use two adjacent sides (i.e., the left and bottom, but not either top/bottom or left/right).

An optimization is that you only need to do rows which have any border in them (if you can't use the sides). I assume that your board is small enough that iterating over every tile and doing a very simple computation is not an issue, even on the weakest mobile system. (You do have to render them, after all, which is far more complex of a task).

# Answer
> 0 votes
You can resolve this by:

1. Finding the bounding box of that shape.
2. Increasing it's size by 1 in each direction.
3. Iterating over the frame of the new slightly enlarged bounding box and applying flood-fill.
4. If there are any tiles that you did not mark with flood-fill that are not on that chain then they are enclosed. I suppose that by your definition if there are enclosed tiles than the shape is a closed figure.

To do one, iterate over all tiles on the chain and find their `minX`, `minY`, `maxX` and `maxY` and that is your bounding box or AABB.

Two is trivial.

Iterating over the frame is simple, just make sure not to flood-fill outside the grid. You can learn how to flood-fill in Wikipedia.

For number four you can start by only checking tiles adjacent to the chain. You could flood-fill from any tile you find that is not marked to locate more tiles.

---
Tags: algorithm, grid, graph
---


title: How do I animate Unity GUIComponents?

text:
# Question
Title: How do I animate Unity GUIComponents?
I want to transform my `GUIWindow` from the bottom of the screen to the middle whenever the user presses a button. How can I do this?

# Answer
> 1 votes
Using isGuiUp to store a state (location of GUI), then an if statement to determine the proper location of the GUI.

Add the following to the Update() funciton of your gui controller script.

```
bool isGuiUp = false;

if (Input.GetKeyUp(KeyCode.Escape))
{
    isGuiUp = !isGuiUp; //toggle the state
}

if (isGuiUp == true)
{
    //code to move the gui to the middle of the screen
}
else
}
    //code to move the gui to the bottom of the screen
}

```

---
Tags: unity, gui, transformation
---


title: Howdo I load a GIF animation in pygame?

text:
# Question
Title: Howdo I load a GIF animation in pygame?
How can I load a GIF animation in pygame? With a web search, I found a severely outdated library called *GIFImage*. I tried it to do it with 2 pictures but I'm getting stuck because I'm a beginner. I also found something about making animations with Sprites, but no tutorial...

How do I do this?

# Answer
> 4 votes
I think what you mean is, how to load an **animated GIF** in pygame.

It's true that pygame doesn't support animated GIFs natively, and you'd need GIFImage for that. Not sure how well it works, but I wouldn't recommend it anyway.

This is because in games you usually want to control the animation yourself. Use a spritesheet or separate images for your sprite frames. Then swap out the image in your game. See this question for more details.

For the record, if the GIF *isn't* animated, it's trivial:

```
sprite_image = pygame.image.load("image.gif").convert_alpha()

```

---
Tags: python, pygame
---


title: Libgdx collision detection and response

text:
# Question
Title: Libgdx collision detection and response
I am trying to create a simple platformer game with libgdx. I implemented a collision detection for the player's bounding box with the map's tiles using the `Rectangle.overlaps` method.

In response I am trying to find out at what edge the player hits the tile and then react accordingly.

Somehow it happens that when the player collides on the X axis, the response of a collision on the Y axes happens (player gets moved to the top of the tile).

I was looking into the SAT (Seperating Axis Theorem), but I don't feel like it's applicable here, since I am not trying to draw any line betwen the Rectangles. In fact, since `Rectangle.overlaps()` is used I am only reacting to a collision already happening.

Here the source:

```
private void resolveCollision() {
    setUpPlayerRec(allObjects.get(0));
    for (Rectangle r2 : tiles) {
        if (!playerRec.overlaps(r2)) {
            continue;
        } else {
            onCollisionWithTile(r2);
        }
    }
}

private void onCollisionWithTile(Rectangle r2) {
    Gdx.app.log("Collision Detected", "Player collided with tile");

    float diff;

    if (playerRec.x +playerRec.width < r2.x) {
        // LEFT EDGE OF TILE
        controlledPlayer.getPosition().x =(r2.x - playerRec.width);
        controlledPlayer.getVelocity().x = 0;
    } else if (playerRec.x > r2.x + r2.width) {
        // RIGHT EDGE OF TILE
        controlledPlayer.getPosition().x =(r2.x + r2.width);
        controlledPlayer.getVelocity().x = 0;
    }

    if (playerRec.y < r2.y) {
        // HIT TOP OF TILE
        diff = (playerRec.y + playerRec.height) - r2.y;
        controlledPlayer.getPosition().y -= Math.abs(diff);
        jumptime = MAXJUMP;
        controlledPlayer.setJumpState(JUMP_STATE.GROUNDED);
    } else if (playerRec.y < r2.y + r2.height) {
        // HIT BOTTOM OF TILE
        controlledPlayer.setJumpState(JUMP_STATE.GROUNDED);
        jumptime = 0;
        diff = playerRec.y - (r2.y + r2.height);
        controlledPlayer.getPosition().y = r2.y + r2.height;
    }
}

```

# Answer
I wrote a tutorial here that could help: http://mijyn.github.io/tutorial/2013/06/05/platformer-aabb-cr.html

But, as StackExchange doesn't exactly love people linking tutorials, I'll give a basic overview of what it says. I was facing the challenge of not copying and pasting the entire post, but still making this answer more than just a link. I think I solved this by simply giving the concepts here, and leaving the implementation in the link.

Here are the beautiful graphics I'm using to demonstrate:

```
||||||||
|      | <- Object 1
||||||||

--------
-      - <- Object 2
--------

```

Alright, so, to check collision between 2 objects, you have to check the overlap between both objects:

```
Startpos1  Endpos1
v          v
||||||||||||
|     -----|--------
|     -    |       -       In this case, endpos1 > startpos2 and endpos1 < endpos2
||||||-|||||       -        Therefore, there is a collision.
      --------------        We must also check vice versa
      ^            ^
      Startpos2    Endpos2

```

We must check this on both axises, because if not, a situation like this could come up:

```
||||||||||
|        |
||||||||||
                     If we only check the X axis,
     ----------       this will be detected as a collision.
     -        -
     ----------

```

To resolve, we must find the overlap, and subtract it from the axis:

```
      ++++++            Overlap = Endpos1 - Startpos2

Startpos1  Endpos1      For this to work,
v          v             we must make sure that Startpos1 < Startpos2
||||||||||||
|     -----|--------
|     -    |       -
||||||-|||||       -
      --------------
      ^            ^
      Startpos2    Endpos2

```

If your game is 1D, the entire collision detection and response process is trivial: Check if there is a collision, and if so, subtract the overlap. Done!

However, chances are, your game is 2D or 3D. So, the obvious solution is to simply check each axis for collision and subtract the overlap if applicable. Also, we must make sure that both axises are colliding

Slight problem with that though:

```
||||||||||||
|     -----|--------         Where do you think this will resolve?
|     -    |       -
||||||-|||||       -
      --------------

||||||||||||
|          |
|          |
||||||||||||
            --------------
            -            -   Most likely not what you wanted
            -            -
            --------------

```

So therefore, we must only resolve one axis if possible. We must resolve the shortest overlap. This will work for most situations. Except for this:

```
||||||||||||
|          | --------------  Frame 1
|||||||||||| -            -
             --------------

                    ||||||||||||
             -------|------    |
             -      ||||||||||||  Frame 2
             --------------

```

Which is the shortest overlap? Y. So it'll end up like this:

```
                    ||||||||||||
                    |          |
                    ||||||||||||
             --------------
             -            -
             --------------

```

Not what we want.

To fix this, we must find which axises the previous frame collided with, and resolve the collision for the *other* axis:

```
||||||||||||
|          | --------------  Collides with Y
|||||||||||| -            -   Therefore, we must resolve X in the next frame
             --------------

||||||||||||
|          |
||||||||||||
             --------------  Collides with none
             -            -   Therefore, we must resolve both in the next frame
             --------------

```

Now it should work perfectly, right? Not quite (whoever told you that AABB is easy was lying!! XD). What if this happens?

```
||||||||||||
|          | --------------  Frame 1
|||||||||||| -            -
             --------------

                         ||||||||||||
             ------------|-         |
             -           ||||||||||||
             --------------  Frame 2

```

It will resolve the X axis (awesome!), but which side?

```
                           ||||||||||||
             --------------|          |
             -            -||||||||||||
             --------------

```

Not what we want!

How do we fix this? Let's go back a bit:

```
      ++++++            Overlap = Endpos1 - Startpos2

Startpos1  Endpos1      For this to work,
v          v             we must make sure that Startpos1 < Startpos2
||||||||||||
|     -----|--------
|     -    |       -
||||||-|||||       -
      --------------
      ^            ^
      Startpos2    Endpos2

```

True, we do have to make sure that Startpos1 \< Startpos2. However, we must use Startpos1 from the previous frame, not this one.

Alright, so, now we have a good collision response function that should work great!

However..... (you knew this was coming, didn't you? XD) that's not the end of the story. While it works great for single objects, we might run into problems in some situations with more than one object:

```
      ------
      -    -
      -    -
      ------   Frame 1
||||||======
|    |=    =
|    |=    =
||||||======

      ------
      -    -
      -    -
    ||||||--   Frame 2
    | ===|==
    | =  | =
    |||||| =
      ======

```

The bottom object (the one with `=`) knows to resolve the X axis. However, the top one thinks that it's best to resolve the Y axis, because it doesn't know which side to resolve (none of the axises were colliding in Frame 1).

To fix this, we must sort the objects such that objects that collide with either axis with Object 1 in Frame 1 (in this example, it's the `=` one) are placed in front of objects that don't collide with either axis (in this example, it's the `-` one).

I apologize if my language style or clarity becomes worse later on in the post, I'm writing this at midnight XD
> 5 votes

---
Tags: collision-detection, libgdx, game-mechanics
---


title: Sampling Heightmap Edges for Normal map

text:
# Question
Title: Sampling Heightmap Edges for Normal map
I use a Sobel filter to generate normal maps from procedural height maps. The heightmaps are 258x258 pixels. I scale my texture coordinates like so:

```
texCoord = (texCoord * (256/258)) + (1/258)

```

Yet even with this I am left with the following problem:

As you can see the edges of the normal map still proves to be problematic. Putting the texture wrap mode to "clamp" also proved no help. EDIT: The Sobel Filter function by sampling the 8 surrounding pixels around a given pixel so that a derivative can be calculated in order to find the "normal" of the given pixel.

The texture coordinates are instanced once per quad (for the quadtree that makes up the world) and are created as follows (it is quite possible that the problem results from the way I scale and offset the texCoords as seen above):

Java:

```
for(int i = 0; i<vertices.length; i++){
        Vector2f coord = new Vector2f((vertices[i].x)/(worldSize), (vertices[i].z)/( worldSize));
        texCoords[i] = coord;

    }

```

the quad used for input here rests on the X0Z plane. 'worldSize' is the diameter of the planet. No negative texCoords are seen as the quad used for input for this method is not centered around the origin.

Is there something I am missing here? Thanks.

# Answer
> 1 votes
It may be that you are hitting an edge of the texture when sampling. If so, the GPU will just wrap around and return you a disconnected texel from the other side. You could try messing a bit with the texture filtering options to see if there are any visible changes (on OpenGL *glTexParameter()* with GL\_TEXTURE\_MIN\_FILTER and GL\_TEXTURE\_MAG\_FILTER), and possibly manually adding a safety border to the textures yourself.

# Answer
> 0 votes
Any specific reason you're using 258 x 258 pixels heightmap/texture?

Two rows and columns of pixels possibly force the graphics card into making the texture up to four times as big as necessary which might as well cause those black lines, since it might not be able to handle textures that aren't the power of two for their width/height.

The unused pixels might be filled with some other color (like black), which could then cause them to bleed into their neighbours when upscaled.

---
Tags: normal-mapping
---


# Question
Title: How should I draw the GUI if I use a 2D camera?
I have a camera in my 2D side scrolling game and I want to implement the GUI. How can I do that?

For the moment, I draw everything like this:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, scaleMatrix * camera.GetMatrix());
  player.Render(spriteBatch);
  GUI.Render(spriteBatch);
  ...
spriteBatch.End();

```

Should I separate the GUI drawing code from the camera's transformation matrix? How can I do that? What is the best way to implement the GUI in a Windows Phone 8 project?

# Answer
You could use a new begin and end set for the GUI. Doing this gets very slow if you use too many begin and end calls in a single frame. However, if you only have 2( one for world space and one for screen space ) it should be fine.

HOWEVER, I strongly suggest you ditch matrices for this. I find manually transforming vectors before I pass them to spriteBatch to be much better.

For example:

```
void Draw( SpriteBatch spriteBatch, Camera camera )
{
    // We perform all transformations on our position vector in camera.Transform.
    // This way we transform per sprite instead of per begin/end set.
    spriteBatch.Draw( texture, camera.Transform( position ), Color.White );
}

```

This will give you more control over what goes in what coordinate space. Matrices can be very easy and convenient to use, but in my opinion SpriteBatch doesn't work with them well.
> 2 votes

---
Tags: xna, c#, monogame, windows-phone-8
---


title: Cull mode back faces

text:
# Question
Title: Cull mode back faces
When i draw a cube using indices, the faces of the cube are skewed but only when CullMode is set to cull back. When i switch it to cull none, it draws the cube perfect. Unfortunately i cant post any code at the time because I'm using my phone, but what are some possible explanations for why the faces of my cube are skewed wjile culling the back? I was thinking the order of my indices may be the problem.

https://i.stack.imgur.com/eZa7E.png

```
VertexType* vertices;
unsigned long* indices;
D3D10_BUFFER_DESC vertexBufferDesc, indexBufferDesc;
D3D10_SUBRESOURCE_DATA vertexData, indexData;
HRESULT result;

m_vertexCount = 8;
m_indexCount = 36;

vertices = new VertexType[m_vertexCount];
if(!vertices)
{
    return false;
}

// Create the index array.
indices = new unsigned long[m_indexCount];
if(!indices)
{
    return false;
}

vertices[0].position = D3DXVECTOR3(-1, 1, -1);
vertices[0].color = D3DXVECTOR4(1, 0, 0, 1);

vertices[1].position = D3DXVECTOR3(1, 1, -1);
vertices[1].color = D3DXVECTOR4(1, 1, 0, 1);

vertices[2].position = D3DXVECTOR3(-1, -1, -1);
vertices[2].color = D3DXVECTOR4(1, 1, 1, 1);

vertices[3].position = D3DXVECTOR3(1, -1, -1);
vertices[3].color = D3DXVECTOR4(0, 1, 0, 1);

vertices[4].position = D3DXVECTOR3(-1, 1, 1);
vertices[4].color = D3DXVECTOR4(0, 1, 1, 1);

vertices[5].position = D3DXVECTOR3(1, 1, 1);
vertices[5].color = D3DXVECTOR4(0, 0, 1, 1);

vertices[6].position = D3DXVECTOR3(-1, -1, 1);
vertices[6].color = D3DXVECTOR4(1, 0, 0, 1);

vertices[7].position = D3DXVECTOR3(1, -1, 1);
vertices[7].color = D3DXVECTOR4(1, 0, 0, 1);

//indices = { 2, 0, 3, 3, 1, 0, 3, 1, 7, 7, 5, 1, 6, 4, 2, 2, 0, 4, 7, 5, 6, 6, 4, 5, 0, 4, 1, 1, 5, 4, 6, 2, 7, 7, 3, 2 };

indices[0] = 2;
indices[1] = 0;
indices[2] = 3;
indices[3] = 3;
indices[4] = 1;
indices[5] = 0;
indices[6] = 3;
indices[7] = 1;
indices[8] = 7;
indices[9] = 7;
indices[10] = 5;
indices[11] = 1;
indices[12] = 6;
indices[13] = 4;
indices[14] = 2;
indices[15] = 2;
indices[16] = 0;
indices[17] = 4;
indices[18] = 7;
indices[19] = 5;
indices[20] = 6;
indices[21] = 6;
indices[22] = 4;
indices[23] = 5;
indices[24] = 0;
indices[25] = 4;
indices[26] = 1;
indices[27] = 1;
indices[28] = 5;
indices[29] = 4;
indices[30] = 6;
indices[31] = 2;
indices[32] = 7;
indices[33] = 7;
indices[34] = 3;
indices[35] = 2;

vertexBufferDesc.Usage = D3D10_USAGE_DEFAULT;
vertexBufferDesc.ByteWidth = sizeof(VertexType) *m_vertexCount;
vertexBufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER;
vertexBufferDesc.CPUAccessFlags = 0;
vertexBufferDesc.MiscFlags = 0;

vertexData.pSysMem = vertices;

result = device->CreateBuffer(&vertexBufferDesc, &vertexData, &m_vertexBuffer);
if(FAILED(result))
{
    return false;
}

indexBufferDesc.Usage = D3D10_USAGE_DEFAULT;
indexBufferDesc.ByteWidth = sizeof(unsigned long) *m_indexCount;
indexBufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER;
indexBufferDesc.CPUAccessFlags = 0;
indexBufferDesc.MiscFlags = 0;

indexData.pSysMem = indices;

result = device->CreateBuffer(&indexBufferDesc, &indexData, &m_indexBuffer);

return true;
}

void CubeClass::RenderBuffers(ID3D10Device* device)
{
unsigned int stride;
unsigned int offset;

stride = sizeof(VertexType);
offset = 0;

device->IASetVertexBuffers(0, 1, &m_vertexBuffer, &stride, &offset);

device->IASetIndexBuffer(m_indexBuffer, DXGI_FORMAT_R32_UINT, 0);

device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

device->DrawIndexed(36, 0, 0);

```

}

# Answer
> 1 votes
Your indices produce triangle with mixed winding orders. Have a look at the quad which is formed by your vertices 0, 1, 2, 3. When viewed along the z-axis it looks like this (sorry for the ASCII art):

```
    ^ y
    |
0   |   1
    |
----+-----------> x
    |
2   |   3

```

Your indices draw 203 which gives a clockwise winding, and then 310 which gives a counter-clockwise winding. Modify your indices to produce only one order.

# Answer
> 0 votes
From experience, when I have an object with faces that do not render, it is because my normals are not facing towards the correct direction. Perhaps setting some normals would help, since you plan on going 3D, this would have to be done anyways.

Here is a reference describing how culling works in D3D. It may well be a winding issue.

Directly from msdn: "To improve rendering performance, you can cull out (or remove) a primitive that faces away from the camera. For single-sided primitives, this saves rendering time because a back-face is not visible. To enable culling, you need to know the winding order of the vertices (typically counter-clockwise). This example will remove any primitive whose back face is facing forward (given a counter-clockwise winding order):..."

---
Tags: directx10
---


# Question
Title: Are there still favored of using bluetooth devices today in modern games for multiplayer gameplay?
I was wondering. Most multiplayer gameplay always favored by Wi-fi during team-up or to compete each other. I know that when in comes in huge groups (say 100 to 500 players or more online) in online games whether it's cooperation or battle, most players relying on Wi-fi to play in very huge group.

What if some persons wants to play in small groups and can be played offline (like in racing games or fighting games for example) using smartphones via bluetooth? The question is that are there most game apps for multiplayer gameplay still favored or popular of using bluetooth when playing in a very few no. of players (let's say only two players) on a certain game?

Also, is it possible to create a game app for iPhone or any smartphones that run on Android that features bluetooth for multiplayer via Unity 3D game development software?

# Answer
> 1 votes
With Unity, anything the engine itself can't do, can be done with native plugins, so I'd say you can.

However, Bluetooth is designed for master/slave personal area networks, like connecting a keyboard, or a headset to a phone. Not for high speed networking.

I guess you could use the LAP profile, but once again, it is not meant for high speed communications.

I don't understand why you're considering bluetooth, but if you're interested in solving the problem of making a network when no access point is available, you may want to consider the ad-hoc mode of WLAN. You can make networks between devices without requiring an infrastructure to support it.

Some devices even let you create an access point, so you may want to consider that as well.

---
Tags: unity, multiplayer, bluetooth
---


# Question
Title: Aim at moving target (or predicting target's position at time it takes for projectile to hit it)
I have a game where I know the location and velocity of my target. I know my own location and the speed of my projectile. I want to determine either

the location of the intersection between my projectile fired and the target, or

the time taken for my projectile to intersect the target

All entities are travelling with constant speed and direction which makes life easier. I have been trying to work out the maths for some time but cannot quite get it right. I know that the predicted location of the target intersecting the projectile will be

**Pp = Tp + Tv * t**

Where Pp is the predicted position, Tp is the current target position, Tv is the target velocity, and t is time.

I also know that

**t = |Pp - Sp| / Bs**

where Sp is my (source) position and Fs is the projectile (bullet) speed. But I cannot figure out a way to solve this to get either Pp or t.

I know that all speeds are constant. I am free to aim in any direction and I know that the projectile is faster than the target therefore a hit is guaranteed

Can anyone enlighten me? Thanks

*I found a website detailing one method but this doesnt seem to work (http://howlingmoonsoftware.com/wordpress/leading-a-target/). My verification method to determine if it worked was to use the predicted position to determine the time for the target to reach it, and for the projectile to reach it. These should be very similar but in my game they are out by almost a factor of 2.*

# Answer
Similar to what you've got, start with the target's position/velocity:

> Ptarget impact = Ptarget now \+ t × vtarget

And we've got your projectile's values:

> Pshot impact = Pplayer \+ t × vshot

Since both are supposed to collide:

> Ptarget impact = Pshot impact

Due to this, you'll get this:

> Ptarget now \+ t × vtarget = Pplayer \+ t × vshot

To solve this, you'll want to bring the time dependent stuff on one side:

> Ptarget now \- Pplayer = t × vshot \- t × vtarget
>
> t × (vshot \- vtarget) = Ptarget now \- Pplayer

Now you just have to transform the term one last time:

> t = (Ptarget now \- Pplayer) / (vshot \- vtarget)
>
> t = Δposition / Δvelocity

This enables you to determine the time it takes your projectile to reach the enemy based on his currenct velocity (and orientation) as well as your distance to the target.

Once you've got this, you can once again use the very first formula to determine the point you'll have to aim for:

> Ptarget impact = Ptarget now \+ (Δposition / Δvelocity) × vtarget
> 2 votes

---
Tags: 3d, projectile-physics, aiming, movement-prediction
---


# Question
Title: Mixing old and new state of game objects?
If I have a group of game objects that are being updated each frame, and some of them query each others data like position and such, is it common practice to not care that a game object might get another game object's old state or new state depending on what got updated first? I could see that working out alright as long as the time delta between frames is small. Or is it typical to handle this either via saving one frame of old state or perhaps sorting the updates in some way?

What do well known game engines do?

Also if sorting / saving state is done, are NPCs given the new or the old state of other NPCs and the player's character?

# Answer
> 1 votes
In many cases it won't matter, but if it does you will have to do your processing in two passes.

For example, imagine you are doing a physics simulation that calculates the attraction between a group of bodies. You would first process the entire group, and calculate the final force acting on each individual body. Then you would update the positions of the objects in a second pass. Effectively the first pass happens "simultaneously", without any change happening until the second pass. There may be a small loss of performance by doing a second loop, but in this case the simulation could fail without it.

If your game shows no unusual behaviour with a single pass approach, then it may not matter, but if you are concerned about it you may want to do it in two passes to be safe.

---
Tags: architecture
---


title: AS3 eventListener not working

text:
# Question
Title: AS3 eventListener not working
I am making a game with as3. I have a Mian Class.In its main function i am putting a movieClip stored in a variable named btn and attaching an EventListener to it for CLICK which envokes a function named StartGame. To test it in the function i am using a statement that fades a movieClip holed in a variable bgClip.But its not working. Dont know why.Although it is not showing any error

```
package  {
import flash.display.Stage;
import flash.display.StageDisplayState;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
    public class Main extends MovieClip {
    public var btn:startbtn = new startbtn();
    public var bgClip:menuBg = new menuBg();
    public function Main() {
      addChild(bgClip);
      bgClip.x = bgClip.y = 0;
      addChild(btn);
      btn.addEventListener(MouseEvent.CLICK , startGame);
      }
      private function startGame(e:MouseEvent):void {
         bgClip.alpha = 0.5;
      }
    }
  }

```

# Answer
> 1 votes
Your code looks fine to me. Adding a MouseEvent listener to a display object on the stage should work as intended. Try adding this line after adding the button:

```
trace(numChildren);

```

If the result is not "2" then it would suggest that there is some other object on the stage that is blocking the cursor from hitting the button.

Common situations where this happens is when you have a large textfield that covers a button, or some other large transparent object (or a visible object with a transparent area).

If there really are no other objects on the stage then something more obscure is happening. Try making a new MovieClip that is just a coloured rectangle and try attaching the MouseEvent listener to that, without anything else on the stage.

I am guessing you are publishing your game using Flash Professional, which can complicate things by giving you an environment outside the code where you can change the settings and contents of the stage. Try making a brand new project and see if the problem persists there.

Good luck :)

---
Tags: flash, actionscript-3, events
---


title: OpenGL - Index buffers problem

text:
# Question
Title: OpenGL - Index buffers problem
I have a custom file format that has all the needed information for a 3D mesh (exported from 3ds Max). I've extracted the data for vertices, vertex indices and normals.

I pass to OpenGL the vertex data, vertex indices and normals data and I render the mesh with a call to `glDrawElements(GL_TRIANGLES,...)`

Everything looks right but the normals. The problem is that the normals have different indices. And because OpenGL can use only one index buffer, it uses that index buffer for both the vertices and the normals.

I would be really grateful if you could suggest me how to go about that problem.

Important thing to note is that the vertex/normal data is not "sorted" and therefore I am unable to use the functionality of `glDrawArrays(GL_TRIANGLES,...)` \- the mesh doesn't render correctly.

Is there a way/algorithm that I can use to sort the data so the mesh can be drawn correctly with `glDrawArrays(GL_TRIANGLES,..)` ? But even if there is an algorithm, there is one more problem - I will have to duplicate some vertices (because my vertex buffer consists of unique vertices - for example if you have cube my buffer will only have 8 vertices) and I am not sure how to do that.

# Answer
> 1 votes
I managed to do it without passing index buffer to OpenGL with `glDrawArrays(GL_TRIANGLES,..)` What I did is the following: Fill a vertex array, vertex indices array, normals array and normals indices array. Then I created new vertex and normal arrays with sorted data and passed them to OpenGL.

```
for i = 0; i < vertexIndices.size(); ++i
    newVertexArray[i] = oldVertexArray[vertexIndices[i]];

for i = 0; i < normalsIndices.size(); ++i
    newNormalsArray[i] = oldNormalsArray[normalsIndices[i]];

```

I optimized it a bit, without filling indices arrays at all. But the optimization depends on the way the programmer is reading the mesh data.

# Answer
> 4 votes
Unfortunately there is no way to do this. What you'll need to do is duplicate the data in places:

```
TexCoords:
    1: 0.67, 0.54
Vertices:
    1: 14.65, 24.09, 87.65
    2: 54.76, 34.78, 17.52

```

Where both these use texture coordinate 1, we need to copy texture coordinate 1 so there are two instances to it. We'll end up with:

```
Final Vertex Data:
    1: V 14.65, 24.09, 87.65, T 0.67, 0.54
    2: V 54.76, 34.78, 17.52, T 0.67, 0.54

```

Of course this is a waste of memory, but it saves jumping around in memory a lot, so we save a bit of time. Of course there will be situations where you find EXACTLY the same final vertex( same position, same texture coordinate, same normal etc ). In this case you'll want to index rather than copy it. This will save you A LOT of space.

---
Tags: opengl, c++, 3d, rendering, mesh
---


# Question
Title: Understanding how texCUBE works and writing cubemaps properly into a cube rendertarget
My goal is to create accurate reflections, sampled from a dynamic cubemap, for specific 3d objects (mostly lights) in XNA 4.0.

To sample the cubemap I compute the 3d reflection vector in a classic way:

```
    half3 ReflectionVec = reflect(-directionToCamera, Normal.rgb);

```

I then use the vector to get the actual reflected color:

```
    half3 ReflectionCol = texCUBElod(ReflectionSampler, float4(ReflectionVec, 0));

```

The cubemap I am sampling from is a RenderTarget with 6 flat faces.

So my question is, given the 3d world position of an arbitrary 3d object, how can I make sure that I get accurate reflections of this object, when I re-render the cubemap. Should I build the ViewProjection matrix in a specific way? Or is there any other approach?

# Answer
The incident light that is reflected will usually be true to the original object, unless it is itself reflected, bent, or otherwise altered light. The accuracy of the reflection is relative to the properties of the reflective material, and the geometry.

This link provides more reading for this wonderful topic. http://en.wikipedia.org/wiki/Fresnel\_equation.

Ideally, your cube map would be generated from the same projection you would want to see the geometry normally. Though this could be something fun to play around with.
> 0 votes

---
Tags: xna, cubemap, reflection-rendering
---


title: LWJGL - Keyboard.next() not firing

text:
# Question
Title: LWJGL - Keyboard.next() not firing
I am trying to make a class which will handle all of my inputs, however `Keyboard.next()` isn't returning true. Here is my code.

```
    while(Keyboard.next()) {
        if(Keyboard.getEventKey() == Keyboard.KEY_SPACE) {
            if (Keyboard.getEventKeyState()) {
                System.out.println("Pressed");
            }else {
                System.out.println("Released");
            }
        }
    }

```

When I removed the while loop, it infinitely outputs Pressed/Released so I know that part of the code is working. Is there something that I am missing to make this fully work?

# Answer
This code must be in the update method, if not it won't work. So you cannot seperate it in another class.

The meanings of the single methods, next() and getEventKeyState() are in the lwjgl docs, if you want more information.

```
while (Keyboard.next()) {
   if (Keyboard.getEventKeyState()) {
   if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
        System.out.println("Pressed");
   }
   }
 }

```
> -2 votes

---
Tags: java, lwjgl, input
---


# Question
Title: using eclipse instead of visual studio for cocos2d-x project
im using coco2d-x v 3.0 i made a new windows project to test it and it is working but when i try to build and run a project using this command `cocos run -p win32` it is print this error

it seem like it need visual studio to run but how can i build and run the project throw eclipse or any IDE i have tried to open it as project using eclipse in deterrent ways but not working it printed lots of errors what should i do ?

# Answer
> -1 votes
Cocos2d-x v3 uses Visual Studio 2012.

http://cocos2d-x.org/wiki/How\_to\_run\_cpp-tests\_on\_Windows

---
Tags: c++, cocos2d-x, visual-studio
---


# Question
Title: How do we solve big video memory requirements in a 2D game?
How do we solve big video memory requirements in a 2D game?

---

We are developing a 2D game (Factorio) in allegro C/C++, and we are facing a problem with increasing video memory requirements as the game content increases.

We currently gather all the info about images that are going to be used first, crop all of these images as much as possible and organize them into big atlases as tightly as possible. These atlases are stored in video memory, the size of which depends on the system limitations; currently it is usually 2 images of up to 8192x8192, so they require 256Mb to 512Mb video memory.

This system works pretty good for us, as with some custom optimisations and splitting the render and update thread we are able to draw tens of thousands of images on the screen in 60 fps; we have many objects on the screen, and allowing a big zoom-out is a critical requirement. As we would like to add more, there is going to be some trouble with the video memory requirements, so this system can't possibly hold.

One of the things we wanted to try is to have one atlas with the most common images, and the second as a cache. The images would be moved there from the memory bitmap, on demand. There are two problems with this approach:

1. The drawing from memory bitmap to video bitmap is painfully slow, in allegro.
2. It is not possible to work with video bitmap in other than the main thread, in allegro, so it is practically unusable.

---

Here are some additional requirements we have:

* The game must be determistic, so the performance issues/loading times can never alter the game state.
* The game is real time, and soon to be multiplayer, as well. We need to avoid even the smallest stutter at all costs.
* Most of the game is one continuous open world.

---

The test consisted of drawing 10 000 sprites in a batch for sizes from 1x1 to 300x300, several times for every configuration. I did the tests on the Nvidia Geforce GTX 760.

* Video bitmap to video bitmap drawing took 0.1us per sprite, when the source bitmap wasn't changing between individual bitmaps (the atlas variant); the size didn't matter
* Video bitmap to video bitmap drawing, while the source bitmap was switched between drawings (non atlas variant), took 0.56us per sprite; the size didn't matter, either.
* Memory bitmap to video bitmap drawing was really suspicious. Sizes from 1x1 to 200x200 took 0.3us per bitmap, so not so horribly slow. For larger sizes, the time started to raise very dramatically, at 9us for 201x201 to 3116us for 291x291.

Using atlas increases the performance by a factor greater than 5. If I had 10ms for the rendering, with an atlas I'm limited to 100 000 sprites per frame, and without it, a limit of 20 000 sprites. This would be problematic.

I was also trying to find a way to test the bitmap compression and 1bpp bitmap format for shadows, but I was unable to find a way to do this in allegro.

# Answer
> 20 votes
We have a similar case with our RTS (KaM Remake). All units and houses are sprites. We have 18 000 sprites for units and houses and terrain, plus another ~6 000 for team colors (applied as masks). Long-stretched we also have some ~30 000 characters used in fonts.

So there are some optimizations against RGBA32 atlases you are using:

* Split your sprites pool into many smaller atlases first and use them on demand as covered in other answers. That also allows to use **different optimizations techniques for each atlas individually**. I suspect you will have a bit less of a wasted RAM, cos when packing to such a huge textures there are usually unused areas at the bottom;
* Give a try to using **paletted textures**. If you use shaders you can "apply" the palette in the shaders code;
* You might look into adding an option to use **RGB5\_A1 instead of RGBA8** (if for example checkerboard shadows are okay for your game). Avoid 8bit Alpha when possible and use RGB5\_A1 or equivalent formats with smaller precision (alike RGBA4), they take half the space;
* Make sure you are **tightly packing sprites into atlases** (see Bin Packing algorithms), rotate sprites when necessary and see if you can overlap transparent corners for rhombus sprites;
* You might try **hardware compression formats** (DXT, S3TC, etc.) - they can dramatically reduce RAM usage, but check for compression artifacts - on some images the difference can be unnoticeable (you can use this selectively as described in first bullet point), but on some - very pronounce. Different compression formats cause different artifacts, so you might pick one that is best for your art style.
* Look into **splitting big sprites** (of course not manually, but within your texture atlas packer) into static background sprite and smaller sprites for animated parts.

# Answer
> 7 votes
First of all you need to use more, smaller texture atlases. The less textures you have the more difficult and rigid memory management will be. I would suggest a atlas size of 1024, in which case you would have 128 textures instead of 2, or 2048 in which case you would have 32 textures, which you could load and unload as needed.

Most games do this resource management by having level boundaries, while a loading screen is displayed all resources that aren't needed anymore in the next level get unloaded and resources that are needed get loaded.

Another option is On-Demand loading, which become necessary if level boundaries are unwanted or even a single level is too big to fit into memory. In this case the game will be trying to predict what the player will see in the future and load that in the background. (For example: stuff that is currently 2 screens away from the player.) At the same time things that weren't used anymore for a longer time will get unloaded.

There is one issue however, what happens when something unexpected happened that the game wasn't able to foresee?

* Panicking and displaying a loading screen until all necessary stuff is loaded. This might feel disruptive to the experience.
* Have low resolution sprites for everything preloaded, continuing the game and replacing them as soon as the high resolution sprites finished loading. This might look cheap to the player.
* Make it impact the gameplay and delay the event as long as necessary. E.g. don't spawn that enemy until it's graphics are loaded. Don't open that treasure chest before all graphics for that loot are loaded, etc.

# Answer
> 2 votes
Wow, that is a hefty amount of animation sprites, generated from 3D models I presume?

You really shouldn't be making this game in raw 2D. When you have fixed perspective a funny thing happens, you can seamlessly mix pre-rendered sprites and backgrounds with live-rendered 3D models, that has been used heavily by some games. If you want such fine animations that seems like the most natural way to do it. Get A 3D engine, configure it to use isometric perspective, and render the objects for which you continue to use sprites as simple flat surfaces with an image on them. And you can use texture compression with a 3D engine, that alone is a big step forward.

I don't think loading and unloading will do a lot for you as you can have pretty much everything on screen at the same time.

# Answer
> 2 votes
Firstly find the most efficient texture format that you can while still being happy with the visuals of the game whether this is RGBA4444, or DXT compression etc. If you are not happy with the artifacts generated into a DXT alpha compressed image, would it be viable to make the images non-transparent using DXT1 compression for the colour combined with a 4 or 8 bit grayscale masking texture for the alpha? I imagine you would stay on RGBA8888 for the GUI.

I advocate breaking things up into smaller textures using whichever format you decided on. Determine the items that are always on screen and therefore always loaded, this might be the terrain and GUI atlases. I would then break up the remaining items that are commonly rendered together as much as possible. I don't imagine you would lose too much performance even going up to 50-100 draw calls on PC but correct me if I'm wrong.

The next step will be to generate the mipmap versions of these textures as someone pointed out above. I would not store them in a single file but separately. So you would end up with 1024x1024, 512x512, 256x256 etc versions of each file and I would do this until I reach the lowest level of detail I would ever want to be displayed.

Now that you have the separate textures you can build a level of detail (LOD) system that loads textures for the current zoom level, and unloads textures if not used. A texture is not being used if the item being rendered is not on screen or is not required by the current zoom level. Try to load the textures into video RAM in a thread separate to the update/render threads. You can display the lowest LOD texture until the required one is loaded. This might sometimes result in a visible switch between a low detail/high detail texture but I imagine this would only be when you perform extremely fast zooming out and in while moving across the map. You could make the system intelligent by attempting to preload where you think the person will move or zoom to and load as much as possible within current memory constraints. You can cache where the user has been until they move away.

That is the sort of thing I would test to see if it helps. I imagine to get extreme zoom levels you will inevitably need an LOD system.

# Answer
> 1 votes
I believe that the best approach is to split the texture in many files and loading them on demand. Probably your problem is that you're trying to load larger textures that you would need for a complete 3D scene and you are using Allegro for that.

For the big zoom-out you want to be able to apply, you have to use mipmaps. Mipmaps are lower-resolution versions of your textures which are used when the objects are far enough from the camera. This means that you could save your 8192x8192 as a 4096x4096 and then another of 2048x2048 and so on, and you switch to the lower resolutions the smaller you see the sprite on the screen. You can both save them as separate textures or resize them when loading (but generating mipmaps during runtime will increase loading times for your game).

A proper management system would load the required files on demand and release the resources when nobody is using them, plus other things. Resource management is an important topic in game development and you're reducing your management to a simple coordinate mapping to a single texture, which is close to having no management at all.

# Answer
> 0 votes
I recommend creating more atlas files that can be compressed with zlib and streamed out of the compression for each atlas, and by having more atlas files and smaller size files you can restrain the amount of active image data in the video memory. Also, implement the triple buffer mechanism so that you are prepping each draw frame sooner and has a chance to complete faster so that the stutters do not appear on the screen.

---
Tags: c++, 2d, memory-efficiency, allegro
---


# Question
Title: Minecraft Modding Errors (.java to .class compression errors)
Recently I started making a personal modpack. I ran into a block ID conflict and decided to fix it. I figured out how, and managed to change a .class file to .java so I was able to edit it. Now comes the issue.

When I try converting my files from .java to .class using the command prompt javac command, I get the following errors:

```
E:\Users\Jeff\Desktop\bettertools_164.s... error: '.' expected /* 3: */ import akc;

E:\Users\Jeff\Desktop\bettertools_164.s... error: ';' expected /* 3: */ import akc;

E:\Users\Jeff\Desktop\bettertools_164.s... error: class, interface, or enum expected /* 4: */ import aqz;

E:\Users\Jeff\Desktop\bettertools_164.s... error: '.' expected /* 5: */ import ard;

E\Users\Jeff\Desktop\bettertools_164.sr... error ';' expected /* 5: */ import ard;

E:\Users\Jeff\Desktop\bettertools_164\b... error: class, interface, or enum expected /* 6: */ import cpw.mods.fml.common.registry.GameRegistr...

```

I'm not sure if that is enough information to solve my problem, but thanks in advance to anyone able to answer it!

# Answer
> 0 votes
To get the .class files of a java project look in your bin folder.

This should work for Eclipse and Netbeans.

---
Tags: java
---


title: What is this type of camera called?

text:
# Question
Title: What is this type of camera called?
I am trying to find a name like "perspective view" of how a camera like this is called:

It is 2d and 3d at the same time. I'm having a hard time trying to find the name.

# Answer
> 6 votes
This is precisely a perspective view. It's a bog standard 3D perspective-view camera -- there's nothing 2D about this at all, and nothing that requires a special name to describe.

The camera is using a standard perspective projection matrix with a real frustum, and is looking into a real 3D scene. Exactly like virtually every 3D game made in the last two decades.

# Answer
> 4 votes
It looks to me like a standard 2D side-scrolling camera. It just happens to be looking into a 3D world and using perspective projection so you get that slight sense of depth. I've seen some people call this a "2D 3D camera" in shorthand, but it doesn't have a standard name.

# Answer
> 1 votes
Games like that are often termed 2.5D and therefore I may be tempted to refer to that camera as a 2.5D side scrolling camera.

Sadly this term can mean a 2D game made to give the illusion of 3D as well as a 3D game that is designed to play and/or look like a 2D game (as in the question's example). However, in both cases the camera is usually locked to a single orientation. So I may also be tempted to call it a "fixed orientation" camera instead.

Games such as Trials Evolution can also be described as 2.5D and are a slight exception to this naming. While the orientation is still fixed, it is only fixed with relation to the track which doesn't have to be fixed to a single plane.

So with all that said, I don't think there is a particularly good name for that kind of camera other than calling it a "Perspective camera with restricted degrees of freedom" or "Fixed orientation perspective camera" or maybe call it a "perspective camera" when detailing it's view type and a "side scrolling camera" when talking about it's movement.

# Answer
> 0 votes
From that image, I see the game world as 3D:

This is a 3D rendering camera, set as Perspective in a 3D world but with a strict 90° or similar angle depending on orientation (axis and local).

# Answer
> -2 votes
I believe it is an orthographic camera you are looking for.

---
Tags: 2d, 3d, camera, terminology
---