# Question
Title: Algorithm for optimising a match game with known queue
I'm trying to write a solver in C# .NET for a game known as Flowerz. For your reference, you can play it on MSN, here: http://zone.msn.com/gameplayer/gameplayer.aspx?game=flowerz. I'm writing it for fun, not for any type of assignment or anything work related. Because of this, the only limit is my computer (an intel i7 core, with 8GB of RAM). It doesn't need to run anywhere else, as far as I'm concerned.

In short, its rules are like this:

* There's a queue filled with coloured flowers. Its length is arbitrary
    + The queue cannot be influenced
    + The queue is generated at the start of the level
* Flowers have either one or two colours.
    + If there are two colours, then there's an outer colour, and an inner colour. In the case of two colours, the outer colour is used for matching.
    + If there is a match, then the outer colour disappears and the flower is now a single colour flower with the same colour as the inner flower
* The goal of the game is to create matches of three (or more) of the same colour
    + When a flower of a single colour is part of a match, it is removed from the playing field, creating an empty space
    + You can match a single colour flower against the outer colour of a two-colour flower. In this case, the single colour flower disappears, the outer colour of two-colour flower disappears and the inner colour remains
* You win the round when the queue is empty *and* there's at least one empty space left over
* Cascading matches are possible. A cascade is when three (or more) outer flowers disappear, and when their inner colours form another chain of 3 (or more flowers).
* The playing field is always 7x7
* Some spaces on the field are covered by rocks
    + You can't place flowers on rocks
* The queue can also contain a spade which you can use to move any placed flower to an unoccupied space
    + You have to use the spade, but you don't actually have to move the flower: it's perfectly legal to place it right back from where it came
* The queue can also contain a coloured butterfly. When you use this butterfly on a flower, then the flower gets the colour of the butterfly
    + Applying a butterfly to a flower with two colours, results in the flower getting only a single colour, namely that of the butterfly
    + You can waste the butterfly on an empty space or a flower which already has this colour
* Clearing the field does not win the game

The goal of the solver is simple: find a way to empty the queue, with as many leftover spaces on the playing field as possible. Basically, the AI plays the game for me. The output of the solver is a list with moves it found. I'm not interested in score, but in surviving as long as possible, hence I'm interested in the moves that leaves as many open spaces as possible.

Needless to say, the search space grows quickly the larger the queue gets, so a brute force is out of the question. The queue starts at 15, and grows with 5 every two or three levels, if I remember right. And, of course, placing the first flower on (0,0) and the second on (0,1) is different from placing the first one on (1,0) and the second flower on (0,0), especially when the field is already populated with flowers from an earlier round. Such a simple decision could make the difference in making it or not.

The questions I have are the following:

* What kind of problem is this? (think travelling salesman, knapsack, or some other combinatorial problem). Knowing this could make my Google-fu a tad better.
* What kind of algorithm could give me good results, fast?

Regarding the latter: At first, I tried to write my own heuristic algorithm (basically: how would I solve it, if I knew queue?), but that results in a lot of edge cases and scoring matching that I might miss.

I was thinking of using a genetic algorithm (because I at least know how to use that...), but I'm having some problems deciding on a binary representation of the board. Then there's the crossover issue, but that can be solved with an ordered crossover operator or a similar type of operation.

My guess is that the solver must always know the board configuration and the queue it's trying to empty.

I know of a few other heuristic algorithms such as neural networks and fuzzy logic systems, but I lack the experience to know which one is best applicable, or if there are others which are better suited for the task at hand.

# Answer
*At first glance*, this seems to me to be a **single agent search problem**. That is: you have one **agent** (the AI "player"). There's a game **state** representing the state of the game board and queue, and you have a **successor function** that can generate new states from a given state.

There's also a **goal criteria** that tells you when the state is the "solved" state. And a **path cost** \- the cost of advancing to a given state (always "1 move" in this case).

One prototypical puzzle of this kind is the 15 Puzzle. And the typical way to solve it is with an **informed search** \- for example, the classic **heuristic** search **A\*** and its variants.

---

However there's a problem with this at-first-glance approach. Algorithms like A\* are designed to give you the shortest path to a goal (for example: smallest number of moves). In your case, the number of moves is always fixed - there is no shortest path - so a heuristic search will just give you *a* path to *a* completed game.

What you want is a sequence of moves that gives you the *best* completed game state.

So what you must do is turn the problem around a bit. Instead of the game board being the "state", the ***sequence of moves*** becomes the "state". (I.e.: Place the items in the queue at positions "D2, A5, C7, B3, A3, ...")

This means we don't really care how those states are generated. The board itself is incidental, required only to evaluate the quality of a given state.

This turns the problem into an **optimisation problem**, which can be solved with a **local search algorithm** (which basically means creating states around a given state, and selecting the best state, without caring about the path between states.)

The prototypical puzzle of *this* kind is the Eight Queens Puzzle.

In this class of problem, you are searching the state space to find a good solution, where "good" is evaluated by an **objective function** (also called an **evaluation function** or, for genetic algorithms, a **fitness function**).

For your problem, an objective function might return a value between 0 and N, for the number of items in the queue that were used up before reaching a failure state (where N is the length of the queue). And, otherwise, a value of N + M, where M is the number of blank spaces left on the board after the queue is empty. As such - the higher the value, the "objectively better" the solution.

(It is worth noting, at this point, that you should optimise the crap out of the code that runs the game - that turns a state into a finished board that can be used for the objective function.)

---

As for examples of **local search algorithms**: The basic pattern is a **hill-climbing** search that takes a given state, mutates it, and moves towards the next state that gives a better result.

Obviously this can get stuck in local maximums (and the like). In this form it's called a **greedy local search**. There are a bunch of variations to deal with this and other issues (Wikipedia has you covered). Some of which (eg: **local beam search**) keep track of multiple states at once.

One particular variation on this is the **genetic algorithm** (Wikipedia). The basic steps for a genetic algorithm are:

1. Determine some way to convert a state into a string of some kind. In your case this might be a string of queue-length digits from 1 to 49 (representing all the possible placements on a 7x7 board, probably stored 1 byte each). (Your "spade" piece could be represented by two subsequent queue entries, for each phase of the move.)
2. Randomly select a breeding population, giving higher probability to states that have better **fitness**. The breeding population should be the same size as the original population - you can choose states from the original population multiple times.
3. Pair up states in the breeding population (first goes with second, third goes with fourth, etc.)
4. Randomly select **crossover** points for each pair (a position in the string).
5. Create two offspring for each pair by swapping the portion of the string after the crossover point.
6. Randomly mutate each of the offspring states. For example: randomly choose to change a random position in the string to a random value.
7. Repeat the process with the new population until the population converges on one or more solutions (or after a given number of generations, or a sufficiently good solution is found).

---

A genetic algorithm solution feels like it *might* be appropriate for your problem - with some adjustment. The biggest difficulty I see is that, with the above string representation, you will find that switching the tail halves of states with very different front halves is likely to result in "dead" states (due to conflicting moves between the two halves, that result in a low fitness score).

Perhaps it is possible to overcome this problem. One idea that comes to mind is making it more likely for states with similar front-halves to become breeding pairs. This could be as simple as sorting the breeding population of states, before pairing them up. It may also help to gradually move the likely position of the crossover, from the start to the end of the string, as the generation number increases.

It may also be possible to come up with a representation of moves within a state that is more resistant (perhaps even entirely immune) to encountering the "square is full" failure state. Perhaps representing moves as relative coordinates from the previous move. Or having moves select the closest empty space to the given position.

As with all non-trivial AI problems like this, it will require some significant tinkering.

And, as I mentioned before, the other major challenge is simply optimising your objective function. Making this faster will allow you to search a large amount of space, and to search for solutions to games with longer queues.

---

For this answer, particularly to get all the terminology right, I had to dig out my university AI textbook, "Artificial Intelligence: A Modern Approach" by Russell and Norvig. Not sure if it's "good" (I don't have any other AI texts to compare it with), but it's not bad. At least it's quite big ;)
> 9 votes

# Answer
## Categorization

The Answer isn't easy. The game theory has some classifications for games, but there seems to be no clear 1:1-match for that game to a special theory. It's a special form of combinatorial problem.

It's not traveling salesman, which would be deciding for an order in which you visit "nodes" with some cost to reach the next node from the last one. You can't reorder the queue, nor do you have to use all fields on the map.

Knapsack doesn't match because some fields become empty while putting some items into the "knapsack". So it's maybe some extended form of that, but most possibly the algorithms will not be applicable because of this.

Wikipedia gives some hints on categorization here: http://en.wikipedia.org/wiki/Game\_theory#Types\_of\_games

I would categorize it as "discrete-time optimal control problem" (http://en.wikipedia.org/wiki/Optimal\_control), but I don't think this will help you.

## Algorithms

In case you really know the complete queue, you could apply tree search algorithms. As you said, the complexity of the problem grows very fast with the queue length. I suggest to use an algorithm like "Depth-first search (DFS)", which doesn't require much memory. As the score does not matter to you, you could just stop after having found the first solution. To decide which sub-branch to search first, you should apply a heuristic for ordering. That means you should write an evaluation function (e.g.: number of empty fields; the more sophisticated this one is, the better), that gives a score to compare which very next move is the most promising.

You then only need the following parts:

1. model of the game state, that stores all information of the game (e.g. board status / map, queue, move number / position in queue)
2. a move generator, which gives you all valid moves for a given game state
3. a "do move" and a "undo move" function; which apply / undo a given (valid) move to a game state. Whereas the "do move" function should store some "undo information" for the "undo" function. Copying the game state and modifying it in each iteration does slow down the search significantly! Try at least to store the state on the stack (= local variables, no dynamic allocation using "new").
4. an evaluation function, which gives a comparable score for each game state
5. search function

Here is an incomplete reference implementation for depth-first search:

```
public class Item
{
    // TODO... represents queue items (FLOWER, SHOVEL, BUTTERFLY)
}

public class Field
{
    // TODO... represents field on the board (EMPTY or FLOWER)
}

public class Modification {
    int x, y;
    Field originalValue, newValue;

    public Modification(int x, int y, Field originalValue, newValue) {
        this.x = x;
        this.y = y;
        this.originalValue = originalValue;
        this.newValue = newValue;
    }

    public void Do(GameState state) {
        state.board[x,y] = newValue;
    }

    public void Undo(GameState state) {
        state.board[x,y] = originalValue;
    }
}

class Move : ICompareable {

    // score; from evaluation function
    public int score;

    // List of modifications to do/undo to execute the move or to undo it
    Modification[] modifications;

    // Information for later knowing, what "control" action has been chosen
    public int x, y;   // target field chosen
    public int x2, y2; // secondary target field chosen (e.g. if moving a field)

    public Move(GameState state, Modification[] modifications, int score, int x, int y, int x2 = -1, int y2 = -1) {
        this.modifications = modifications;
        this.score = score;
        this.x = x;
        this.y = y;
        this.x2 = x2;
        this.y2 = y2;
    }

    public int CompareTo(Move other)
    {
        return other.score - this.score; // less than 0, if "this" precededs "other"...
    }

    public virtual void Do(GameState state)
    {
        foreach(Modification m in modifications) m.Do(state);
        state.queueindex++;
    }

    public virtual void Undo(GameState state)
    {
        --state.queueindex;
        for (int i = m.length - 1; i >= 0; --i) m.Undo(state); // undo modification in reversed order
    }
}

class GameState {
    public Item[] queue;
    public Field[][] board;
    public int queueindex;

    public GameState(Field[][] board, Item[] queue) {
        this.board = board;
        this.queue = queue;
        this.queueindex = 0;
    }

    private int Evaluate()
    {
        int value = 0;
        // TODO: Calculate some reasonable value for the game state...

        return value;
    }

    private List<Modification> SimulateAutomaticChanges(ref int score) {
        List<Modification> modifications = new List<Modification>();
        // TODO: estimate all "remove" flowers or recoler them according to game rules
        // and store all changes into modifications...
        if (modifications.Count() > 0) {
            foreach(Modification modification in modifications) modification.Do(this);

            // Recursively call this function, for cases of chain reactions...
            List<Modification> moreModifications = SimulateAutomaticChanges();

            foreach(Modification modification in modifications) modification.Undo(this);

            // Add recursively generated moves...
            modifications.AddRange(moreModifications);
        } else {
            score = Evaluate();
        }

        return modifications;
    }

    // Helper function for move generator...
    private void MoveListAdd(List<Move> movelist, List<Modifications> modifications, int x, int y, int x2 = -1, int y2 = -1) {
        foreach(Modification modification in modifications) modification.Do(this);

        int score;
        List<Modification> autoChanges = SimulateAutomaticChanges(score);

        foreach(Modification modification in modifications) modification.Undo(this);

        modifications.AddRange(autoChanges);

        movelist.Add(new Move(this, modifications, score, x, y, x2, y2));
    }

    private List<Move> getValidMoves() {
        List<Move> movelist = new List<Move>();
        Item nextItem = queue[queueindex];
        const int MAX = board.length * board[0].length + 2;

        if (nextItem.ItemType == Item.SHOVEL)
        {

            for (int x = 0; x < board.length; ++x)
            {
                for (int y = 0; y < board[x].length; ++y)
                {
                    // TODO: Check if valid, else "continue;"

                    for (int x2 = 0; x2 < board.length; ++x2)
                    {
                        for(int y2 = 0; y2 < board[x].length; ++y2) {
                            List<Modifications> modifications = new List<Modifications>();

                            Item fromItem = board[x][y];
                            Item toItem = board[x2][y2];
                            modifications.Add(new Modification(x, y, fromItem, Item.NONE));
                            modifications.Add(new Modification(x2, y2, toItem, fromItem));

                            MoveListAdd(movelist, modifications, x, y, x2, y2);
                        }
                    }
                }
            }

        } else {

            for (int x = 0; x < board.length; ++x)
            {
                for (int y = 0; y < board[x].length; ++y)
                {
                    // TODO: check if nextItem may be applied here... if not "continue;"

                    List<Modifications> modifications = new List<Modifications>();
                    if (nextItem.ItemType == Item.FLOWER) {
                        // TODO: generate modifications for putting flower at x,y
                    } else {
                        // TODO: generate modifications for putting butterfly "nextItem" at x,y
                    }

                    MoveListAdd(movelist, modifications, x, y);
                }
            }
        }

        // Sort movelist...
        movelist.Sort();

        return movelist;
    }

    public List<Move> Search()
    {
        List<Move> validmoves = getValidMoves();

        foreach(Move move in validmoves) {
            move.Do(this);
            List<Move> solution = Search();
            if (solution != null)
            {
                solution.Prepend(move);
                return solution;
            }
            move.Undo(this);
        }

        // return "null" as no solution was found in this branch...
        // this will also happen if validmoves == empty (e.g. lost game)
        return null;
    }
}

```

This code isn't verified to work, nor is it compileable or complete. But it should give you an idea how to do it. The most important work is the evaluation function. The more sophisticated it is, the the wrong "tries" the algorithm will try (and have to undo) later. This extremely reduces the complexity.

If this is too slow you can also try to apply some methods of two-person-games as HashTables. For that you'll have to calculate an (iterative) hash key for each game state that you evaluate and mark states that do not lead to a solution. E.g. every time before the Search() method returns "null" a HashTable entry must be created and when entering Search() you'd check if this State has been already reached so far with no positive result and if so return "null" without further investigation. For this you'll need a huge hash table and would have to accept "hash collisions" which could cause that you probably don't find a existing solution, but which is very unlikely, if your hash functions is good enough and your table is big enough (its a risk of calculate-able risk).

I think there is no other algorithm to solve this problem (as described by you) more efficient, assumed your evaluation function is optimal...
> 2 votes

---
Tags: c#, algorithm, ai, puzzle
---


# Question
Title: How can I render an .stl file in XNA or Monogame?
How should I go about rendering a .stl file as a 3d model in XNA? The .stl file contains a bunch of triangles that add up to a solid mesh. I have already figured out how to read the contained data. The file firstly contains the amount of facets. The file then consists of groups of data that represent the triangles. For each triangle the is a normal and 3 vectors that represent the 3 corners of the triangle.

My question is how I should go about rendering theses triangles in XNA. I guess I have to use a vertex buffer or something but I have almost no experience with 3D at all. Could someone please help?

# Answer
> 8 votes
Here is a tutorial on using vertex and index buffers in XNA; vertex buffers are probably the ideal way to approach this, but if that seems a bit daunting to you right now you could use the simpler `DrawUserPrimitives` function. A related tutorial outlines that process.

Essentially, you'll want extract the vertex data from the `.stl` file (the format is described here). The most straightforward way to do this is probably to call File.ReadAllLines and parse the data line-by-line, assuming you are using the ASCII version of `.stl` (otherwise try File.ReadAllBytes). The `File` methods may not be available to you if you want to deploy to the 360, though.

You turn each vertex in the `.stl` file into an appropriate vertex structure in your C# code, write that vertex into a vertex buffer or an array of vertex objects you're going to use `DrawUserPrimitives` with, and then draw the buffer or call `DrawUserPrimitives`.

The `.stl` format doesn't appear to support indexed data, so you don't need to worry about index buffers, although you could in theory look for duplicate vertex data as you load and build an index buffer that way (I wouldn't recommend trying this first though, keep it simple).

---
Tags: xna, c#, 3d-meshes, monogame, windows-phone-8
---


title: How to play animations (GIF, SWF... )?

text:
# Question
Title: How to play animations (GIF, SWF... )?
I have many diffrent animations made with flash.
I can make it as (1).SWF, (2).GIF or as (3).PNG (every Frame per second).
Searched in google... but coudn't find anything usefull.

1. SWF: For SWF i need Flash on the android phone... this is something new to me and because of that i woudn't prefer a solution with that.
**-\> I heard that Flash is not supported on Android for a long time, so this does not work.**
2. GIF: If that is possible it woud be very nice. I'm thinking of something like "animation1.start();".
**But i heard that android can't handle GIF.. -.-**
3. PNG: I know how to animate many .png pictures with an animationdrawable but when i export the animations into a .png for every frame in the second... imagion how many pictures i have. The problem is that i can't make subdirectorys in the drawable folder. Why? I don't have a clue. :/ But realy, that woud suck.

Do anyone have any solution to that than pls feel free to tell me. :)

**Edit:** I didn't finde a easy solution so i will make it with animationdrawables.
If you have a solution... pls pls answer here :)

# Answer
> 4 votes
Export to PNG and use a texture packer to create one texture-atlas/spritesheet.

https://code.google.com/p/libgdx-texturepacker-gui/
or
http://www.codeandweb.com/texturepacker

These texturepacker export a text file( usually a json file ). This file contains all coordinate data. If you plan on using your own implementation look at the LibGDX source code and see how its making use of texture packer files.

Edit:

Because you are rather new to gamedev, it would be way easier if you just used LibGDX. If you insist on doing your own things then:

With libgdx-texturepacker-gui: first you need to understand how json works. If i'm not mistaken in the package android.util there should be a jsonreader class. You need to parse the json file and read the coordinates you need to clip the image with when you draw it. There is an example that comes with the zip file called "test-me". It shows how to pack textures.

Open the project in that folder and hit : Pack selected. It will create some files in the output folder. It will create a png ( your sheet/atlas ) and .pack file ( your json file you can open it with notepad or any other text editor and read what created based on those images)

For animations you need to do some extra work, because you create sequences based on the region names ( that's why you just need to use something like libgdx, it's all done for you).

withtexturepacker: There are several formats it can export too, but that's up to you. Same story as above you need to parse the file and need to create a function to get the region you want.

Alternatively you don't use a texture packer and create the texture atlas yourself by placing the images uniform in a sequence like so:

```
[][][][][]        <---- animation 1 : 5 frames
[][][]            <---- animation 2 : 3 frames
[][][][][][][][]  <---- animation 3 : 8 frames
[][]              <---- animation 4 : 2 frames

```

But you will not only waste space on your atlast ( meaning it might consume more memory ), you still have to write something that disects every sequence.

# Answer
> 5 votes
Alternatively to texture packing, you could simply load each frame one at a time and stream them with animation. SpriteSheets are not required, although they can (not always) save on memory.

# Answer
> 1 votes
To use SWF, you don't need Flash Player or anything from Adobe. Just make your own parser / interpreter, specification is open and available here http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/swf/pdf/swf-file-format-spec.pdf

---
Tags: java, android, animation, swf, png
---


# Question
Title: OpenGL ES2: Changing Z doesn't appear to change the location of triangle
So I am very new to OpenGL out I am playing around and trying to create a rectangle.

```
GLfloat vVertices[] = { -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.5f, -0.5f,
                0.0f,0.5f,0.5f,0.0f};
GLfloat colors[] = {
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f,
            1.0f, 0.0f, 0.0f, 1.0f};
glClear(GL_COLOR_BUFFER_BIT);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vVertices);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, colors);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

```

But when I try to make the top further back than the bottom by increasing the z of 2 and 4....

```
GLfloat vVertices[] = { -0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 1.0f, 0.5f, -0.5f,
                0.0f,0.5f,0.5f,1.0f};

```

I would expect the top to be larger than the bottom because it would be closer. This isn't what happens, instead it just looks like a regular old square. What am I missing here? From a little research online it looks like I might need to setup a frustum, however, I am not sure how to do that on GLES2. I tried the following...

```
glDepthRangef(-2.0f,2.0f);

```

But that didn't help either.

**Update**

Here is my function to set my projection ortho...

```
void glOrthof(float left, float right, float bottom, float top, float near, float far){
        LOGD("In glOrtho");
        float a = 2.0f / (right - left);
        float b = 2.0f / (top - bottom);
        float c = -2.0f / (far - near);

        float tx = - (right + left)/(right - left);
        float ty = - (top + bottom)/(top - bottom);
        float tz = - (far + near)/(far - near);

        float ortho[16] = {
            a, 0, 0, 0,
            0, b, 0, 0,
            0, 0, c, 0,
            tx, ty, tz, 1
        };

        GLint loc1= glGetUniformLocation(programObject, "project");
        glUniform1i(loc1, 1.0f);
        GLint projectionUniform = glGetUniformLocation(programObject, "Projection");
        glUniformMatrix4fv(projectionUniform, 1, 0, &ortho[0]);
        LOGD("In finished glOrtho");
}

```

Vertex Shader...

```
 GLbyte vShaderStr[] =
    "attribute vec4 vPosition;   \n"
    "uniform mat4 Projection;   \n"
    "uniform vec4 color;   \n"
    "attribute vec4 inColor;   \n"
    "varying vec4 fragColor;   \n"
    "uniform int project;  \n"
    "void main()                 \n"
    "{                           \n"
    "   if(project == 0){ \n"
    "     gl_Position = vPosition; \n"
    "   } \n"
    "   else{ \n"
    "     gl_Position = Projection * vPosition; \n"
    "   } \n"
    "   fragColor = inColor; \n"
    "}                           \n";

```

And finally my call

```
glOrthof(0, widthScreen, heightScreen, 0, 2.0, -2.0);

```

**UPDATE 2**

per here I tried the following vertex shader...

```
GLbyte vShaderStr[] =
    "attribute vec4 vPosition;   \n"
    "uniform mat4 Projection;   \n"
    "uniform mat4 Projection2;   \n"
    "uniform vec4 color;   \n"
    "attribute vec4 inColor;   \n"
    "varying vec4 fragColor;   \n"
    "uniform int project;  \n"
    "void main()                 \n"
    "{                           \n"
    "   if(project == 0){ \n"
    "     gl_Position = vPosition; \n"
    "   } \n"
    "   else{ \n"
    "     gl_Position = Projection2 * (Projection * vPosition); \n"
    "   } \n"
    "   fragColor = inColor; \n"
    "}                           \n";

```

And the following additional function...

```
void glFrustumf(float near, float far){
        LOGD("In glOrtho");
        float angleOfView = 180.0;
        float aspectRatio = 1;

        // Some calculus before the formula.
        float size = near * tanf(degree2Radian(angleOfView) / 2.0);
        float left = -size, right = size, bottom = -size / aspectRatio, top = size / aspectRatio;
        float a = 2.0f * near / (right - left);
        float b = 2.0f *near / (top - bottom);
        float c = (-2.0f*far*near) / (far - near);

        float tx = - (right + left)/(right - left);
        float ty = - (top + bottom)/(top - bottom);
        float tz = - -(far + near)/(far - near);

        float ortho[16] = {
            a, 0, 0, 0,
            0, b, 0, 0,
            tx, ty, tz, -1,
            0, 0, c, 0
        };

        GLint loc1= glGetUniformLocation(programObject, "project");
        glUniform1i(loc1, 1.0f);
        GLint projectionUniform = glGetUniformLocation(programObject, "Projection2");
        glUniformMatrix4fv(projectionUniform, 1, 0, &ortho[0]);
        LOGD("In finished glOrtho");
}

```

But nothing shows up when I add the new matrix.

# Answer
You're using an orthographic projection matrix, which does not do perspective (things getting smaller in the distance). You need to use some kind of perspective projection matrix.

Libraries like GLM are intended to make this easy.

Here is an explanation of what is going on mathematically.
> 1 votes

---
Tags: opengl-es2
---


# Question
Title: XNA 3d model mesh.draw() throws TextureCoordinate0 is missing error
I've downloaded a bunch of 3d models from turbosquid.com. The majority of the one's I've downloaded are simply .fbx files. When I load the model into my game and run it, the following error is thrown in `mesh.draw()`:

```
An unhandled exception of type 'System.InvalidOperationException' occurred in Microsoft.Xna.Framework.Graphics.dll

Additional information: The current vertex declaration does not include all the elements required by the current vertex shader. TextureCoordinate0 is missing.

```

All the answers I've found online seem to tell people to reexport the model, or change something in the shader. I don't have access to these, just the fbx file. What can I do?

# Answer
> 2 votes
As an alternative to adding textures to your model, you can stop the default `BasicEffect` from looking for them when drawing.

```
//foreach BasicEffect basicEffect in model.mesh[n].effects ....

basicEffect.TexturesEnabled = false;

//begin effect pass...

```

# Answer
> 0 votes
Your model is missing the Texture Coordinates. You need to unwrap the model in a 3D modeling program, then export it.

---
Tags: xna, 3d-meshes, fbx
---


# Question
Title: Error instantiating Texture2D in MonoGame for Windows 8 Metro Apps
I have an game which builds for WindowsGL and Windows8. The WindowsGL works fine, but the Windows8 build throws an error when trying to instantiate a new Texture2D.

The Code:

```
var texture = new Texture2D(CurrentGame.SpriteBatch.GraphicsDevice, width, 1); // Error thrown here...
texture.setData(FunctionThatReturnsColors());

```

You can find the rest of the code on Github.

The Error:

```
SharpDX.SharpDXException was unhandled by user code
  HResult=-2147024809
  Message=HRESULT: [0x80070057], Module: [Unknown], ApiCode: [Unknown/Unknown], Message: The parameter is incorrect.

  Source=SharpDX
  StackTrace:
       at SharpDX.Result.CheckError()
       at SharpDX.Direct3D11.Device.CreateTexture2D(Texture2DDescription& descRef, DataBox[] initialDataRef, Texture2D texture2DOut)
       at SharpDX.Direct3D11.Texture2D..ctor(Device device, Texture2DDescription description)
       at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height, Boolean mipmap, SurfaceFormat format, Boolean renderTarget)
       at Microsoft.Xna.Framework.Graphics.Texture2D..ctor(GraphicsDevice graphicsDevice, Int32 width, Int32 height)
       at BrewmasterEngine.Graphics.Content.Gradient.CreateHorizontal(Int32 width, Color left, Color right) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Graphics\Content\Gradient.cs:line 16
       at SampleGame.Menu.Widgets.GradientBackground.UpdateBounds(Object sender, EventArgs args) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Menu\Widgets\GradientBackground.cs:line 39
       at SampleGame.Menu.Widgets.GradientBackground..ctor(Color start, Color stop, Int32 scrollamount, Single scrollspeed, Boolean horizontal) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Menu\Widgets\GradientBackground.cs:line 25
       at SampleGame.Scenes.IntroScene.Load(Action done) in c:\Projects\Personal\GitHub\BrewmasterEngine\SampleGame\Scenes\IntroScene.cs:line 23
       at BrewmasterEngine.Scenes.Scene.LoadScene(Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\Scene.cs:line 89
       at BrewmasterEngine.Scenes.SceneManager.Load(String sceneName, Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\SceneManager.cs:line 69
       at BrewmasterEngine.Scenes.SceneManager.LoadDefaultScene(Action`1 callback) in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Scenes\SceneManager.cs:line 83
       at BrewmasterEngine.Framework.Game2D.LoadContent() in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Framework\Game2D.cs:line 117
       at Microsoft.Xna.Framework.Game.Initialize()
       at BrewmasterEngine.Framework.Game2D.Initialize() in c:\Projects\Personal\GitHub\BrewmasterEngine\BrewmasterEngine\Framework\Game2D.cs:line 105
       at Microsoft.Xna.Framework.Game.DoInitialize()
       at Microsoft.Xna.Framework.Game.Run(GameRunBehavior runBehavior)
       at Microsoft.Xna.Framework.Game.Run()
       at Microsoft.Xna.Framework.MetroFrameworkView`1.Run()
  InnerException:

```

Is this an error that needs to be solved in MonoGame, or is there something that I need to do differently in my engine and game?

# Answer
> 1 votes
This is actually an issue in MonoGame, if it was properly supporting the GraphicsProfiles introduced in XNA 4.0 the MaxTextureSize would be 2048 for `Reach` and 4096 for `HiDef`. You can check the Capabiities of your hardware by querying through SharpDX directly. Once you have access to a `D3D9Driver` instance, you'll have to create this yourself as I don't think there's a way to get from MonoGame, use the `D3D9DeviceCaps` to query the `MaxTextureWidth` and `MaxTextureHeight`.

# Answer
> 2 votes
~~Turns out the issue was not initializing and loading content in the correct order.~~ I am building an engine and had to refactor it to work as a library for Windows 8 apps. When I shuffled some code around I removed some XNA-specific code and put in back in the wrong place.

Here's the basic flow of things:

1. `Constructor`
    * Instantiate `GraphicsDeviceManage`
    * Set `Content.RootDirectory` (optional)
2. `Initialize`
    * Update graphics options (optional)
3. `LoadContent`
    * Instantiate `SpriteBatch`, using your `GraphicsDeviceManage` from before
    * Load the content for the game.

**Update:**

The actual error was that the texture I was trying to create was too big on the Surface RT. After looking in to it a bit, this is related to the graphics card and driver. My Surface RT has a limit of 2048(211), but my laptop goes up to 8192(213).

Here is a snippet that allows you to determine the maximum texture size based on each device and 'caches' the result. (PLEASE update it if you know a more elegant way!)

```
/// <summary>
/// Max texture size supported by the current device.
/// </summary>
public static int MaxTextureSize
{
   get
    {
        if (maxTextureSize == 0)
            maxTextureSize = CalculateMaxTextureSize();
         return maxTextureSize;
    }
}
private static int maxTextureSize;
private static int CalculateMaxTextureSize()
{
    var maxSize = 0;
    var i = 8;
    while (i < 20)
    {
        try
        {
            var size = (int)Math.Pow(2, i);
            new Texture2D(SpriteBatch.GraphicsDevice, size, 1);
            maxSize = size;

            size++;
            new Texture2D(SpriteBatch.GraphicsDevice, size, 1);
            maxSize = size;
        }
        catch (Exception e)
        {
            break;
        }
        i++;
    }
    return maxSize;
}

```

If you know the maximum size of a texture then you can just scale accordingly!

---
Tags: xna, monogame, sharpdx, windows-8
---


# Question
Title: Resize a texture using the full SpriteBatch.Draw in XNA
I'm using the full Spritebatch.Draw function to draw my explosion sprite since I also need rotation. I am using the Scale value to resize my texture, but I can't get it to be accurate.

I want to be able to set the textures Size to a specific pixel size, width/height are exactly the same. Say the texture is 128x128, and I want to resize it to be 23x23.

Heres my current code:

```
  Vector2 Scale = new Vector2((float)sprite.Area.Width / (float)sprite.Texture.Width, (float)sprite.Area.Height / (float)sprite.Texture.Height);
            spriteBatch.Draw(sprite.Texture, sprite.Position, null, sprite.Color * sprite.Alpha, (float)Math.Atan2(sprite.Angle.Y, sprite.Angle.X), new Vector2(sprite.Area.Width / 2, sprite.Area.Height / 2), Scale, SpriteEffects.None, 0f);

```

I have the Area set to be the size I want it at, however the Draw function seems to not be drawing it to the exact size.

# Answer
Since it looks like you are using the `Scale` parameter, you will need to calculate the correct scale value based on the original and target size. Since the `Scale` parameter is a float, and not a pixel size, you'll need to calculate the percentage your target is of your source.

> If your resource is 128x128, and you draw at scale `1.0f`, your output will be 128x128.
>
> If your resource is 128x128, and you draw at scale `0.5f`, your output will be 64x64.
>
> If your resource is 128x128, and you draw at scale `0.179f`, your output will be 23x23 (rounding may make this slightly different, adjust scale accordingly.

The formula for uniform scaling as you are asking, would be `Scale = TargetSize/SourceSize`.

For additional information, and alternate approaches (i.e. using a destination rectangle instead of a scaling factor) see this MSDN article.
> 2 votes

# Answer
In the *destination* variable of Draw() use a new Rectangle() so that you can specify the not just the position of the draw but the size also.

Rectangles properties

```
Height  Specifies the height of the rectangle.
Width   Specifies the width of the rectangle.
X       Specifies the x-coordinate of the rectangle.
Y       Specifies the y-coordinate of the rectangle.

```

Use X,Y for the location and Height,Width for the size.
> 1 votes

---
Tags: xna, rendering
---


# Question
Title: Converting double "perlin noise" value to a set of colors
I've been working all day at learning perlin and other methods for generating terrain. I have a 2d top-down game and I need to generate random regions of connected colors. I've been playing with existing implementations - some worked very well, some didn't. My main problem was that several implementations were very inconsistent and were not returning the same noise number for a coordinate - something that's important to me.

I finally landed on an implementation of Simplex I like, and with all of my tests it's generating the same noise value for every coordinate properly.

However, the noise values are doubles with unknown ranges, for example:

```
x:1525 y:1125 Noise: 0.0
x:1525 y:1150 Noise: 0.2764424964813472
x:1525 y:1175 Noise: 0.02497111685822111
x:1525 y:1200 Noise: 0.22943575651784293
x:1525 y:1225 Noise: -0.498659492513381
x:1525 y:1250 Noise: -0.9257368870408553
x:1525 y:1275 Noise: 0.2976243577485172

```

I have a list of a dozen initial tile colors and am stumped as to best way to ensure that I can safely choose a color from the range based on the noise value.

Secondary question if possible - if anyone knows how I can change the above class to compute the noise values by using a seed (to eventually allow people to generate specific maps with known seeds)

# Answer
> 5 votes
The noise values are between -1 and 1. Simply set specific ranges to be certain colors. You can do this a few different ways:

**Method One**

```
if ( noise <= -0.5 ) {
    //color 1
} else if ( noise <= 0 ) {
    //color 2
} else if ( noise <= 0.5 ) {
    //color 3
} else {
    //color 4
}

```

**Method Two**

```
noise = ( noise + 1 ) / 2.0; //noise is now between 0 and 1
if ( noise <= 0.25 ) {
    //color 1
} else if ( noise <= 0.5 ) {
    //color 2
} else if ( noise <= 0.75 ) {
    //color 3
} else {
    //color 4
}

```

**Method Three**

```
//assume colors is an array of colors
noise = ( noise + 1 ) / 2.0; //noise is now between 0 and 1
color = colors[ Math.floor(noise * colors.length) ];

```

These methods are some ways to turn noise into regions by using the *elevation* of the noise.

**Random Seeds** *via http://www.cs.geneseo.edu/~baldwin/reference/random.html*

```
Random generator2 = new Random( 19580427 );

```

# Answer
> 1 votes
**Indexed color**

to pick a color based on a noise value, you just have to convert a range into a set of discrete values.

```
allColors = { Color(0,0,0), Color(255,255,255) ... } // etc
min= -1;
max= 1;
index = (int)(allColors.length() * (noisevalue - min) / (max - min));
color = allColors[index];

```

**Random Seed**

The randomness comes from the permutation table defined in `private static final int[] p = { 151, 160, ... };`. Simply use a random number generator initialized to a particular seed to shuffle all the integers from 0-255 instead of the fixed value you have there.

---
Tags: java, perlin-noise
---


title: Giving the update function a history

text:
# Question
Title: Giving the update function a history
I am using Unity but this is an issue, that can be applied to every programming language.

I only have one Update-Function.

```
function Update ()
{

}

```

This function runs each frame. If I want to include a history, like "Has player already been at x, show z, else show g" I work with

```
function Update ()
{
  if(playerwasatx == true)
  {
    showz = true;
  }
  else
  {
    showg = true;
  }
  if (showg == true)
  ...

  if (showz == true)
  ...

}

```

You get the idea. Losing track is just too easy. Which approach helps me include a history, like an animation to be played.

For instance(pseudocode)

task1: if player is at z, play animation xy smoothly. If something interrupts animation xy by entering object u's space, do m

task2: if it's already night in the game(night == true), move person a to position b, then let him wait there for a certain amount of time(time = x) until night is false again.

All of this can be solved with if then else but to not lose track, which approach is more human friendly?

# Answer
It kind of sounds like you're doing things on update that should be done on trigger. Let's take an example I thought of:

You want a particular puzzle-related light to shine much more brightly if the hero is standing in a particular spot in the room, to alert his attention to it.

You probably shouldn't be checking each frame whether he's there; you should be setting up a system of triggers, with functions like 'onEnter', or 'onLeave'.

```
onEnter: function() {
  shineEffect.visible = true;
}
onLeave: function() {
  shineEffect.visible = false;
}

```

I'll also try to extend the idea of the "has been to" sample. Let's say the hero got a new ability after visiting an oracle, and for the rest of the game, it's in his HUD. I'd imagine your current code might say:

```
drawHUD: function() {
  drawHealth();
  drawMagic();
  if (hero.hasVisitedOracle) {
    drawSpiritSummon();
  }
}

```

Your target might be something like this;

```
drawHUD: function() {
  foreach(var hudElement in hudStuff) {
  hudElement.draw()
}

onVisitOracle: function() {
  userMessage('You got the "Song of Spirits"! You can now [Summon Spirits] at any time.');
  hudStuff.add(new SpiritSongHudElement());
}

```

It kind of sounds like you're trying to make the transition to event-based programming. You're right to think it weird to be doing so many 'if' checks in an Update loop. Really stingy programmers (not practical ones) pride themselves on not using any 'if's, ever, in routine logic.
> 1 votes

# Answer
@Zurechtweiser

Going from what you wrote:

> It's about procedural animations. For instance, I want to move a character from A to B. As soon as he is at B, he should rotate around 20°. Then he should wait for event z to happen.

It would be prudent to follow the Single Responsibility Principle. The principle states that a class, or in this case an object, should have a single responsibility, and that responsibility should be encapsulated entirely in that class/object.

What I mean by this is that the character object should know how to move from A to B, should know how to rotate 20 degrees, and should know what to do after event Z. How the character "knows" these things can be represented by different methods inside the character 'object'. For example, you could have the following method in a script attached to the character gameObject:

```
rotateCharacter(rotateTo : Transform)
{
     // implement code to rotate character
}

```

However, the character shouldn't know **when** to rotate, just **how** to rotate. That's an important distinction. By following the Single Responsibility Principle, it is more object oriented to have another object, for example a gameController object, know **when** the character should be doing certain things. The character's Update() function isn't the best place to put code that controls event timing and animations in your game. You don't have to worry about having a "history" inside the character object's Update() function, when that implementation should be in another object all together; possibly stored as game state information.

You can read more about the Single Responsibility Principle here: http://en.wikipedia.org/wiki/Single\_responsibility\_principle
> 0 votes

---
Tags: unity, software-engineering, metaprogramming
---


# Question
Title: How to implement SDL Button/Menu GUI with callbacks?
I have been reading Bjarne Stroustrup's Programming Principles and Practice Using C++ for a while now and am nearing the end of the book. I have to tried to make a very simple game using the SDL libraries as a little exercise to practice programming and utilize techniques from the book.

I've attempted to implement a rather crude GUI system that sort of resembles the one described in the book. The problem that I am having is implementing a callback system so that when a button is constructed it takes a member function as an argument so that it can be called when the button pressed. The reason why it needs to be a member function is that the game has a state system very similar to this http://gamedevgeek.com/tutorials/managing-game-states-in-c/ since I followed the tutorial when crafting my own game state system.

The existing code looks like this:

```
class Button : public Widget {
private:
    SDL_Surface* m_image;
    SDL_Rect* m_clip;
    bool m_pressed;
    bool m_released;
    int frame;
public:
    Button(int x, int y, int w, int h, SDL_Surface* img, SDL_Rect* clip);
    void handle_events(SDL_Event& event);
    void show(SDL_Surface* screen, GameState* state);
    bool released();
};

Button::Button(int x, int y, int w, int h, SDL_Surface* img, SDL_Rect* clip)
   :Widget(x,y,w,h),
   m_image(img),
   m_pressed(0),
   m_released(0),
   m_clip(clip),
   frame(0)
{
}

```

So my question is: *How do you pass a function in the constructor and call it when the button is pressed?* (Like a callback). Currently each state, for example a Menu state, will just look if a button is pressed and perform a corresponding task which is pretty bad and hardly readable.

Stroustrup's code for the GUI system in the PPP book can be found here: http://www.stroustrup.com/Programming/Graphics/ in the two GUI files.

Thanks in advance.

# Answer
> 4 votes
If you want simple callbacks, you can just use normal C function pointers. You can see here a small tutorial on them: http://www.learncpp.com/cpp-tutorial/78-function-pointers/

So, in your case you'd add a parameter like `void (*clickedCallback)()` in the ctor of the Button. Then, when it is clicked you'd call the function your saved before: `m_clickedCallback();`

Optionally, you might want to send the button which called the callback as argument. The definition/calling will become:

```
void (*m_clickedCallback)(const Button&);
// ...
m_clickedCallback(*this);

```

LE: On a second read, it seems you might want a member function (not a simple one). That is slightly more complicated, because you'd have to pass the **object** instance around when you want to call its method. More info on this topic you can find on Parashift's superb website: http://www.parashift.com/c++-faq/pointers-to-members.html.

Basically you'd need some sort of wrapper/struct that holds both the function to a member (similarly to the C one, but with the class specified) and the member instance where to call the callback function on.

# Answer
> 5 votes
The more modern way of doing it is by using delegates or functors.

C++11 has them built in: http://en.cppreference.com/w/cpp/utility/functional/function They're also a part of Boost if you're using an older compiler: http://www.boost.org/doc/libs/1\_53\_0/doc/html/function.html

Or if you want something a little more streamlined you can use something like FastDelegate: http://www.codeproject.com/Articles/7150/Member-Function-Pointers-and-the-Fastest-Possible

---
Tags: c++, sdl, gui
---


# Question
Title: When do assets get loaded into video memory?
Specifically when do textures / geometry load into video memory? Do objects need to be in a direct line of sight (on screen) or are they drawn in at a certain camera radius?

Obviously thing like mipmaps and LODs are progressively loaded depending on camera position, but will those assets occupy video memory if they are say within camera radius but behind a wall off 'screen space'?

# Answer
You question is very broad. This is very dependent on the platform you are using and the framework/engine if any. The answer is most likely: They are loaded into video memory when your code/framework/engine load them there.

Your other question is related to culling: http://en.wikipedia.org/wiki/Hidden\_surface\_determination#Culling\_and\_VSD

The assets are most likely to be loaded to (asset, video) memory, but not rendered. But again, it is platform dependent.
> 2 votes

# Answer
They endup in video memory when you create the resource for it. And if you run out of video memory it will be paged to the RAM, and if you run out of ram you will page it to the Harddrive, and if you run out of that.. i dont really know whats happening.

And lets say you run out of videomemory, it will be redirected to the video memory when you are binding or using that geometry/texture/uav what ever. this is also a bit depending on how you create the resource, for instance in dx11, there is plenty of resource flags that will tell you where it will endup.

Mipmaps, are a part of the texture so they will be "living" with the texture it self. so they are not sepparate.
> 0 votes

# Answer
It really depends on if you're using a game engine or not. If not, things are only loaded into memory when you load them into memory.

For example, in a 2D tile based game, you could easily render only the visible tiles. Anything outside of the visible tiles is never rendered.

What is loaded into memory? Anything and everything, or nothing at all. If it's rendered, it's in memory. However, you can easily load tons of things in memory that are never rendered, so always remember that you need to handle both memory management AND rendering management to avoid loading, keeping, and rendering that which one cannot see.

Of course, sometimes you WANT to load something in when it isn't rendered, so it is accessed faster.
> 0 votes

---
Tags: level-design, memory
---


# Question
Title: Simple Bounding Box Multiple Collision problem
I'm making my first game, and in it I use a moving ball to hit static blocks (kinda like breakout).

Basically, I loop through all of the static blocks on the screen each frame, update the position of the ball based on its velocity, and if it collides with a block, the ball will bounce back off of the block.

If the ball hits one block exactly, then there is no problem whatsoever. But if the ball happens to hit two blocks at the same time (that is, it hits in between both blocks), it passes right through both of them--no deflection whatsoever.

(I know the looping is inefficient and I'm looking to correct that later, but if it has to do with the problem, I just hope someone can point to me why it is that the collision resolution fails when two similar objects are hit at once.)

# Answer
> 0 votes
I actually ran into this exact problem not too long ago when making a similar game. Each frame, the ball would move to its next increment and sometimes the ball would increment itself into two blocks at the same time.

When I did a collision check against the blocks it would process the first one and alter its direction, but then before it got a chance to move it would process the second collision and change direction again, making it go the same direction it originally started in. This may be what's happening in your game.

I don't know how your collision detection is coded but make sure that if it detects a collision it breaks the loop so it won't try another one in the same frame. I also created a counter that was set to 2 each time a collision happened that it would increment -1 each frame so that a collision couldn't happen the frame after a collision already happened, only when the counter was equal to 0.

---
Tags: collision-detection, cocos2d-iphone, collision-resolution, aabb
---


# Question
Title: What's a good way to distribute delayable tasks between frames to avoid lost frames?
I'm having a problem with finding a good way to keep the framerate high and at the same time keep running methods of game world update. I figured I could just put those methods in a thread so they are executed simultaneously with the rest of the game loop methods, but the threads tend to hog resources, which causes lost frames.

Then I thought I should break down tasks in parts and only run a little piece of a bigger task each frame or so. But this turned out to be way much slower than expected, and it also took a lot of time to implement.

After thinking some more about threads I found another way to use them: `Thread.Suspend` and `Thread.Resume` methods ought to prevent threads from keeping hogging all the resources until the game drawn or calculates some physics. But I also read that it's risky because you can't know what the thread is doing right before you suspend it, which may cause big problems. My tasks are mostly independent from each other, but still, some of them rely on objects which are sometimes edited by two separate threads, and sticking those operations together is an undesired solution.

Are these options any good? What other solutions for this problem do you know?

# Answer
> Then I thought I should break down tasks in parts and only run a little piece of a bigger task each frame or so. But this turned out to be way much slower than expected, and it also took a lot of time to implement.

Did you profile to figure out why it was slower? Assuming it was the overhead of task management, there are two main possible problems: Picking too small a chunk of work for each individual 'task', or using a task management system with too much overhead for your purposes (e.g. using a web server job system meant to distribute tasks across multiple machines).

Job/Task systems come with some necessary overhead, but correctly implemented and fed appropriately sized chunks of work, the overhead should be relatively small. They're frequently used to *improve* performance by giving multiple threads relatively self contained chunks of work to do in a sane and consistent manner.

> After thinking some more about threads I found another way to use them: Thread.Suspend and Thread.Resume

You can accomplish much the same effect with normal synchronization primitives (locks, semaphores, etc.) without the nasty downsides of blindly fiddling around with the thread run state can have. Aside from your own locks, there's also the locks used in implementing every single 3rd party library (right down to the underlying .NET framework, runtime, and even the debugger itself!) to worry about. If the thread that's supposed to resume the paused thread ever tries to lock the same mutex, your program is hosed.

Calling it risky is an understatement: It's basically guaranteeing your program will at some point deadlock. There's a reason it was immediately marked deprecated in the 2.0 version of the framework, and I'd be confident it's author regrets making it available in the first place.
> 2 votes

---
Tags: c#, performance, multithreading, frame-rate
---


title: libgdx keyboard input

text:
# Question
Title: libgdx keyboard input
I'm trying to figure it out how to check if keyboard key was released. I tried messing around with InputMultiplexer, InputProcessor, etc. Nothing helped. Not enough documentation from lib developers (at least for me).

Anyone had similar problem? Can someone help me?

With InputProcessor I can check if single key was pressed. But what if I want to check multiple keys?

# Answer
> 2 votes
There are two ways I can think of to accomplish this.

1. In the InputProcessor keyPressed method you could save the key state in a map. You'll have to use the keyReleased method to set the key state to released. This way you can just check the map to make sure the right keys are pressed.
2. Inside your update/render method call Gdx.input.isKeyPressed(Input.Keys.Key) to see if a key is pressed. This way you are polling input every frame to check for the key combination.

I personally would use method 2, but pick whatever will suit your app best. I might be able to expand on my answer more tomorrow when I'm on my Desktop. Hopefully for now this will get you going in the right direction.

---
Tags: java, libgdx, input
---


# Question
Title: How do I make a character "jump" when leaving an up slope?
I have developed a game in Android using a tile-based system. I´ve implemented 22º, 45º and 67º up and down slopes and everything works (almost) perfect. The problem now is that, when the character gets to the end of an up slope, it justs falls until it finds the ground. I want it to perform some kind of parabola depending on the slope and its speed. I think it´s better explained in the picture:

I already have a function that determines whether or not the character is leaving the slope, I just want some ideas of how to achieve that kind of "jump" in some pseudo-code or explanation because I don't know how to start. Any help would be appreciated.

# Answer
> 1 votes
Let's diversify the situation in the game in different sections :

**Section 1:** Character reaches Slope.

**Section 2 :** Character leaves Slope.

**Section 3:** After leaving slope, character must jump and then fall down .

As Nathan suggested, for a parabolic fall down, you need to maintain a constant horizontal velocity for your character, so i am hoping you now have something like :

`final horizontalVel = '10';//units/sec`

As you have already mentioned, you have a function to determine , if the character is leaving the slope or not. Let us assume, you call a function named `jumpAndFall()` after the character leaves the slope and set a global boolean variable `jumpAvailable` to `true`.

So, here is a little algo for that :

`if(character_leaves_slope){
 jumpAvailable = true;
 jumpAndFall(horizontalVel, jumpAvailable );
}`

Now inside the function :`jumpAndFall`:

You have got to calculate jump speed and add `gravity` to jump speed. However, your character's jumpSpeed must not exceed the game area length, so when it does, immediately reduce jump speed to make the character fall down, as obviously, we don't want your character to fly up!(Take that Newton, we can make the apple fly up :)) So, we will have :

```
jumpAndFall(String horizontalVel, boolean jumpAvailable ){

  if(jumpAvailable )
    jumpSpeed = horizontalVel + gravity;//Define gravity as normal gravity is defined.
   if (jumpspeed>game.tileH-char.height) {
       jumpspeed = game.tileH-char.height-2;//Can be any arbitrary value depending on how much you want the character to fall down
   }
}

```

I know this is not the exact code, but i hope this helps you in achieving what you are trying to do. In any case, i just laid out a little algorithm for you to think about.

Often for tile based games, i have found this site to be quite useful : **Tile Game Programming**.

---
Tags: physics
---


# Question
Title: Game loop delta, factoring execution time?
Was thinking this morning, I 99.9% of the time, only see a main game loop, looking like this, just as much so where the delta is passed into update():

```
while running
getDeltaTime()
...
f(deltatime)
---

```

Now the question I was thinking to myself was what if between getDeltaTime() and f(deltaTime), the code in the middle took 1 second (large value to be easy). That means f(deltaTime) would have moved whatever object less distance than it was supposed to. This would of course be solved by grabbing the delta time directly before it is used.

Should this be a factor to be concerned with in any case?

# Answer
deltatime is the time between two consecutive calls to getDeltaTime(). If a particular frame takes very long, that will show in the next iteration, and the model will be updated accordingly.

That being said, you're right: you should call f(..) straight away. Other code after it. Delays introduced by that extra code, as well as the time it takes to update the model itself, will show in the delta of the next frame.
> 1 votes

# Answer
Yes, it is a factor. Some engines take this into account in some cases. For example AndEngine and its LimitedFPSEngine:

```
@Override
public void onUpdate(final long pNanosecondsElapsed) throws InterruptedException {
    final long preferredFrameLengthNanoseconds = this.mPreferredFrameLengthNanoseconds;
    final long deltaFrameLengthNanoseconds = preferredFrameLengthNanoseconds - pNanosecondsElapsed;

    if (deltaFrameLengthNanoseconds <= 0) {
        super.onUpdate(pNanosecondsElapsed);
    } else {
        final int sleepTimeMilliseconds = (int) (deltaFrameLengthNanoseconds / TimeConstants.NANOSECONDS_PER_MILLISECOND);

        Thread.sleep(sleepTimeMilliseconds);
        super.onUpdate(pNanosecondsElapsed + deltaFrameLengthNanoseconds);
    }
}

```
> 1 votes

---
Tags: game-loop, timing
---


# Question
Title: How to create / draw clickable object (such as Button in WinForm) in XNA WP8?
I am developing a 2D (No 3D in every aspect) Windows Phone 8 turn based tactical games for my college project. I use Monogame.

I want to draw an object similar to Button in windows form, that if the object is tapped / touched, then an event / method started. I am looking for a way to create a similar event like "OnClick" attached on an object, so I know which tile is tapped by the user specifically.

The object is not entirely visible, because I used an empty transparent texture2D (In case you wondered)

Thank you.

(Please feel free to ask anything if my question is not clear enough, and sorry for my jumbled language, if any.)

===============================

FURTHER EXPLANATION : In front of every sprite, I want to draw a "transparent object" that can run an event when tapped (so it appear like user tapped the character, but behind-code-ly, the "transparent object" which is tapped, because it the one that can receive tap input).

Why I need this kind of object, because if I get the tapped coordinate, the coordinate fetched is relatively based on the viewport, once the map bigger, then it's so hard to calculate the tapped thing. But with the "transparent object", wherever the tile is, I can get which tile is tapped precisely.

I think this also an attempt to make my code as detached as possible by dividing each action into a separate class.

# Answer
> 2 votes
Here's some code taken from one of my games to get mouse / touch coordinates.

```
        int x = 0;
        int y = 0;
        bool isInputPressed = false;
        var touchPanelState = TouchPanel.GetState();
        var mouseState = Mouse.GetState();
#if ANDROID
        if(touchPanelState.Count >= 1)
        {
            var touch = touchPanelState[0];
            x = (int)touch.Position.X;
            y = (int)touch.Position.Y;

            isInputPressed = touch.State == TouchLocationState.Pressed || touch.State == TouchLocationState.Moved;
        }
#else
        x = mouseState.X;
        y = mouseState.Y;
        isInputPressed = mouseState.LeftButton == ButtonState.Pressed;
#endif

```

Once you have that you can check to see if the coordinates are inside the rectangle of your "transparent object" or button.

```
var buttonRectangle = new Rectangle(X, Y, Width, Height);

if(isInputPressed && buttonRectangle.Contains(x, y))
    OnClick();

```

As mentioned previously, you may need to scale your input to screen coordinates to and back again. Using a projection is technically the correct way to do it, but ultimately what you are really doing is just scaling your screen size by some ratio.

Generally for 2D games you will work with a "virtual screen size" and scale everything based on that. For example, lets say you make your virtual screen size 800x480 (typical Android screen). You can create a scale vector like this:

```
var scaleX = (float)GraphicsDevice.Viewport.Width / 800f;
var scaleY = (float)GraphicsDevice.Viewport.Height / 480f;

_screenScale = new Vector3(scaleX, scaleY, 1.0f);

```

And pass it into your spritebatch draw call to scale the graphics.

```
_spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend,
    SamplerState.PointClamp, DepthStencilState.Default,
    RasterizerState.CullNone, null, Matrix.CreateScale(screenScale));

```

When you are dealing with mouse / touch coordinates you'll want to scale back like so:

```
x = (int)(x / _screenScale.X);
y = (int)(y / _screenScale.Y);

```

That way, the rest of your code can deal with coordinates in virtual screen space as if you are always dealing with the same side screen. Good luck! :)

# Answer
> 1 votes
This sounds a bit like you're overthinking this (that's not how you should "detach" code or functionality).

You shouldn't have any issue transforming screen coordinates (the clicked/tapped position) into game/world coordinates. Don't introduce extra objects just to catch events, you'll have to do the transformation stuff anyway (to place the transparent objects over actual objects).

I haven't dabbed into XNA 4.0 specifically, but there should be some premade transformation stuff you can use to translate your coordinates in one single line. Just check the accepted answer to this question.

The actual implementation is really based on how you handle input (e.g. creating events or just checking coordinates, etc.).

# Answer
> 1 votes
There are classes where you can ask the position of the touch/mouseclick. Not sure if you can use Mouse.GetState() on WP, but there are also TouchPanel classes.

When you have the current state (if a touch happend, where it happend), you can check if the touch location is within the buttons location and if so, raise the event.

---
Tags: xna-4.0, events, monogame, touch, windows-phone-8
---


title: How to simulate feather fall in box2d?

text:
# Question
Title: How to simulate feather fall in box2d?
I am working with AndEngine with Box2d extension, but general answer or a concept idea will be appreciated too.

I have feather-like objects in a 2D side view world that I want to be part of the physics simulation. I am using linear damping to make the "feather" fall slowly. This might not be a good idea, maybe I should rather apply force in each update, but nevertheless, this works and it makes the object look "light" and it feels like there is air with resistance.

Now how can I make the objects actually look like feathers falling through air?

Specifically I am looking for two types of objects: Long with low density, that should move down in a slow swinging motion and square objects that would just randomly change trajectory. It would be great if this could be one simulation and length would be a parameter - the longer the object is, the more it would swing. Right now I want to simulate feathers, leaves and snowflakes in a cartoon world.

# Answer
> 6 votes
Much like the moon landing, you should **fake it**. The physics of flutter, tumble and vortex induced autorotation are complex. There are papers on simulating this effect, and they do produce some lovely Java animations.

But, I would even go further in your fakery and implement something like a growing sine wave to animate the movement.

Obviously you'll want to tweak the starting values, rate of independent increase of amplitude and frequency until you get something that looks closer to what you want. You'd want some randomness thrown in to make it interesting. Additionally, as your example shows, very light objects with high surface area could actually go *up* near the edges of their waves. So, waves above a certain amplitude should start to factor in a sweeping up value, with a small capped max value.

The less mass and more surface area an object has, the more you increase the amplitude and frequency of the sine wave. The more mass and less surface area should result in a decrease of amplitude and frequency.

---
Tags: box2d, physics
---


# Question
Title: What range of values can HLSL's tex2D function return?
When using the `tex2d` function in a HLSL shader, as so:

```
float height = tex2D(heightMap, IN.texCoord).r;

```

What range of values can be returned to the height variable? Is it always a number between `0.0f` \- `1.0f`? Or does it depend on the texture or sampler?

# Answer
> 5 votes
The tex2D function *usually* returns a float in the range of `[0.0, 1.0]`.

*Think of tex2D as a function that returns a color.*

Color components (like red, for example) range from `0.0` to `1.0` where the former is the total absence of that color and the latter is full intensity.

**However**, as Nathan Reed and other members have pointed out, texture formats that are not normalized may return values outside this range. Here is a StackOverflow post that explains floating-point textures: What exactly is a floating point texture?

# Answer
> 2 votes
it always returns 0.0f -\> 1.0f. even if you save your texture as an uint, you will still sample it as a float. the gpu is specially built for fast float operations and lots of them.

And if the case comes that you want it to range from -1.0 to 1.0 ( where black is -1 and gray ( 128 ) is 0 and white is 1 ) you can simply convert it like this

tex2D() * 2.0 - 1.0; this is really normal when you are using normalmaps.

---
Tags: directx, shaders, hlsl
---


# Question
Title: How can I acheive a smooth 2D lighting effect?
I'm making a 2D tile based game in XNA.

Currently my lightning looks like this.

How can I get it to look like this?

Instead of each block having its own tint, it has a smooth overlay.

I'm assuming some sort of shader, and to pass the lighting values for the surrounding tiles to the shader, but I'm a beginner with shaders so I'm not sure.

My current lighting calculates the light, and then passes it to a `SpriteBatch` and draws with the tint parameter. Each tile has a `Color` that is calculated before draw in my lighting algorithm, which is used for the tint.

Here is an example on how I currently calculate lighting (I do this from left, right, and bottom too, but I got really tired of doing this frame by frame...)

So actually getting and drawing the light so far is **no problem**!

I have seen countless tutorials on fog of war and using gradient circular overlays to create smooth lightning, but I already have a nice method to assign each tile a lightning value, it just needs to be smoothed between them.

So to review

* Calculate Lighting (Done)
* Draw Tiles (Done, I know I will need to modify it for the shader)
* Shade tiles (How to pass values and apply "gradient)

# Answer
How about something like this?

Don't draw your lighting by tinting your tile sprites. Draw your **unlit** tiles to a render target, then draw the tile lights to a second render target, representing each one as a grayscale rectangle covering the area of the tile. To render the final scene, use a shader to combine the two render targets, darkening each pixel of the first according to the value of the second.

This will produce exactly what you have now. That doesn't help you, so let's change it a bit.

Change the dimensions of your lightmap render target so that each *tile* is represented by a single *pixel*, rather than a rectangular area. When compositing the final scene, use a sampler state with linear filtering. Otherwise leave everything else the same.

Assuming you've written your shader correctly the lightmap should be effectively "scaled up" during compositing. This will get you a nice gradient effect for free via the graphics device's texture sampler.

You may also be able to cut out the shader and do this more simply with a 'darkening' BlendState, but I'd have to experiment with it before I could give you the specifics.

**UPDATE**

I had some time today to actually mock this up. The answer above reflects my habit of using shaders as my first answer to everything, but in this case they're not actually necessary and their use needlessly complicates things.

As I suggested, you can accomplish exactly the same effect using a custom BlendState. Specifically, this custom BlendState:

```
BlendState Multiply = new BlendState()
{
    AlphaSourceBlend = Blend.DestinationAlpha,
    AlphaDestinationBlend = Blend.Zero,
    AlphaBlendFunction = BlendFunction.Add,
    ColorSourceBlend = Blend.DestinationColor,
    ColorDestinationBlend = Blend.Zero,
    ColorBlendFunction = BlendFunction.Add
};

```

The blending equation is

```
result = (source * sourceBlendFactor) blendFunction (dest * destBlendFactor)

```

So with our custom BlendState, that becomes

```
result = (lightmapColor * destinationColor) + (0)

```

Which means that a source color of pure white (1, 1, 1, 1) will preserve the destination color, a source color of pure black (0, 0, 0, 1) will darken the destination color to pure black, and any shade of gray in between will darken the destination color by a middling amount.

To put this into practice, first do whatever you need to do to create your lightmap:

```
var lightmap = GetLightmapRenderTarget();

```

Then just draw your **unlit** scene directly to the backbuffer as you normally would:

```
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);
/* draw the world here */
spriteBatch.End();

```

Then draw the lightmap using the custom BlendState:

```
var offsetX = 0; // you'll need to set these values to whatever offset is necessary
var offsetY = 0; // to align the lightmap with the map tiles currently being drawn
var width = lightmapWidthInTiles * tileWidth;
var height = lightmapHeightInTiles * tileHeight;

spriteBatch.Begin(SpriteSortMode.Immediate, Multiply);
spriteBatch.Draw(lightmap, new Rectangle(offsetX, offsetY, width, height), Color.White);
spriteBatch.End();

```

This will multiply the destination color (unlit tiles) by the source color (lightmap), appropriately darkening unlit tiles, and creating a gradient effect as a result of the lightmap texture being scaled up to the necessary size.
> 5 votes

# Answer
Okay here is one very simple method to create some simple and smooth 2D lightning, render in three passes:

* Pass 1: the game world without lightning.
* Pass 2: the Lightning without the world
* Combination of the 1. and 2. pass which is displayed on the screen.

In pass 1 you draw all the sprites and the terrain.

In pass 2 you draw a second group of sprites which are the light sources. They should look similar to this:
Initialize the render target with black and draw those sprites onto it with Maximum or Additive blending.

In pass 3 you combine the two prior passes. There are multiple different ways how they can be combined. But the simplest and least artsy method is to blend them together via Multiply. This would look like this:
> 9 votes

# Answer
The second link you posted looks like a *fog of war* of sorts, there are a couple of other questions on this

That looks to me like a *texture*, where you "erase" bits of the black overlay (by setting the alpha of those pixels to 0) as the player moves forward.

I would say the person must have used a brush type "erase" where the player has explored.
> 2 votes

# Answer
Light vertices (corners between tiles) instead of tiles. Blend lighting across each tile based on its four vertices.

Do line-of-sight tests to each *vertex* to determine how lit it is (you can either have a block stop all light or decrease light, e.g. count how many intersections to each vertex combined with distance to calculate a light value rather than using a pure binary visible/not-visible test).

When rendering a tile, send the light value for each vertex to the GPU. You can easily use a fragment shader to take the interpolated light value at each fragment in the tile's sprite to light each pixel smoothly. It's been long enough since I've touched GLSL that I wouldn't feel comfortable giving real a code sample, but in pseudo code it would be as simple as:

```
texture t_Sprite
vec2 in_UV
vec4 in_Light // coudl be one float; assuming you might want colored lights though

fragment shader() {
  output = sample2d(t_Sprite, in_UV) * in_Light;
}

```

The vertex shader simply has to pass the input values on to the fragment shader, nothing even remotely complicated.

You'll get even smoother lighting with more vertices (say, if each tile is rendered as four sub-tiles), but that may not be worth the effort depending on the quality you're going for. Try it the simpler way first.
> 2 votes

---
Tags: xna, c#, shaders, rendering, lighting
---


# Question
Title: What is the better way of generating levels in android game using LibGDX
I downloaded the source code of metagun for android from https://github.com/libgdx/libgdx/tree/master/demos/metagun/metagun-android

The game uses a png image to create the level. It uses the following code. I am finding it difficult to understanding. The following code is from `Level.java`:

```
@SuppressWarnings("unchecked")
public Level (GameScreen screen, int w, int h, int xo, int yo, int xSpawn, int ySpawn) {
    this.screen = screen;
    this.xSpawn = xSpawn;
    this.ySpawn = ySpawn;

    walls = new byte[w * h];
    entityMap = new ArrayList[w * h];
    this.width = w;
    this.height = h;

    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            entityMap[x + y * w] = new ArrayList<Entity>();

            int col = (Art.level.getPixel(x + xo * 31, y + yo * 23) & 0xffffff00) >>> 8;
            byte wall = 0;

            if (col == 0xffffff)
                wall = 1;
            else if (col == 0xFF00FF)
                wall = 2;
            else if (col == 0xffff00)
                wall = 3;
            else if (col == 0xff0000)
                wall = 4;
            else if (col == 0xB7B7B7)
                wall = 5;
            else if (col == 0xFF5050)
                wall = 6;
            else if (col == 0xFF5051)
                wall = 7;
            else if (col == 0x383838)
                wall = 8;
            else if (col == 0xA3FFFF)
                wall = 9;
            else if (col == 0x83FFFF) {
                BossPart prev = new Boss(x * 10 - 2, y * 10 - 2);
                int timeOffs = random.nextInt(60);
                ((Boss)prev).time = timeOffs;
                add(prev);
                for (int i = 0; i < 10; i++) {
                    BossNeck b = new BossNeck(x * 10 - 1, y * 10 - 1, prev);
                    b.time = i * 10 + timeOffs;
                    prev = b;
                    add(prev);
                }
            } else if (col == 0x80FFFF) {
                Gremlin g = new Gremlin(0, x * 10 - 10, y * 10 - 20);
                g.jumpDelay = random.nextInt(50);
                add(g);
            } else if (col == 0x81FFFF) {
                Gremlin g = new Gremlin(1, x * 10 - 10, y * 10 - 20);
                g.jumpDelay = random.nextInt(50);
                add(g);
            } else if (col == 0x82FFFF) {
                Jabberwocky g = new Jabberwocky(x * 10 - 10, y * 10 - 10);
                g.slamTime = random.nextInt(30);
                add(g);
            } else if (col == 0xFFADF8) {
                add(new Hat(x * 10 + 1, y * 10 + 5, xo * 31 + x, yo * 23 + y));
            } else if ((col & 0x00ffff) == 0x00ff00 && (col & 0xff0000) > 0) {
                add(new Sign(x * 10, y * 10, col >> 16 & 0xff));
            } else if (col == 0x0000ff) {
                // if (xSpawn == 0 && ySpawn == 0) {
                this.xSpawn = x * 10 + 1;
                this.ySpawn = y * 10 - 8;
                // }
            } else if (col == 0x00FFFF) {
                Gunner e = new Gunner(x * 10 + 2, y * 10 + 10 - 6, 0, 0);
                e.chargeTime = random.nextInt(Gunner.CHARGE_DURATION / 2);
                e.xa = e.ya = 0;

                add(e);
            }
            walls[x + y * w] = wall;
        }
    }
    player = new Player(this.xSpawn, this.ySpawn);
    add(player);
}

```

I want some advice as to whether this is a good idea or not? This game was developed in 2010 using LibGdx.

The other example I found using TiledMap is at http://chrismweb.com/wp-content/uploads/2013/03/superkoala/ at the offical site of libgdx.

# Answer
This level loader is an example of converting an image into level data (basically, they're reading pixels, and instead of interpreting the pixel data as a "color" its being interpreted as information about how the level works).

The main idea for this is to leverage some existing tool you're good at using (e.g., an image editor) to avoid needing to create a custom new "level editor" tool. In this example, any pixel-based image editor will work as a "level editor".

An alternative, along similar lines, would be to use a text editor as the level editor. The level loading code would interpret ASCII characters as level information. (E.g., read a "!" as a wall, and an "X" as the starting point, etc). You don't even need to load the level from an external file, at this point it can just be a String in your source code.

A final option is to just hardcode the level data in your source code (this is handy when you're just getting started and want to get a level working quickly to develop/debug). Imagine hard-coding a `walls[5 * 5] = { 1, 1, 1, 1, 1, ...}` for the above code.
> 3 votes

# Answer
IN my opinion there are two main ways to generate game levels.

1. Generate your level and place objects via logic based on world size width and limitation of your game characters
2. Generate and place your objects based on file. Like the code sample you have above, it will iterate through each line or column in your file and generate/place objects based on thier char reference or hex code.

I personally find option 2 better as your have more control over your level and can design it the way you want it. However I use a txt file, string buffer and Char to determine location or objects.
> 0 votes

---
Tags: android, libgdx, level-design, platform
---


title: Combining 2D and 3D in game engine

text:
# Question
Title: Combining 2D and 3D in game engine
I've implemented basic 3D functionality and made little "2.5D" demo in orthographic projection using OpenGL ES 2 and Box2D.

Now I want to make completely two-dimensional game (using sprites) and consider 2 variants:

1. Implement 2D graphics separately from 3D in separate layer, leave 3D stuff in background, draw 2D using various simplified algorithms (disable depth testing, simplified culling etc.)
2. Leave everything as is and use billboards for sprites

Currently I use hierarchical system of entities with matrix transformations. I know about computational complexity of 3D and 2D graphics and believe first method should result in faster code, though it's my first engine and my google-fu fails me this time, so I'm not sure about it.

Engine is Desktop/Mobile.

What method would you recommend? Does implementing first method worth it (in performance aspect)?

# Answer
Implementing 2D as 3D objects can have benefits when you want to mix the two (a 2D interface floating in 3D space, like Dead Space for example).

In the approach I would recommend you will have a 3D object that is the root of a 2D hierarchy. Use traditional 2D rendering to an off-screen buffer for all objects below that root, then use that as a texture for the 3D object (billboarded or not). You can have as many roots as you want (usually just 1 in a pure 2D game).

The problem is that 2D rendering typically works pretty differently to 3D in non-trivial cases. Render order becomes more important and trying to sort polygons in traditional ways for 3D games tends to not work super well for lots of 2D billboards. Using explicit depth layers is faster, easier, and will be more correct in the general case. The "faster" bit is probably not as important for you as you seem to think, though it'll become relevant at truly large numbers of sprites.

So far as engines, most do it your first way as they use an entirely separate library like Scaleform for all of their 2D rendering. Others, like Unity, have libraries to "optimize" some forms of 2D by rendering them separately (and doing various bits of geometry batching and depth ordering) though by default usually just uses the 3D pipeline straight up with a specialized orthographic camera setup.

In short, I would recommend to have both scene types, but make sure you can render either view to a texture so it can be rendered into the other scene type.
> 0 votes

---
Tags: 2d, 3d, architecture, opengl-es2
---


# Question
Title: Are Anaglyph 3D shaders used in game engines?
I have always wanted to put on the "3d glasses" and instead of watching a 3d movie, go to my pc and play a game in real 3D. Has anyone ever tried creating a Real 3D game? Are there any shaders that would allow creating Anaglyph 3D effect in real time? How do they work? (If they exist)

> http://en.wikipedia.org/wiki/Anaglyph\_3D

# Answer
Your game will need to render two viewpoints, one for the left image and one for the right image. From there, a quick search revealed the following shader created by objo on Codeplex:

```
sampler2D input1 : register(S0); // right image input
sampler2D input2 : register(S1); // left image input

float4 main(float2 uv : TEXCOORD) : COLOR
{
    float4 Color1;
    Color1 = tex2D( input1 , uv.xy);

    float4 Color2;
    Color2 = tex2D( input2 , uv.xy);

    Color1.r = Color2.r;
    Color1.g = Color1.g;
    Color1.b = Color1.b;
    Color1.a = max(Color1.a,Color2.a);

    return Color1;
}

```

While created for WPF applications, you might be able to use the above as-is or with a little bit of tweaking.

There have been many games from the NES on up that have rendered an anaglyphic or other method of 3d effect.

The above code is licensed under the CPOL

Link to Codeplex article: Anaglyph ShaderEffect in WPF
> 4 votes

---
Tags: 3d, anaglyph
---


title: Cocos 2D - Hold down CCMenuItem

text:
# Question
Title: Cocos 2D - Hold down CCMenuItem
I am using the following code to move a CCSprite left and right.

```
-(id)init{
    CCMenuItemImage * moveLeftButton = [CCMenuItemImage itemFromNormalImage:@"Move Left Button.png" selectedImage:@"Move Left Button.png" target:self selector:@selector(moveLeftVoid:)];
}
-(void)moveLeftVoid{
    id moveLeft = [CCMoveBy actionWithDuration:.3 position:ccp(-10, 0)];
                [_mainSprite runAction:moveLeft];
}

```

This does work, but only as a single tap. What I want for the CCSprite to move continously in that direction when the CCMenuItem is held down. Then when it's released the character stops moving. If you need to see more code, please just ask. :) Thanks

# Answer
> 3 votes
Another approach is to subclass the **CCMenuItemImage** object. You can override the two functions **-(void)selected** and **-(void)unselected** to determine when the user has pressed and is holding.

# Answer
> 1 votes
I think the CCMenu (and the CCMenuItem) is not appropriated in your case. Indeed, the CCMenu is designed to fire an event only when a touch up inside an item occured, nothing else.

I should you to use the CCControlButton (from the CCControlExtension). This component works like a UIButton and thereby you can know when a user touches down your button and when he touches up. So while the button is pushed you can schelude your "moveLeftVoid" method each among of time and unschedule it when the button is released.

# Answer
> 1 votes
If you are traying to implement some kind of touch controller I suggest you to use SneakyInput

Extremely easy to create analog sticks, dpad, buttons and It's totally customizable(skinnable).

It's been a while since the last update but works fine with the latest stable cocos2d

# Answer
> 1 votes
I wanted this sort of thing too. I looked at both of the CCControlButton and SneakyInput options, but decided against them. CCControlButton didn't really do what I wanted, plus it seems to assume/require you to use a CCScale9Sprite, which for a simple button in a game, is too much work.

SneakyInput, upon analysis seems to schedule it's own update events which seems overkill and inefficient to me.

So, I wrote a simple subclass of CCMenuItemSprite which allows a second block to be provided. When the user taps, the first block is called, when the user releases, the second block is called. It might be worthwhile to add a check to ensure that the hold isn't fired unless the button is held for at least a second, but for a game, I'm not sure it's a good idea. I'll leave that to those that follow.

The code can be found at: CCExtensions

# Answer
> 1 votes
Instead of overriding the ***selected*** method, I simply used the *isSelected* variable.

Change this:

```
   -(id)init{
CCMenuItemImage * moveLeftButton = [CCMenuItemImage itemFromNormalImage:@"Move Left Button.png" selectedImage:@"Move Left Button.png" target:self selector:@selector(moveLeftVoid:)];
   }
   -(void)moveLeftVoid{
   id moveLeft = [CCMoveBy actionWithDuration:.3 position:ccp(-10, 0)];
            [_mainSprite runAction:moveLeft];
}

```

To this:

```
-(id)init{
CCMenuItemImage * moveLeftButton = [CCMenuItemImage itemFromNormalImage:@"Move Left Button.png" selectedImage:@"Move Left Button.png" ];
   }
}

```

And in your scheduler method do something like:

```
 if(moveLeftButton.isSelected){

 //change your position according to (ccTime) dt

 //maybe something like:
 _mainSprite.position = CGPointMake(_mainSprite.position.x - 10/.3*dt,_mainSprite.position.y);

 }

```

---
Tags: iphone, cocos2d-iphone, game-mechanics
---


title: Black areas on different screen sizes

text:
# Question
Title: Black areas on different screen sizes
I'm currently facing some problems with sprites/images on different screen sizes. For now the game stage is stretched to maximum width and height of the screen.

In Samsung Galaxy S2, SGS3 and SGS4 the game is working as normal as expected:

But... yesterday I tested it on GT-P5110 android tablet.. and the result was:

The screen background and car sprite was replaced by black rectangles...

Does somebody know what's happening?

The same result occurs on sgs2/sgs3/sgs4 when any of the sprite image has more than ~4100px of height. Maybe it's something with image limits? If yes... how to know that limit? Currently (working on sgs2, but not on tablet) the background image size is 3117x480. It's so wide because it used for parallax background. If it exceeds the limit how should I handle this (join two images)?

# Answer
Some Googling reveals that the max texture size may be 2048x2048 on the tablet, and your ~4100px limit implies a max texture size of 4096x4096 on the phones, though I've never seen this particular rendering artifact result from that. Generally the texture won't load at all, not somehow get its alpha component chopped off, but if that's the reproducible cause of the problem, then texture size must be it. Honestly it looks more like the alpha test or blend state is just wrong, but maybe the PowerVR drivers do something silly with over-sized textures instead of just erroring out on texture object initialization.

Yes, the correct thing to do in that case is to split your image up (preferably into power-of-two sizes that are within the GL\_MAX\_TEXTURE\_SIZE size; you have to query it at runtime with glGetIntegerv or the like as the spec only guarantees a size of 64 texels to be supported by any particular device/driver.) You can then render multiple quads/triangles to cover the multiple source textures. With a little leg work you can set up a system to take any texture, split it into tiles of the maximum size, and then create both the necessary texture objects and vertices for the split image.
> 1 votes

---
Tags: sprites, libgdx, image
---


title: Picking game entities

text:
# Question
Title: Picking game entities
What is the preferred methods for doing so, performance-wise?

For example I want to pick certain objects in an area around a given point.

What I have thought off so far is using invisible objects as extended hit detectors. Like creating a circle or square then have collision responses to them.

Or maybe just pass the entire object list and iterate on it, then using a distance/angle based condition.

# Answer
> 1 votes
If you have a physics engine that is already capable of efficiently finding collisions between bounding shapes, generating a temporary shape (like a sphere) is common practice. If the physics engine has support for single-frame shape-collision queries, you could use that, but many will require you to create a new physics collision shape and then remember to remove it yourself after the next physics update.

You might want the object to exist more than one frame anyhow, for example maybe the effect you're looking for is to damage every enemy in contact with the explosion at 100 dmg/sec with the explosion lasting 3 seconds, so enemies can enter or leave the explosion and get less than the full 300 dmg it could do.

---
Tags: architecture, game-loop, haxe
---


title: Rotating sprites

text:
# Question
Title: Rotating sprites
I'm a beginner at making games, i'm currently only working in 2D using XNA.

So far all of my games i've been using the following logic for sprite movement:

```
if(left key pressed)
   sprite_x_position --;

```

This movement is kind of square?

I want to be able to turn the sprite, so that'd be rotating the vector i'm using to store the sprites position?

My vector and matrix math is OK but i'm having a hard to looking for a decent walk through on how to do this?

Any help would be appreciated,

thanks in advance

# Answer
Make a new float variable called `Rotation`

You can use the `MathHelper` class to provide easy methods to convert degress to radians (the value `SpriteBatch` accepts)

For example: (I use an origin for the rotation so it rotates around the center)

```
Rotation = MathHelper.ToRadians(180); //Rotate the sprite 180 degrees
SpriteBatch.Draw(TEXTURE, SPRITE_POSITION, null, Color.White, Rotation, new Vector2(TEXTURE.Width / 2, TEXTURE.Heigh / 2), 1, SpriteEffects.None, 1); //Draw TEXTURE with Rotation

```

*Additionaly*, I would recommend creating a sprite class to hold your Texture, Position, Rotation, Velocity, etc.

```
public class Sprite
{
      Texture2D Texture;
      Vector2 Position;
      float Rotation;

      public Sprite(Texture2D texture)
      {
            Texture = texture;
      }
}

```

This way you can just do `Sprite sprite = new Sprite(TEXTURE)` and have a nice object oriented approach to accessing it (`sprite.Position`, `sprite.Texture`, etc) and will probably help you later in the long run.

One of the bigest mistakes that will hurt you later is not applying elapsed time. If your FPS drops (different computer, running alot of programs, etc) or rises then your sprite will move faster, since it is depending on the update rate. You can solve this by applying elapsed time.

```
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
float speed  = 10; //Will need tweaking, I cant remember a good value
if (KeyBoardState.GetState().IsKeyDown(Keys.Left))
{
      sprite.Position -= elapsed * speed //Elapsed is so small so we must multiply by speed
}

```
> 1 votes

---
Tags: xna, movement, vector
---