# Question
Title: Random looking item placement that's deterministic?
I'm working on a sidescrolling game and I want to generate a forest for the background. I want the background to be the same for every one to make sure the quality is the same. I don't have access to a seeded random number generator either, so I can't find a good seed and go from there.

Ideas?

# Answer
The most obvious way would probably be to write a random number generator of your own. Especially since you don't need to meet any particularly high standards for randomness (just lack of obviously visible patterns) it's pretty easy to write a pretty reasonable one in under a half dozen lines of code.

You can add a argument that make the object density abut the same to improve it if needed
> 15 votes

# Answer
Try this. Iterate from numbers 1 to n, where n is the number of trees you want to draw. Compute a hash on each number. Use the hash as input for the function that draws or positions the elements in the background. For instance, you could use the first 8 bits of a 128-bit MD5 hash as the x percentage, the next as the y percentage, the next as some sort of x scaling, etc. If you use the same hash function, and give the same inputs, each time you run it you will get the same output.

This should absolutely give both good randomness and will be deterministic.

Also, if this is not a good answer, please leave a comment explaining why.

Just looking at wikipedia, this method looks promising:

http://en.wikipedia.org/wiki/Random\_number\_generation#Computational\_methods
> 6 votes

# Answer
If you have access to any sort of hash (like MD5) or checksum (like CRC32), you could just hash a sequence of numbers.

Otherwise, the simplest PRNG would probably be the Linear Congruential Generator. It has a complicated-sounding name, but writing one is extremely simple:

Choose three constants, **m**, **a**, and **c**.
Begin by setting **xprev** to your seed.
Then every time you want to generate a new value **xnext**, just do

```
x<sub>next</sub> = (a*x<sub>prev</sub> + c) mod m
x<sub>prev</sub> = x<sub>next</sub>
```

Some good choices for **m**, **a**, and **c** can be found here.
> 5 votes

# Answer
You could apply the cicada principle (use prime numbers for intervals).
> 3 votes

# Answer
Given that a seeded random number generated is essentially just a look up table with the seed being the offset (starting index), you can set up a simple one by reading in a CSV (comma seperated values) file of numbers.

As long as all instances use the same seed, it will be deterministic whilst maintaining it pseudo-randomness.
> 3 votes

# Answer
One possibility is to use an algorithm called simplex noise, invented by Ken Perlin (known for Perlin Noise). One nice feature of simplex noise (like Perlin noise) is that it can be tiled - ie, only a small region out of the potential area needs to be calculated and this can be repeated over the entire area without visible seams.

> For the noise function to be repeatable, i.e. always yield the same value for a given input point, gradients need to be pseudo-random, not truly random. They need to have enough variation to conceal the fact that the function is not truly random, but too much variation will cause unpredictable behaviour for the noise function

Simplex noise can be generated faster than Perlin noise and does not require a random number generator. It is not arbitrary to implement just by knowing the theory, but there is some source code to help you along (referenced from Wikipedia).

Other options for generating pseudo-random noise are fractals and wavelets.

On your situation you would use one of these techniques to generate a series of data in one dimension, and then apply a threshold to determine whether a tree should be placed at that position.
> 3 votes

# Answer
Simplest answer: Make your program load a file with pre-generated numbers in it and write a simple utility to generate random (or algorithmic in any case) numbers to save into that file.

In this way you can generate files that are mostly-good and hand tweak the remaining parts of it that suck without getting into the problem where every random seed you try has some problem with it.
> 1 votes

# Answer
Another approach:

Use a block cipher to "encrypt" a series of numbers from 1 to N, using a fixed key. TEA is easy to implement and fairly fast.

One advantage of this approach is that if you don't like the series of "random" numbers which you get back, you can try a different encryption key and get a whole different series back.
> 0 votes

---
Tags: algorithm, random, mathematics
---


# Question
Title: Rotating and scaling textures built up of pixel arrays in java?
---

I'm making my first real game, in *Java*, and I'm currently working on the base system, for rendering images (sprites) and I wonder **how I can rotate sprites**.

---

**My sprite class** looks like this:

```
package com.game.graphical;

import com.game.location.Vector2i;

/**
 * A simple Sprite with a Texture.
 *
 * @author TheDDestroyer12
 */
public class Sprite {

    // The Sprite's Texture
    private Texture texture;

    // The Sprite's location
    private Vector2i location;

    /**
     * Create a new Sprite.
     *
     * @param texture The texture for the Sprite.
     * @param location The location of the Sprite.
     */
    public Sprite(Texture texture, Vector2i location) {
        // Set the Texture
        this.texture = texture;
    }

    /**
     * Move the Sprite a number of pixels in any direction, specified by the Vector2i.
     *
     * @param change The amount of pixels to move the Sprite.
     */
    public void move(Vector2i change) {
        // Add the change to the Sprite's location
        location.add(change);
    }

    public void rotate() {
        // TODO ROTATE THE SPRITE
    }

    /**
     * Get the Sprite's Texture.
     *
     * @return The Texture.
     */
    public Texture getTexture() {
        // Return the Texture
        return texture;
    }

    /**
     * Get the Sprite's location.
     *
     * @return The Sprite's location.
     */
    public Vector2i getLocation() {
        // Return the location variable
        return location;
    }
}

```

**and the class called `Texture`**, looks like this:

```
package com.tdd12.darkness.graphical;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Texture {

    // The BufferedImage
    private int[] pixels;

    // The size of the Texture
    private int width, height;

    /**
     * Create a new Texture.
     */
    private Texture(BufferedImage image) {
        // Set the pixels array
        pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
        // Set the size
        width = image.getWidth();
        height = image.getHeight();
    }

    /**
     * Load a Texture from an image file.
     *
     * @param path The path to load the image from.
     *
     * @return The loaded Texture.
     */
    public Texture loadTexture(String path) {
        // Create a new Texture object
        Texture texture = null;
        try {
            // Load a BufferedImage from the file at the path
            BufferedImage image = ImageIO.read(new File(path));
            // Create a new Texture of the BufferedImage
            texture = new Texture(image);
        } catch(IOException e) {
            // Print an error description
            System.err.println("Texture loading failed!");
            // Print the error message
            e.printStackTrace();
        }
        // Return the Texture
        return texture;
    }

    /**
     * Get the pixels of the Texture.
     *
     * @return The pixels as an integer array.
     */
    public int[] getPixels() {
        // Return the pixel array
        return pixels;
    }

    /**
     * Get the width of the Texture, measured in pixels.
     *
     * @return The width of the Texture.
     */
    public int getWidth() {
        // Return the width
        return width;
    }

    /**
     * Get the height of the Texture, measured in pixels.
     *
     * @return The height of the Texture.
     */
    public int getHeight() {
        // Return the height
        return height;
    }
}

```

**The rendering** works like this:

```
public void drawTexture(Texture texture, Vector2i location) {
    // Get the sprite's texture's pixels
    int[] texturePixels = texture.getPixels();
    // Store the current texture coordinates
    int tx = 0, ty = 0;
    // Store the starting location
    int x = location.x, y = location.y;
    // If the X coordinate is less than 0
    if(location.x < 0) {
        // Set it to 0
        x = 0;
    }
    // If the Y coordinate is less than 0
    if(location.y < 0) {
        // Set it to 0
        y = 0;
    }
    // Scroll through each pixel on the screen vertically (begin at the Y coordinate specified by the 'location')
    for(int xx = x; (xx < getWidth() && xx < x + texture.getWidth()); xx++) {
        // Scroll through each pixel on the screen horizontally (begin at the X coordinate specified by the 'location')
        for(int yy = y; (yy < getHeight() && yy < y + texture.getHeight()); yy++) {
            // Set each pixel to the color of the corresponding pixel on the Texture
            pixels[xx + yy * getWidth()] = texturePixels[tx + ty * texture.getWidth()];
            // Add one to the texture X coordinate
            ty++;
        }
        // Reset the ty variable
        ty = 0;
        // Add one to the texture X coordinate
        tx++;
    }
}

```

The array called `pixels` is the array of pixels from a `BufferedImage`, which is got by using `int[] pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData()`. The drawTexture method isn't completely optimized. I'm working on it, but that's the base. The process looks like this:

## \- Texture loading:

* A new `Texture` object is created using `Texture.loadTextrue(pathToTexture)`.
* A `BufferedImage` is loaded from the file at the path specified by `pathToTexture`.
* In the constructor for `Texture`, the pixels is loaded from the `BufferedImage` into an array.

## \- Rendering:

* With some pretty simple loops, the color of each pixel from the `Texture` is applied to the corresponding spot in a larger `BufferedImage`'s pixel array.
* The larger `BufferedImage` is then being drawn to a `Canvas`, which is contained in a `JFrame`, using `Canvas.getBufferStrategy().getDrawGraphics().drawImage(img, x, y, width, height, null)`.

---

## The way I'm thinking of doing it

is by creating a larger array, and moving the pixels, relative to the center point. I'll try to illustrate it:

*Before rotation:*

*After rotation (not correct size. Just made it to illustrate that the array size has grown):*

**I'm not using any engines**. Just pure *Java*.

---

**Preferbably, I would like** to keep this method, and not use `Graphics2D` and `AffineTransform`, but in case that's the only solution, well, go on.

***// TheDDestroyer12***

# Answer
> 1 votes
A rotation is essentially that for each sample in the resulting grid, find out which texels in your original texture that your filter footprint covers and interpolate them accordingly. This will be a lossy process, and if done repeatedly will quickly obliterate all interesting information in the image.

If you only look at the nearest texel, you'll get a box filter or nearest neighbour. If you look at the four closest and weigh them by distance, you get a bilinear filter. There's lots of fancy filters out there, with different tradeoffs and costs.

I recommend reading Alvy Ray Smith's memo "A pixel is not a little square", it covers a lot of fundamentals in raster images.

As a side note, a decent resource on all sorts of old-school image manipulation is the old flipcode.com archives.

---
Tags: java, 2d, rendering, pixel
---


# Question
Title: Why does my depth test fail on Nvidia cards?
I sent a test version of my in-development game to some friends, and they found out that the Depth Test in OpenGL does not work on Nvidia cards. I'm using LWJGL.

I use my own matrices and send them to the shader, and at the start of evey game loop I use

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // clear the display

```

On an Nvidia card, you can see mountains through other mountains and stuff. On my Radeon HD 6650M it works perfectly fine. Any ideas?

I don't have anything special in the shaders—just some basic lighting calculations. I dont touch the `gl_FragDepth`.

Here's a screenshot (with placeholder textures):

I use these calculations for the Projection Matrix:

```
public Matrix4f getProjectionMatrix() {
    // Setup projection matrix
    Matrix4f projectionMatrix = new Matrix4f();
    float fieldOfView = 40.0f;
    float aspectRatio = (float)Display.getWidth() / (float)Display.getHeight();
    float near_plane = 0.1f;
    float far_plane = 1000f;

    float y_scale = coTangent((float) Math.toRadians(fieldOfView / 2f));
    float x_scale = y_scale / aspectRatio;
    float frustum_length = far_plane - near_plane;

    projectionMatrix.m00 = x_scale;
    projectionMatrix.m11 = y_scale;
    projectionMatrix.m22 = -((far_plane + near_plane) / frustum_length);
    projectionMatrix.m23 = -1;
    projectionMatrix.m32 = -((2 * near_plane * far_plane) / frustum_length);
    projectionMatrix.m33 = 0;
    return projectionMatrix;
}

```

# Answer
Make sure you request a depth buffer from LWJGL by passing a PixelFormat to your call of Display.create. Like so:

```
Display.create(new PixelFormat(4,24,0,4));

```

The 24 indicates a 24 bit depth buffer.
> 1 votes

---
Tags: opengl, java, shaders, lwjgl, depth-buffer
---


title: Cover system design considerations

text:
# Question
Title: Cover system design considerations
I'm trying to plan out a cover system for a 3D game.

## The mechanic

1. When the player approaches a surface they can take cover behind...
2. A prompt appears indicating they can enter cover, and what to press to do so.
3. If the player presses the prompted button, their avatar is locked into a path following the scenery they're taking cover behind.
4. If the cover is a half wall, the avatar should crouch.
5. If the player approaches a gap in cover the camera should peek around the corner and
6. ...they should be prompted to jump to the next cover
7. ...otherwise, the player can exit cover by pressing another action button.

As seen from directly overhead (please forgive the side view character):

## The plan so far

As far as I know, cover must be either

* baked into the level by algorithm
* explicitly created by the level designer
* somehow handled on the fly

What I think should happen is the environment should be baked into hidden geometry which qualifies as cover. Then, I would detect sphere collisions (blue) with the generated cover areas (purple) to find out when one is in range.

Static geometry would qualify as cover if it were higher than a certain amount from adjacent ground (ie. at least 2.5 feet tall), and another threshold would indicate whether the character should crouch (at least 6 feet for standing cover, otherwise crouch). It seems like this would also be helpful for NPC vision and path finding.

This sphere detection process could be used similarly to locate gaps with cover available on the other side. Finally, once in cover, the player would move tangent to the cover surface (purple regions). Cover surfaces with angles less than a certain threshold would interpolate the current path into the path the player should follow to continue, otherwise they would be counted as a corner. So when the player reaches the end of cover, the angle of the adjacent surface determines that cover has ended and will prevent the player from accidentally breaking cover. They could press a button to move around the corner.

---

But I prefer not to reinvent the wheel - so is this "correct," or is there some accepted way of doing this that's totally different?

# Answer
> 1 votes
Avoid using an algorithm for figuring out cover from the raw environment, you'll have to debug both the algorithm and the environment when the character decides to snap through another object and then gets stuck or fall through the floor, or 5 crates in a slight L placement cause the algorithm to make a huge cover box rather than a proper L, etc.

Handling this on the fly is even worse for this as you'll have a harder time reproducing the bugs.

Best is to have cover boxes attached to entire cover objects (tipped tables, walls, windows, stone wall) that are instantiated in the environment and other explicitly created cover boxes for groups of random props (crates) that the level designers can control.

Make sure you can visualize the cover boxes for debugging and also have a tool check for invalid placement such as two covers too close to another that will snap the player into the other collision so they can then be fixed by hand.

Any game logic that snaps actors into place (ledge grab, cover, sitting in chair, etc) are a huge source of collision bugs, be ready to spend a surprising amount of time debugging those.

---
Tags: optimization
---


# Question
Title: Using Delta for a stopwatch, delta too fast than real time seconds
I search for methods to create a stopwatch on libgdx and came across with this:

```
public void trigger(float delta){

    playTime += delta;
    playTimeRounded = ((double)Math.round(playTime * 100) / 100);
    Gdx.app.log("deltaTime", delta + "");
}

```

But its not accurate and its much faster. How can i create an accurate stopwatch?

# Answer
> 1 votes
When you accumulate deltas you are also accumulating rounding errors.

Instead, record the system time the game started and compare it to the system time now.

Do not use time-of-day as this can get adjusted by internet-based time-of-day clock synchronization and other things.

Different OSes have different names for those clocks.

On windows you can use GetTickCount64 for this ( http://msdn.microsoft.com/en-us/library/windows/desktop/ms724411%28v=vs.85%29.aspx )

On linux you can use clock\_gettime with CLOCK\_MONOTIONIC (http://man7.org/linux/man-pages/man3/clock\_gettime.3.html )

On OSX you can use clock\_get\_system\_microtime ( https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/services/services.html )

For Java use System.nanoTime()

# Answer
> 0 votes
Maybe your `delta` parameter has a wrong value when called. I prefer to use `Gdx.graphics.getDeltaTime()` instead.

```
float playTime = 0;
float playTimeRounded;

void AnyUpdateMethod()
{
    playTime += Gdx.graphics.getDeltaTime();
    playTimeRounded = Math.round(playTime * 100) / 100.0f;
    Gdx.app.log("playTimeRounded", playTimeRounded + "");
}

```

# Answer
> 0 votes
The deltaTime is the amount of time which passes between drawing two consecutive frames. It is used for updating things on your screen that change in time, for example when moving your objects around, you would want to apply the deltaTime to the object's speed, in order to have a consistent movement across devices. When calculating playtime though, you should only use the system time, increase it, decrease it normally, without applying any delta to it. You would have to store your playTime value as a long, since you are going to add to it the value of TimeUtils.millis(). Just forget about the deltaTime in this case.

---
Tags: libgdx
---


title: 3D model editor manipulators

text:
# Question
Title: 3D model editor manipulators
I'm trying to make my own 3D model editor to better learn 3D programming. I have my translate manipulators and I'm trying to calculate the Vector2 that the mouse would have to move in order to move an object down a specific axis. This will obviously change based on the position of the camera, position of the object and the axis. I have the majority of it working, I'm just not sure on how to finish it. If the camera is completely horizontal to the object then the values come out correct, but once I start to move the camera above or below the object the values start to get less accurate. I figure I need to incorporate the camera's up vector into it, but I'm not sure how.

The code snippet is for the X axis.

```
Vector3 meshCameraDistance = meshPosition - cameraPosition;
Vector3 angleAxis = new Vector3(1, 0, 0);
float meshCameraAngle = Vector3.Angle(meshCameraDistance, angleAxis);
Vector2 mouseDragDirection = new Vector2(Mathf.Sin(Mathf.Deg2Rad * meshCameraAngle), Mathf.Cos(Mathf.Deg2Rad * meshCameraAngle));

if (meshCameraDistance.z < 0)
{
    mouseDragDirection = new Vector3(-mouseDragDirection.x, mouseDragDirection.y);
}

speed = (manipulatorSpeed.x * mouseDragDirection.x) + (manipulatorSpeed.y * mouseDragDirection.y);

```

# Answer
Usually this is handled a bit differently.

When manipulator is picked, you choose a movement plane (XY, YZ or XZ). Then you cast ray from cursor on to that plane and detect the hit point and move the manipulator (and object) to that location.

Special cases you need to work around for are when the plane is parallel to the view and ray from cursor can reach infinity. For such cases you need to clip your movement plane to some reasonable size and discard the movement outside of it.
> 2 votes

---
Tags: unity, 3d, mathematics, camera, axis
---


# Question
Title: How to reference UnityEditor in external DLL when using UnityVS, successfully?
So I'm trying to put my scripts and custom inspector editor scripts in two external DLLs and I'm facing a problem on my Editor DLL. First of, I'm using UnityVS with Visual Studio 2013 Ultimate.

I added a reference to `C:\Program Files (x86)\Unity\Editor\Data\Managed\UnityEditor.dll` and it successfully shows me IntelliSense and I can access all classes and it's members, too. But when I try to compile the build, it will complain not finding the assembly UnityEditor. Even referencing the same DLL like the UnityProject (inside the Library folder) results in that problem, as it's just a copy of installed UnityEditor.dll.

I even tried to open this project in a separate Visual Studio and build it, got the same result.

I've heard, placing the resulting DLL in the Editor folder will make the custom inspectors available, so I really wish this would compile.

# Answer
> 1 votes
My bad, I forgot to reference the right target framework in my Editor DLL.

---
Tags: c#, unity, visual-studio
---


title: Sprite sheets, Clamp or Wrap?

text:
# Question
Title: Sprite sheets, Clamp or Wrap?
I'm using a combination of sprite sheets for well, sprites and individual textures for infinite tiling.

For the tiling textures I'm obviously using Wrap to draw the entire surface in one call but up until now I've been making a seperate batch using Clamp for drawing sprites from the sprite sheets. The sprite sheets include a border (repeating the edge pixels of each sprite) and my code uses the correct source coordinates for sprites.

But since I'm never giving coordinates outside of the texture when drawing sprites (and indeed the border exists to prevent bleed over when filtering) it's struck me that I'd be better off just using Wrap so that I can combine everything into one batch.

I just want to be sure that I haven't overlooked something obvious. Is there any reason that Wrap would be harmful when used with a sprite sheet?

# Answer
If you never sample outside of `0 .. 1.0` range, then it does not really matter if you use wrap instead of clamp.
> 1 votes

---
Tags: xna-4.0, spritesheet, sampler-state
---


# Question
Title: Isometric graphics with fake perspective
Diablo 2 is a game with isometric graphics. However, unlike other isometric games, D2 has the option to activate perspective. Obviously, the D2 developers found a clever trick to convincingly fake perspective in their isometric engine. It has to be a fake, because D2's graphics assets consist of pre-rendered isometric 2D tiles.

I want to implement a similar effect in my isometric graphics engine, but was unable to find out how to deal with the more subtle issues of applying perspective. A similar question has been asked on this site before. Unfortunately, the answer to that question does not help with the specific problems I am facing.

Let me explain my approach in detail. I use two dimensional tiles for floor and walls that look like this: (Note that the floor tile is not actually part of the wall tiles. I added it just for clarity.)

These tiles can be assembled in 2D to create an isometric scene:

It is actually pretty easy to fake perspective in such an isometric scene. Slightly enlarging objects at the bottom of the screen and shrinking objects at the top makes them seem close or distant, and creates a subtle illusion of perspective. This is easily achieved in a vertex shader and works very well for floor tiles: . The floor looks good, but the walls do not. Vertical lines get distorted. I can fix this by applying uniform scaling to objects, instead of distorting them like floor tiles. The scale factor depends on the object's y-position. This works well for character sprites and front facing walls, but fails for diagonal walls and more complex objects.

Now the actual question: A front facing wall can be scaled by the y-coordinate of points A and B, which is the same. However, this does not work for corners or diagonal walls where the points have different y-coordinates. It seems, for an accurate perspective effect, each wall tile needs to be treated differently so they can fit seamlessly together. This does not seem feasible to me. Ideally, I want to treat all wall tiles equally.

Is it possible to scale wall tiles so they fulfill the following criteria?

* they should become continuously smaller the further up on the screen they are
* they should not appear to move or jitter when the viewpoint changes
* they should seamlessly fit together

Any help is appreciated. I've been worrying about this for days, but maybe I'm thinking too complicated :)

**update:** Isometric view with increasing perspective. Note what happens when wall tiles are simply scaled. This works well for front facing walls only.

I want to approximate perspective correction so that all wall tiles fit seamlessly.

# Answer
I want to thank everyone who took their time to respond to my question. I finally came up with my own solution, which nevertheless was inspired by the suggestions here.

Especially this comment from Ali.S turned out to be particularly useful:

> Just an idea, but you can provide your shader with another texture, representing the height of that pixel, and take that information into account – Ali.S Dec 13 at 22:24

Instead of using another texture with height information, I went for an approximate approach. I store for each tile a line that passes through the two ends of the wall at ground height:

Now it is possible to scale the two sides of each tile differently, according to the y-coordinate of the line's endpoints. However, in case of the corner tile, this leads to distortions because the wall does not exactly coincide with the line.

Fortunately, these distortions are not a big problem since I only plan to apply a subtle perspective effect. This makes the distortions hardly noticeable, unlike in the image above, where perspective is highly exaggerated for illustrative purposes.
> 4 votes

# Answer
I would try using a screen buffer to draw all the walls (and possibly the characters) to. And then you can apply the perspective to all the walls at once. This should eliminate any errors you are getting because perspective is being applied to a single image rather than multiple images. You would than assemble the scene by drawing floor layer and then the wall layer on top of it.
> 0 votes

---
Tags: 2d, graphics, isometric, perspective
---


title: Collision detection enhancement

text:
# Question
Title: Collision detection enhancement
I am developping a spaceinvader-like game. There comes the problem of how to handle collision detection.

At first I was doing like that :

```
forEach(fireBall : fireBalls) {
    forEach(stormTrooper : stormTroopers) {
        if (collides(fireBall, stormTrooper)) {
             // Explode

```

But then when playing I had the feeling the game was **slowing down** at some point, and I tought it had something to do with the multiple elements and the double loop.

So I tried to **break the loops** whenever I had the chance, changing the forEach loops to for loops at the same time :

```
for (var i = 0; i < fireBalls.length; i++) {
     if (stormTroopers.length > 0 && fireBalls[i].y > stormTroopers[0].y) {
          break;
     }
     for (var j = 0; j < stormTroopers.length; j++) {
         if (fireBalls[i].y > (stormTroopers[j].y + 31)) {
             break;
         }

```

If the fireball isn't on the same "y" as any stormtrooper, the fireballs following are not going to be either, so no need to check. Same for the stormtroopers loop. This works **only if the list is ordered**, meaning the first stormTrooper of the list has the highest "y" value.

The problem in my game is that all stormTroopers don't have the same speed, so I need to sort the list each time.

This leads to my question : in order to enhance the performance, I tried to break the loops, but for that I had to add a new operation : sort the list of the stormTrooper. **Is it worth it?**

# Answer
> 1 votes
To know if its worth it profile the collision loop and see if its faster after your changes.

For sorting, a bubble or insertion sort will be faster than a quick sort if you reuse the same mostly-sorted array every frames.

Quick sort is only faster if the list is completely random, for mostly-sorted lists you're better off with an improved bubble (insertion) sort as most of the time your stormTroopers will still be in the proper order the next frame.

You can probably keep your fireballs sorted as well in reverse order, especially if they all move at the same speed. You'll only have to check the overlap.

Because everything moves at roughly the same speed in roughly the same direction full blown quadtrees might be overkill. The quadtree maintenance itself could become more intensive than the cost of plain Y-ranged, Y-sorted collision.

You can also do a pseudo-binary search (warmer - colder) in your sorted arrays on the Ys as the next fireball will be close to the previous one it can help skipping to a relevant stormTroopers, then scan forward AND backward in the stormTroopers array until you're outside the Y range in both directions, start scanning stormtroopers from the range's proper extremity for the next fireball.

By sorting both fireballs and stormtroopers, checking only the overlap, and ranged scanning on every iteration it can end up faster than maintaining a quadtree.

With this you can also try sorting them in X, the sorted & ranged scanning will cause your two inner loops (backward and forward scan) to do very few iterations as it will resume the inner-scan from the values found in the previous outer iteration.

# Answer
> 2 votes
You've inadvertently come across a form of broad-phase collision culling. Specifically, sort and sweep!

Why not go all the way and use a QuadTree instead? Quadtrees recursively subdivide the space into quadrants, and only check collisions between entities which occupy the same quadrant. You can speed up your collision detections exponentially this way, with just a bit of mental overhead.

---
Tags: collision-detection, javascript, performance
---


# Question
Title: Checking whether moving object has reached target position
So I have a fast-moving object in my game, let's say a bullet. At each iteration of the main loop I update the object's position based on the delta time value `dt` and draw it at the new position.

I also check whether the object's new position is close to a target position. In that case the object will be removed:

```
S....|...|....|....|......|...|....|....|...|..T..|X

```

The object starts from location `S`, moving towards target position `T`. Each dot `.` represents one ms time. The vertical bars `|` represent a game loop iteration, in which I check whether the object has reached its target destination. At `X` the object will be removed.

Since these checks (ie. game loop iterations) might take place before or after the 100% exact target position (even if only a few pixels off), I perform this check with a distance between a line segment from the last position to the current position, and whether the target position is on that line. This approach works well.

There is one issue though: Since the check in which I recognize that the target has been reached happens **after** the real position of the target, the object moves a little bit further than desired. That's becoming more severe when the object is moving very fast.

Now my question: Is there kind of a "best practice" how to deal with this issue? I assume this is a common problem in game development.

PS: The only solution I could think of is to re-position the object to the real target position as soon as the check succeeds. However, that can look a bit like a "jump" back, which does not look great.

# Answer
Definitely a common issue! Whenever you quantize time -- which is always, in a step-wise simulation -- you need to account for these boundaries.

As part of each bullet-move, you need to say something like,

```
distanceToMove = min(velocity * time, howFarTilWeGetStopped);

```

Which really is the same check you're already doing... just do it before rendering.
> 2 votes

---
Tags: algorithm, game-loop
---


title: Creating Entities from Identifiers (C#)

text:
# Question
Title: Creating Entities from Identifiers (C#)
I am writing a game in C#/XNA. Often, it's useful to have a function like this in a game engine:

```
   Entity CreateEntity(string id, Vector3 location)
   {
       ...
   }

```

So that, for instance, you can do something like this:

```
   List<string> entitiesToSpawn = { "Tree", "Bird", "Flower", ... }

   foreach (string entity in entitiesToSpawn)
   {
       CreateEntitiy(entity, location);
   }

```

Or else you can easily store the ids in data files, or populate generic GUI elements with them, for instance. What, in your opinion, is the best way to implement `CreateEntity` in such a way that is scalable and preserves this kind of interface? Right now, I have a gigantic static switch statement, which is obviously not sustainable. Perhaps I can create a big static map of strings to functions? Or is there an easier way to get this kind of functionality out of my engine?

# Answer
It's a nice approach and really useful especially if you are planning to add level files. Surely a gigantic switch will not work for too many Entities. I think you should use a map. But instead of making it static you can create a class `EntityFactory` which will include it. This `EntityFactory` may have two methods. One to create new Entities and one to Add new Entities to the map.

```
public class EntityFactory
{
    private Dictionary<string, Func<Entity>> factoryMethods = new Dictionary<string, Func<Entity>>();

    public void RegisterClass<T>(string name) where T : Entity , new()
    {
        factoryMethods[name] = () => new T();
    }

    public Entity CreateEntity(string name)
    {
        return factoryMethods[name]();
    }
}

```

The `RegisterClass` method creates a simple function that only calls the constructor of the `T` type.

You can use it like this:

`factory.RegisterClass<TreeEntity>("tree");`

`Entity tree = factory.CreateEntity("tree")`

Of course you will need at some point to register all your classes. This can be done at the start of your game.

Edit: This is how you could use this piece of code if you wanted to automatically register all Entity types using reflection:

```
        var assembly = Assembly.GetAssembly(typeof(Entity));
        var entityTypes = assembly.GetTypes().Where(t => t.BaseType == typeof(Entity));//get everything that derives from Entity
        foreach(var type in entityTypes)
        {
            string name = type.Name;

            //call the generic method of the factory using the type of the entity
            MethodInfo method = typeof(EntityFactory).GetMethod("RegisterClass").MakeGenericMethod(new Type[] { type });
            method.Invoke(factory, new object[] { name });
        }

```

This will register all classes that derive from Entity with name their class name. For instance `class TreeEntity : Entity` will be registered as `"TreeEntity"`

Although it works, personally I would not chose this approach. Also one side note, this will only work for all classes that directly derive from `Entity` if you need to, you can change the criterion of type selection in `Where(t => t.BaseType == typeof(Entity))`. Again this piece of code should be called at the start of your game.
> 1 votes

# Answer
I'm a bit late to the party, but here is my solution from my games EntityManager. It avoids static maps and switch statements.

I've commented the code to help explain what it does.

```
/// <summary>
/// Creates an entity from a given XML block.
/// </summary>
/// <param name="data">The XML string containing the entities data.</param>
/// <returns>The created entity, or null if the entity could not be created.</returns>
public AEntity CreateNewEntity(string data)
{
    // convert the XML string to a Linq XML element
    XElement element = XElement.Parse(data);

    // find the entity type
    string entityType = element.Element("entityType").Value;

    // get the local namespace and attach the entity type to it
    string t = string.Format("{0}.{1}", this.GetType().Namespace, entityType);
    // try and find the class type of our entity
    Type T = Type.GetType(t);
    // no type - return
    if (T == null)
        return null;

    // otherwise lets create an instance of our entity, assign it an ID, and then load it
    AEntity entity = (AEntity)Activator.CreateInstance(T, GetRandomID());
    entity.Load(element);

    // return our new entity
    return entity;
}

```

The basic entity:

```
abstract class AEntity
{
    public int ID
    {
        get;
        protected set;
    }

    public AEntity(int id)
    {
        ID = id;
    }

    // Other stuff here
}

```

And a sample entity in XML format is as follows (from a much large XML list):

```
<entity>
    <entityType>EntityPlayer</entityType>
    <position x="0" y="0" z="0"/>
</entity>

```

So far this has worked for me, but it has the following limitations:

* Entity classes need to be in the same namespace as my manager.
* Entities need to have the class name specified in the XML, so if I rename a class, I need to update all the XML's, or just find/replace (not that it happens often).
* Doesn't report an error when an unknown entity type is encountered, only returns null to indicate it couldn't create.

1) Isn't much of a problem for me - everything entity related lives in its own entity namespace. 3) Isn't much of a problem either, since a null result can be considered an error, its just that I don't get any more additional data out of it. 2) is the biggest problem, but I think defining codes to differentiate entities is a problem that every sort of entity system faces (and is also the point of the original question as well) so its kind of a moot point.
> 0 votes

---
Tags: xna, c#, serialization, entities
---


title: How to setup glOrtho and Viewport

text:
# Question
Title: How to setup glOrtho and Viewport
When setting up a window I set 6 variables in my render class

```
int windowWidth;    // the width of the window
int windowHeight;   //the height of the window
int dimL;           // the coordinate of the left side of the display
int dimR;           // the coordinate of the right side of the display
int dimB;           // the coordinate of the top side of the display
int dimT;           //the coordinate of the bottom side of the display

```

In my initiation routine, i set the displayMode like this:

`Display.setDisplayMode(new DisplayMode(windowWidth, windowHeight));`

I set glOrtho like this:

```
GL11.glOrtho(dimL, dimR, dimB, dimT, 1, -1);

```

now my question is:

Using these variables how can i configure glViewport to have the area defined by the dimX variables fill the display?

thanks!

# Answer
> 0 votes
It might help if you knew that the viewport defines the region (in terms of window-space coordinates) where your scene is projected to. If you had no projection matrix at all, then the coordinates (**-1**,**-1**) would map to the lower-left corner of your viewport and the coordinates (**1**,**1**) would map to the top-right. We call that coordinate space "Normalized Device Coordinates" and they make illustrating how the viewport mapping works a lot easier.

The `glViewport (...)` call is effectively to establish the window-space coordinates of the bottom-left and top-right corners. Using the above-mentioned information, you should come up with this:

```
glViewport (dimL, dimB,  dimR - dimL, dimT - dimB)

// First two parameters are the window-space origin (bottom-left)
// The remaining two are the width and height of the viewport

```

### Here is an illustration of the relation between projection and viewport discussed above:

*For more details see the following article.*

---

Keep in mind that the viewport only defines the region that geometry projects to. When you clear the color, depth and stencil buffers it will clear your entire window's framebuffer. If you only want to clear the region defined by `dimX`, then you will need to use a scissor rectangle in addition.

# Answer
> -1 votes
`glViewport()` specifies the part of the window to which OpenGL will draw (in pixels).

`glOrtho()` specifies the projection matrix to use inside the viewport.

To make the coordinates specified by `glOrtho()` fill the whole window, you would call `glViewport(0,0,windowWidth,windowHeight);`.

Or alternately, not call `glViewport()` at all, since OpenGL's default viewport already fills the whole window.

---
Tags: lwjgl, viewport
---


title: Get a GID listing?

text:
# Question
Title: Get a GID listing?
I have about 16 tiles in my spritesheet that I'm using for Tiled, and I'm trying to build a GID map so I can properly convert them in my game. I'm using the JSON format for my map, if that helps.

What I would like is a way to say "this sprite is most definitely this GID" but there doesn't appear to be any option in the Tiled GUI to get a GID for a sprite.

I need this so I can figure out which tiles correspond with which GID when I load the map.

What can I do to accomplish this? Or is there a better way to do what I want?

# Answer
Your easiest option is to just use an existing library or game engine that supports the Tiled map format. Then you don't have to worry about GIDs or which sprites to use; you simply load the Tiled map and the associated spritesheets, and the Tiled API will let you render the map on a per-layer basis - no need to worry about individual tiles or sprites.

This is because the GID is an internal ID used by the Tiled map format; it's an ID that uniquely identifies a type of tile in a map, given that the map could contain multiple layers and spritesheets. The map itself is expressed as a bunch of layers, and each layer contains a big list of GIDs. Elsewhere in the map file, there will be a section describing the tilesets used, and each of them will occupy a range of GIDs. That is, GIDs 1-128 (for example) might use the first tileset, GIDs 129-512 might use the second and so on. You can see how GIDs can be fragile: if you change the order of the tilesets, the ranges of the GIDs will change.

## How to tell which tiles are which

This is all fine if all you care about is rendering. For games this is not nearly enough. We might want to know whether tiles are:

* Impassable, or opaque or whatever, so the engine can treat them as such
* Where we need to spawn enemies, or place pickups etc.

This is the real problem we want to solve; GID is just a means to this and is quite poor in that regard too. We have very little control over it; we can't tell Tiled that "instead of GID 123, I want to use *wall* or *w* as the value so I can look for this in code", or "always use GID 1 as tile #1 in the *Walls* tileset". So I suggest keeping away from exact values of GID and using one of the following techniques:

### Differentiate special tiles by tileset

That is, instead of remembering that GIDs 56-68 are walls (and breaking once you update the tilesets/layers), you keep all your walls in the one tileset/spritesheet, give the tileset a name (e.g. *Walls*), and treating all tiles that came from that tilesets as walls. You still need to compare the GID with all the `firstgid`s of all the tilesets to figure out which tileset that GID belongs to, but you can now add/remove wall tiles with impunity.

### Differentiate special tiles by layer

You can also keep all walls in the same layer, and give it a special name to look for. The downside is that your map editors will need to take care and draw only walls in the wall layer and everything else on other layers, lest you end up with intangible wall-tiles and impassable non-wall-tiles because they were on the wrong layer. The upside is that you have full freedom in composing your tilesets, to suit your artist / texture packer.

Unfortunately both approaches requires some human diligence, whether that's the people that make the tilesets or the people making the maps. For a more fool-proof solution, you may need to make your own modified version of Tiled Map Editor that enforces said restrictions.
> 0 votes

---
Tags: tiles, tilemap, tiled
---


# Question
Title: How to make a function in Haxe that reads content from text file and does something with each line?
How can I make a function in **Haxe** that reads a line from a text file, prints it/saves it to a variable, and then goes to the next line?

My objective is to make the dialogues on a text file, having the code read a line, and if the first word (a keyword like 'Dialogue01') is found, it reads all the text after such keyword on the same line and it checks the next line for another keyword or a different command to notify the game to advance or show the next dialogue.

# Answer
First parse the text to a list with something like this

```
private function parseText(text:String):Array<String>
        {
            var dialog:Array<String>=new Array();
            var lines:Array = text.split("\n");// split in all lines
            var line:String;
            while (lines.length>0)
            {
                line= lines.shift().replace("\r", "");// remove more hidden info...
                if (line.length != 0)
                {
                    //you can create a switch if you are not just adding dialogues
                    // just add if(line.indexOf("Dialogue")!=-1)
                    dialog.push(line);
                }
            }
        }

```

After that it's easier to work with each line. If you want to use codes for example Dialogue01 is better to add another char like : or _ at the end of the word to identify key words. Use the split(":") function to separate the parts. That way you can separate a line with your char. In the right side you get your line and on the left side you get your keyword "Dialogue" and the rest can be parsed as a number. That way you dont have to worry to write Dialogue01: or Dialogue1: or Dialogue1234:
> 0 votes

# Answer
You can try my open source TextParser class in HaXe: http://bruce-lab.blogspot.com/2014/11/textparser-simple-class-for-parsing.html (tutorial)

The class is very simple, functions ReadInteger() and ReadString() can be used to get string or integer from a text file. Function GotoNextLine() can move the position of the file pointer to the next line. The class has been use in my JiuGongGe UI for reading layout from a text file.

If you have any problem with the class, let me know.
> 0 votes

---
Tags: text, file, haxe
---


# Question
Title: Is this a viable architecture for lag compensation?
In some games/engines (such as Source), the server compensates for latency by applying player inputs in the past. Whenever the server receives a player's input for a frame, it rewinds the game to the frame that input was intended for, applies the player input, then simulates the game again up to the current time. The server needs to do several times as much game-logic computation as the clients, as each frame can be simulated many times - so it seems like this would not scale well to many clients or processing-intensive games.

However, we can turn this around. If the client input for a particular frame always arrives before the server simulates that frame, then the server never needs to rewind - it only ever simulates each frame once.

In order for a player's input to reach the server before the frame that the player entered it on, the client needs to run in advance of the server. If a particular client has a latency of 250 ms, then it must simulate tick 51388 at least 250ms before the server simulates tick 51388.

Therefore, the client must be predicting the game state several ticks in advance. Every time the client receives an update from the server, the *client* rewinds the game, applies the update, and fast-forwards up to the current time.

If *n* is the number of clients, then the clients each do *O(n)* extra work per tick to support lag compensation, instead of the server doing *O(n^(2))* extra work per tick (assuming the game state size scales as *O(n)*).

I don't know of any games that actually do this. What are the problems with this approach?

# Answer
> 2 votes
You want the server doing lag compensation because that's its job. In a multiplayer environment, the client is in charge of graphics, and movement lag compensation (smoothness of movement). The server is in charge of physics, computations between players and objects, as well as lag compensation(assurance of accuracy).

In the end, the server still has to verify the accuracy of your aim on whoever you shot.

With the client prediction you have, you can't guarantee the enemy will be in your sights when you fire because the client predicted where everyone was and when you shoot, your assuming your aim is accurate entirely on the clients prediction. Just like a crazy driver on the freeway, you cant accurately predict they were going to cut off the big rig and get sandwiched.

in a more technical form, each time you fire, the client sends a timestamp of when you fired, not the tick you were on. The server looks back at the tick closest to that timestamp and determines if you were accurate. This is why you die a second after you ducked behind the wall in battlefield. The enemy shot while you were standing, and the round hit you, but the server verifies and tells all players.

# Answer
> 2 votes
If you shift the work to the clients, they have to do even more work than the server does.

They will have to rewind the same way as each client sends their input to each clients and the rewinding will be done on double the latency (250ms (clientA-\>server) + 250ms (server-\>clientB)) as inputs are relayed over to the other clients through the server.

The idea of having the server do all the work and send the solution over is so that clients with cheap PCs and consoles can still play the game and that the one with the least lag, the best internet connection, will process things with the least lag for the other players as possible to not penalize everyone over the entire clientA-\>Server-\>clientB ping-pong.

# Answer
> 2 votes
In addition to the other answers about the extra work it presents, I will make two other points:

1. As the game developer, you likely have control over the servers you're running. This means you can ensure your server meets the requirements necessary to run your game. Even if you let others run your server on their own machines, it's easy to say that they need to match certain requirements. The requirements of a game server are expected to be high. Meanwhile, you don't have control of the client machines, and the more machines you can target the better, so it's best to reduce the amount of computation that clients need to perform. Server requirements are expected to be high, but players expect you to work to decrease their technical requirements.
2. Split-responsibilities. Similar to OOP's Single-Responsibility Principle or the reason for splitting up the responsibilities in a framework like MVC or Entity-Component-System, it's important to decide what is responsible for what and maintain that. Specifically, what I would point out is that client input can never be trusted, the server needs to validate everything. So if the server would need to validate the input, which can only be done by rewinding anyway, then you're just doing the same calculations anyway. Ultimately, it's best to have the client do as few computations as possible and let the server handle the majority of the work on things like physics.

Lag compensation, like physics and player interactions, is ultimately the server's responsibility.

---
Tags: architecture, networking
---


# Question
Title: Making dialog "clips" in libGDX or in general?
I'm new to libGDX (I just released my first game), and I've started thinking about things I'd like to do next time. One thing I really want to do is, have those story type movies, where you tap the screen to advance the dialog. I'm specifically thinking of Pokemon Mystery Dungeon. A small action happens, and then the user has to tap the screen after reading what happened to move on.

My question is how can I do this? I've done a lot of research, but I can't seem to find out how to approach this. I have this vague idea where I create a different GameState using enum types in which the gameplay is modified but I don't know if there is a better way.

# Answer
> 1 votes
You would be correct in your assumption that you need to create a better "Game State Management" system for use in your game. This is how you control how the game is working.

Think about when a game is Paused. Nothing is happening, it's just waiting for the User to un-pause the game. This is essential in what you would want to do.

A basic GameState might consist of an enum like such

```
Menu
Playing
Paused
Credits

```

Which you can probably derive what each state does for the user.

You could add in a state of "cinematic" or something of that nature. I've never used libGDX, but essentially you "manage" game states by just not calling certain functions.

So to "Pause" a game, you'd set the gamestate to paused, which would not call the function that updates game logic. It just sits there, looping to receive input, so it can to be told it can call the game logic again.

```
Cinematic comes up
GameState set to Cinematic
Halts other logic, waits for user selection
User selects option
GameState switched to other state
Game continues

```

There are a lot of easy to ready gamestate examples written for XNA...even if you don't know c#, you could understand the logic just by looking at them. I'd suggest studying them.

---
Tags: android, libgdx, npc, architecture
---


title: Unity3D : Prefab Instancing Issue

text:
# Question
Title: Unity3D : Prefab Instancing Issue
I am using latest unity engine and I am having a scripting issue.

I create a prefab , added a few scripts to it and I am trying to instantiate a few of those objects like this :

```
        GameObject go = Instantiate(Prefab) as GameObject;
        var co = go.GetComponent<MyScriptA>();

```

Issue here is co is always null, this means that MyScriptA is no on the go instance. Accessing the prefab.GetComponent also returns null, but the prefab has the scripts in the editor and its assigned also in the editor to the Prefab variable (drag dropping). So I am not sure what might be wrong. For example if I Debug.Log(prefab) its not null.

So what am I doing wrong here?

# Answer
> 1 votes
```
GameObject go = Instantiate(Prefab) as GameObject;

```

Since go is a gameobject your prefab must also be a gameobject Make sure you have something like

```
GameObject prefab;

```

at the start rather than

```
Transform prefab;

```

---
Tags: c#, unity
---


# Question
Title: How would a game-state snapshot system be implemented for networked real-time games?
I want to create a simple client-server real-time multiplayer game as a project for my networking class.

I've read a lot about real-time multiplayer network models and I understand the relationships between the client and the server and lag-compensation techniques.

What I want to do is something similar to the Quake 3 network model: basically, the server stores a snapshot of the whole game state; upon receiving input from the clients, the server creates a new snapshot reflecting the changes. Then, it calculates the differences between the new snapshot and the last one and sends them to the clients, so that they can be in sync.

This approach seems really solid to me - if the client and server have a stable connection, only the minimal necessary amount of data will be sent to keep them in sync. If the client gets out of sync, a full snapshot can be requested as well.

I cannot, however, find a good way to implement the snapshot system. I find it really hard to move away from single-player programming architecture and think about how I could store the game state in such a way that:

* All the data is separated from the logic
* Differences can be calculated between snapshot of game states
* Game entities can be still easily manipulated via code

How is a **snapshot** class implemented? How are the entities and their data stored? Does every client entity have an ID that matches an ID on the server?

How are snapshot differences calculated?

In general: **how would a game-state snapshot system be implemented?**

# Answer
You can calculate snapshot delta (changes to its previous synced state) by keeping two snapshots instances: current one and last synced one.

When client input arrives you modify current snapshot. Then when it's time to send delta to clients, you calculate last synced snapshot with current one field-by-field (recursively) and calculate and serialise delta. For serialisation you can assign unique ID to each field in scope of its class (as opposed to global state scope). Client and server should share the same data structure for global state so client understands what a particular ID is applied to.

Then, when delta is calculated you clone current state and make it the last synced one, so now you have identical current and last synced state but different instances so you can modify current state and not affect the other.

This approach can be easier to implement, especially with help of reflection (if you have such a luxury), but can be slow, even if you highly opitimise reflection part (by building your data schema to cache most reflection calls). Mainly because you need to compare two copies of potentially large state. Of course it depends how you implement comparison and your language. It can be fast in C++ with hardcoded comparator but not so flexible: any change of your global state structure requires modification of this comparator, and these changes are so frequent on initial project stages.

Another approach is to use dirty flags. Each time client input arrives you apply it to your single copy of global state and flag corresponding field(s) as dirty. Then when it's time to sync clients you serialise dirty fields (recursively) using the same unique IDs. (Minor) drawback is that sometimes you send more data than strictly required: e.g. `int field1` was initially 0, then assigned 1 (and flagged dirty) and after that assigned 0 again (but remains dirty). Benefit is that having huge hierarchical data structure you don't need to analyse it completely to calculate delta, only dirty paths.

In general, this task can be quite complicated, depends how flexible should be final solution. E.g. Unity3D 5 (upcoming) will use attributes to specify data that should be auto-synced to clients (very flexible approach, you don't need to do anything except adding an attribute to your field(s)) and then generate code as a post-build step. More details here.
> 3 votes

# Answer
First you need to know how to represent your relevant data in a protocol compliant manner. This depends on the data relevant to the game. I will use an RTS game as an example.

For networking purposes, all entities in the game are enumerated (e.g. pickups, units, buildings, natural resources, destructibles).

The players need to have the data relevant to them (for instance all visible units):

* Are they alive or dead?
* What type are they?
* How much health do they have left?
* Current position, rotation, velocity (speed + direction), path in the near future...
* Activity: Attacking, walking, building, fixing, healing, etc...
* buff/debuff status effects
* and possibly other stats like mana, shields and what not?

At first the player must receive the full state before she can enter the game (or alternatively all info relevant to that player).

Each unit has an integer ID. Attributes are enumerated and therefore have integral identifiers too. The units IDs don't have to be 32 bits long (it could be if we aren't frugal). It could very well be 20 bits (leaving 10bits for the attributes). The units' ID has to be unique, it could very well be assigned by a counter when the unit is instantiated and/or added to the game world (buildings and resources are considered an immobile unit and resources could be assigned an ID when the map is loaded).

The server stores the current global state. Each player's most recent updated state is represented by a pointer to a `list` of recent changes (all the changes after the pointer have not been sent to that player yet). Changes are added to the `list` when they occur. Once the server is done with sending the last update, it can begin to iterate over the list: the server moves the player's pointer along the list to it's tail, collecting all changes along the way and placing them in a buffer that will be sent to the player(i.e the protocol's format can be something like this: unit\_id; attr\_id; new\_value) New units are considered changes as well and are sent with all their attribute values to the receiving players.

If you are not using a language with a garbage collector, you will need to setup a lazy pointer that will be lagging behind and then catching up to the most outdated player pointer in the list, freeing objects along the way. You can remember which player is the most outdated inside a priority heap or simply iterate and free until the lazy pointer equals (i.e points to the same item as one of the players pointers).

Some questions you did not raise and I think are interesting are:

1. Should the clients receive a snapshot with all the data in the first place? What about items outside their line of vision? What about fog of war in RTS games? If you send all the data, the client could be hacked to display data that should not be available to the player (depending on other security measures you take). If you only send relevant data, the issue is resolved.
2. When is it vital to send changes instead of sending all the information? Considering the bandwidth available on modern machines, do we gain anything from sending a "delta" instead of sending all the information, if so when?
> 1 votes

---
Tags: architecture, networking, multiplayer, game-state
---


# Question
Title: Is it possible to create sqlite database only for android in LIBGDX game?
I want to know if I can just implement sqlite database for android in libgdx game? Also if this is not possible then may I know the simple way to integrate libgdx game to just store scores in sqlite database. I dont want to use preference or jason because I have to get last stored scores and then level wise comparison of scores.

# Answer
To use platform specific code in libgdx you make an interface in your core project.

```

interface SaveScore {
   public void saveScore(int score);
}

```

And then make an implementation in your android project and any other projects you might have (desktop, ios and so on).

```

public class SaveScoreAndroid implements SaveScore {
    public void saveScore(int score) {
        //Platform specific code goes here
    }
}

```

Then you make your application listener take in an implementation of the interface as an argument in the constructor. Now you can pass in the platform specific implementation of the interface in the starter class of your android project.

```
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    initialize(new MyGame(new SaveScoreAndroid()), config);
}

```
> 0 votes

---
Tags: android, game-design, libgdx, databases
---


title: At what scale do I need to make tools?

text:
# Question
Title: At what scale do I need to make tools?
In making a game, if I'm writing my own engine, at what sort of scale of team should I invest time in making a level editor tool? If it's just me on my own will it be worth it? Or when there's a team of two? ten?

By what metric do I judge if making the tool is "worth it"? Or is it always worth the time investment?

# Answer
The number of team members is irrelevant.

Whether or not to invest time in tool development is a simple cost/benefit analysis.

Make an estimate how many hours it will take to develop a tool and how many hours of work it will save you in the long run. When the first number is smaller than the second, go for it, otherwise do it manually.

Also, never forget to check which 3rd party tools are available for your purpose. Adapting an existing tool is usually magnitudes less work than developing a comparable tool from scratch, even when it means that you might have to do some modifications to your engine, the tool itself or write some form of middleware. The first 3rd party tool you should consider using when planning a game development project is the game engine. Very few game projects have so unique and exotic technical requirements that using a standard game engine is more work than developing your own from scratch.
> 3 votes

---
Tags: tools
---


# Question
Title: How can I smoothly move from tile to tile?
I've looked at other games with tile based movement. I am aiming to create a game like pokemon, where the player moves smoothly to the next tile.

I am using KeyAdapter, in my KeyInput class. This basically just sets a move speed which is added to the x position of my player in the player's tick function:

```
if(key == KeyEvent.VK_A && ((Player)object).velY == 0){
    object.setVelX(-3);
    ((Player)object).setDirection(Direction.LEFT);
}
//The other keys as well...

```

In my tick method, as I said it basically just adds it:

```
public void tick() {
    x += velX;
    y += velY;
}

```

And it renders in my render method through Awt Graphics. Anyways, I was wondering how I could make this have tile based movement. Each tile is 32x32 pixels. I've looked at other tutorials and they all seem to have different solutions, I'm not sure it will be compatible with what I'm using a KeyAdaptor. I assume I might have to use a modulus operator to make sure the movement is in tiles.

# Answer
Use another set of variables to track where you are suppose to be, as well as where you are at.

```
if(key == KeyEvent.VK_A && ((Player)object).velY == 0){
    object.setVelX(-3);
    ((Player)object).setDirection(Direction.LEFT);
    currentTileX -= 32;
}

```

And then you could do something like this

```
public void tick() {
    if (x != currentX && y != currentY) {
        x += velX;
        y += velY;
    }

    if ((x - currentX) < velX) {
       x = currentX;
    }

    if ((y - currentY) < velY) {
       y = currentY;
    }
}

```

This example probably still needs some tweaking to make it just like you want, but it should get you started.
> 1 votes

---
Tags: java, tiles, movement
---


# Question
Title: box2d rendering performance degrading extremely even with sleeping bodies?
I'm working on my first smartphone game, a simple 2D platformer built with libgdx. Game maps use the Tiled level format, so a map is just a bunch of blocks. I recently started using box2d to implement character collision and movement.

So this is probably naive, but what I did is for a level consisting of 64x50 (= 3200) blocks, I added a static body for every block to represent the physics for this geometry. I set these blocks to sleep, which I thought would be a hint for box2d to disregard these blocks when stepping the simulation unless they're actually interacting with the player (the only dynamic body), so this shouldn't hinder performance very much? I recall reading in the box2d manual that it employs a spatial algorithm to only even look at the bodies relevant to render the current frame.

Yet having these 3500 sleeping static bodies degrades performance to such a degree that even when running the game on my MacBook Pro 2012 in a Genymotion emulator, I get about 5 FPS.

I suppose I'm doing something terribly wrong. My questions would be:

* when dealing with bodies in the thousands, am I supposed to remove/add box2d bodies for my level geometry dynamically to improve performance, e.g. based on a fixed box around the player? that sounds painful and I'm wondering why the library wouldn't be able to figure out itself
* maybe I've just made a mistake mapping map tiles to box2d bodies? I've posted my setup code below

Any help appreciated.

Here's how I attach the static bodies to the level geometry; it just walks the map and creates a static body for every block:

```
private void addB2Bodies(World b2World) {
    for (int row = 0; row < blocksLayer.getHeight(); row++) {
        for (int col = 0; col < blocksLayer.getWidth(); col++) {
            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyDef.BodyType.StaticBody;
            bodyDef.awake = false;
            bodyDef.position.set(col + 0.5F, row + 0.5F);

            final PolygonShape shape = new PolygonShape();
            shape.setAsBox(0.5F, 0.5F);
            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = shape;
            fixtureDef.friction = 0;

            final Body body = b2World.createBody(bodyDef);
            body.createFixture(fixtureDef);
            blocks[col][row] = body;
        }
    }
}

```

I only have one dynamic body, the player. As for the simulation, I step it at 1 / 60, with the default/recommended iteration counts of 6 and 2.

# Answer
> 2 votes
Okay I feel like an idiot now. The problem was that I had the box2d debug renderer running all along. The only thing it does is render a bunch of lines around boxes which I didn't think would be that costly, and I found it to be quite useful so never turned it off during development.

Thanks for your input though.

PS: Still curious though as to why it would drop my frame rate so much. It really only drew a grid around the tiles in my game. How can it be that expensive?

# Answer
> 5 votes
> Yet having these 3500 sleeping static bodies degrades performance to such a degree that even when running the game on my MacBook Pro 2012 in a Genymotion emulator, I get about 5 FPS.

As Anko said in his comment, you shouldn't be guessing about whether this is Box2D or rendering or something else. Measure what's taking all the frame time. Use a profiler and collect hard data indicating whether it's Box2D, your custom rendering code, or some other game logic that's taking up all that time. This problem may literally have nothing to do with Box2D at all.

> maybe I've just made a mistake mapping map tiles to box2d bodies? I've posted my setup code below

You should not create a new body for each tile.

That's not only inefficient but has various implications for the simulation that you'll likely run into before too long. Namely, dynamic bodies can "catch" on the inner edges between adjacent tiles due to how Box2D models its physics integration and collision detection (it's a discrete engine, not a continuous engine).

Look at the Edge and Chain shapes in the Box2D manual. These allow you to generate chunks of static geometry that cover many times with a single body and without inner edges to catch on. Generating correct edge and chain shapes will require a little post-processing of your tile data.

---
Tags: android, libgdx, box2d
---


# Question
Title: Handle Entities & Collision in large numbers
I am creating a simple 2D maze game and I am a little confused about entities & collision detection.

At the moment, my entity class is an abstract class containing position, velocity, sprite and a booolean named shouldRender, as well as a tick and render method. Should I go with this or lean towards a component based entity system? If so, how would I implement that in java?

Also, when I update and render my entities I have a class named Level, which holds an arraylist with all entities. When updating and rendering my entities, I iterate through this list and render the entities that are visible in the camera, via the shouldRender boolean. However, all entities are updated, which makes the FPS drop.

Also, when checking for collisions: should I use a Rectangleand loop through all entities in the list and check if the current entity is colliding with any other entity? Or should I lean more towards stuff like quadtrees etc? (And how would I implement those?)

Because when every entity has to check for collisions with all other entities on the map the game runs at 10-20FPS, which is not too good.

So, if anyone could explain this to me, I would be very thankful!

# Answer
> 0 votes
`Should I go with abstract class or lean towards a component based entity system?`

What you are doing is fine. If its working and its fast enough, dont change it unless it doesnt meet all your requirements.

`All entities are updated, which makes the FPS drop.`

The first solution to this problem should also be: do I need to update all the entities? Is some of my entities stationary? Eg walls? If so, why bother calling the update method? Is it possible to create an list that contains `ObjectsRequiringUpdates` and only update those?

`should I lean more towards stuff like quadtrees etc?`

Did you have unnecessary collision checks? Did you check wall to wall collision? If so, remove all of these! The more collisions checks you can knock off the better. If you are working in a 2D maze game my guess is that quadtrees are not necessary and your problem is probably doing too much unnecessary work.

And finally, profile first to determine which area is the bottleneck first before applying optimizations.

---
Tags: java, 2d, collision-detection, entity
---


# Question
Title: How can I change the rendering backend on Windows in Monogame?
I'm using MonoGame with Visual Studio 2013 Express. I'd like to switch from a SharpDX backend to OpenGL and OpenAL. How do I achieve that?

# Answer
> 4 votes
Unfortunately, there is no way to do this with an existing project, without a bit of a workaround. Here are the steps:

* Select `Create a new project` from inside of the IDE.
* Next, you have to select the appropriate project type, in this case either `MonoGame Windows Project` or `MonoGame Windows OpenGL Project`. Both options should be available, and the only difference that I have seen inside of the Monogame source is inside of the graphics rendering code, as would be expected.
* Finally, you have to add all old code from the old project. A very important rule to follow is that you have to manually copy Game1.cs, instead of just adding the project to the new project, since there is already a file called this in the new template project. You can also copy over Program.cs, as well.

This project that you have created at this point is the one that you will now open when you want to work on it. Feel free to delete the old project, assuming all code that you want has been copied over correctly. Ensuring this is important, you could lose a lot of work if your code has not been copied.

Note (thanks to @OMGtechy) that this is only available to developers using Visual Studio, as you seem to be doing. Other IDEs may not have this option. Monodevelop, the IDE I personally use on Linux, does have this option but others may not.

**UPDATE:** It seems like there actually *is* a way to do this, but it is much more complicated and seems unnecessary for most applications (it would be easier to make a new project).

* First, you have to obtain SDL.dll somewhere on your system, and add it to the project. (Important: the DLL itself must be added to the project, not a reference.)
* After that, you must add references to the project for: Lidgren.Network, OpenTK, and Tao.Sdl.
* There may be other changes that need to be made, so don't expect this method to work out-of-the-box. There seems to be a #define that needs to be changed (first option under the Build tab when opening the .csproj properties), but when creating a new Windows OpenGL project it doesn't seem to change.

---
Tags: monogame, visual-studio
---


# Question
Title: Restricting character movement to "rails"
I'm building a Pacman clone in Unity 3D and am now thinking about how to restrict the movement of the player to the hallways that the map is made up of.

Basically, the player is only allowed to change direction at an intersection. When he is not at an intersection, he can only continue to move in the same direction, or reverse by 180°.

The simplest idea I have come up with so far is, to have little un-rendered Boxes with Colliders at every intersection, and when the player collides with one of those, the collider knows which directions the player can go from there.

This seems easy, but a lot of work. Is there an easier way to restrict the movement of the player to given track (as in a railroad), but allow him to change "onto" a different "track" at given points (those would be the intersections)?

# Answer
> 2 votes
You're over thinking this - using collisions is way too complex for the goal of a Pac-Man clone. Consider a grid approach instead, and forget collisions. If your goal is to create a clone, this is about functionality, not fads.

**Why a Grid?**

Give yourself the following conditions for a grid approach...

1. Movement is only at 90 degree angles (up, down, right, left)
2. Pellets exist only on grid points
3. The player will come to a stop on a grid point if no arrow keys (or joystick or whatever) is pressed
4. Wall/solid elements also exist only on a grid point
5. Map is wrappable - player can exit one side and come back onto the other side

**Keep It Simple!**

So basically create a 2d array the size of your map, where each entry has a value of 0 for empty, 1 for a pellet, and 2 for solid (no walk). Then, when you are trying to decide if the player can move to an adjacent cell, simply check the target cell location to see if it's solid or not. If so, no movement allowed. If solid, movement allowed. If occupied by a pellet, award a point and remove the pellet.

Put your player at some starting coordinate that is not solid with no movement. Now whenever the player wants to move, check the target cell to see if it is free (i.e., not solid). If so, move player to that spot. If there's a pellet there, give them a point. And if you allow coordinates to wrap, you can easily handle maps that wrap (e.g., go off left side of map and come back on on right).

The best thing about this approach is that it's massively portable. You could use this to make it with JavaScript/CSS or even text-based.

**Advantages**

* Super simple implementation
* Handles map wraparound in a trivial way
* Extremely portable to any environment (even a text based game on an old DOS box)
* Simple solution lets you concentrate on the real challenge, which is modelling Ghost movement :)
* Probably how the original works
* Bragging rights over how "incredibly simple the implementation is"

**Disadvantages**

* Doesn't work for curved, non-linear paths
* No bragging rights over how "incredibly complex the implementation is"

**Pseudo Code**

Here's some pseudocode...

```
// --- Map constants and vars
define MAP_WIDTH 20
define MAP_HEIGHT 20
define EMPTY 0
define PELLET 1
define SOLID 2
var map[GRID_WIDTH, GRID_HEIGHT];

// --- Built map
map = build_map();

// --- Start player at [1,1], which is open
player_x = 1;
player_y = 1;

while (game_active) {
   // --- Scoring check
   if (map[player_x, player_y] == PELLET) {
      // --- Pellet in player spot, so give point and remove pellet
      score += 1;
      map[player_x, player_y] = 0;
   }

   // --- Set target_x/y to where player will go (default to nowere)
   target_x = player_x;
   target_y = player_y;

   // --- keypress check for movement.  If target cell is free, player moves there
   switch (key) {
      case 'W': // up
         // --- Test one map cell up, allowing for possible map wrap
         target_y = player_y - 1;
         if (target_y < 0) target_y += MAP_HEIGHT;
         break;
      case 'A': // left
         target_x = player_x - 1;
         if (target_x < 0) target_x += MAP_WIDTH;
         break;
      case 'S': // down
         target_y = player_y + 1;
         if (target_y >= MAP_HEIGHT) target_y -= MAP_HEIGHT;
         break;
      case 'D': // right
         target_x = player_x + 1;
         if (target_x >= MAP_WIDTH) target_x -= MAP_WIDTH;
         break;
      default:
         // --- Do nothing
         break;
   }
   // --- Check if target for player movement is not solid
   if (map[target_x, target_y] != SOLID) {
      // --- target point is NOT solid
      // --- Presume this handles animating movement and setting player pos to target
      move_player_to(target_x, target_y);
   } else {
      // --- Player target is solid, so do nothing
   }

   // --- Perform monster logic
   move_monsters();

   // --- Render map
   render_map();
}

```

# Answer
> 2 votes
Since this is a small game, I think a 2D collision map would work great...that's what I call them. I don't know if that's the correct name.

Basically, you have an image of where they can move, defined by 2 colors. Black, White. In my example they are allowed to move on the white part. It's a duplicate of the play screen but just containing 2 colors. Ideally your sprite that you want to move would be the exact width of the movement lane, so that it would move in the appropriate directions. There wouldn't be any small pixel movements to the sides.

In a large game this would be unfeasible, however for a small pac man clone it works great. You just detect the pixel color of the collision map they are trying to move onto by its coordinates. You will always get a RGB(0,0,0) or RGB(255,255,255) back. If it's white, don't halt sprite, if its black, stop movement.

---
Tags: c#, unity, movement
---


# Question
Title: Memory strategy for multilayer, tilebased maps
I am currently developing a 2d mmorpg and am having some memory issues with regards to my tile based map. The client takes a little while to load and then sits around 1GB ram, because I am loading each tile, for each layer, into memory. My map is currently 1/3 of its expected size.

My map has multiple layers which are drawn on top of each other - ground, building, and object. Each of these layers is stored in a separate short\[\] array. My question is how can I do this better.

I have thought of some ideas:

* Load zones into memory (i.e. 500x500) and when user goes into next zone disgard and load new 500x500
* Load zones into memory (i.e. 500x500) and when user goes 250 tiles east disgard 0-250 tiles
* Read from filesystem rather than memory

Can anyone give some suggestions and perspectives as to why, which above (or other ideas) work best?

Somes notes/issues I've found:

* My game has 1 seamless world map(hard to split to zones)
* Users can be teleported by GM/DEVs - but will usually only happen if they are stuck somewhere(potiential issues for storing chunks in memory)
* My game is www.KisnardOnline.com for anyone interested.

Thanks anyone/everyone for taking a look and your help.

# Answer
> 2 votes
I can address your ideas and some of the issues related with them.

> Load zones into memory (i.e. 500x500) and when user goes into next zone disgard and load new 500x500

This is the basic idea of what you want to achieve for a seamless world. However, if left at this basic approach you will incur what is known as "image popping". When the player gets to the boundary of that zone, he will see nothing, and then, BAM, the entire zone is pushed into his screen. So, while this is the right step, it has some issues.

> Load zones into memory (i.e. 500x500) and when user goes 250 tiles east disgard 0-250 tiles

This is more of the complete step to your previous idea was looking for. Now, you are essentially buffering the viewport against image popping. This is a much better solution then the previous.

> Read from filesystem rather than memory

No, no, don't do that. Ram is MUCH faster then the file system. Not too mention, you need to have room in ram to pull in that data, so if you're blocking room for that data...just read it anyways!

> My game has 1 seamless world map(hard to split to zones)

You solved that issue with your second idea.

> Users can be teleported by GM/DEVs - but will usually only happen if they are stuck somewhere(potiential issues for storing chunks in memory)

I don't want to recommend this because I hate loading screens, but if it's an issue with graphics lag etc, you might have to throw up a loading screen when gm teleports them. Or, just let the elements pop in. It's fun to watch sometimes.

# Answer
> 0 votes
Here is what I have come up with so far (note: player is in center of chunk & chunk always odd number sized)... It has the following issues(when the character is on the edge of the map):

* change characterX/Y to 0,0 and the bottom left(0,2) coordinate will be 7

> 0, 0, 0
>
> 0, 1, 1
>
> 7, 1, 8
* change characterX/Y to 8,8 and the top right(2,0) coordinate of the chunk will be 7

> 1, 1, 6
>
> 1, 1, 0
>
> 0, 0, 0

Here is the code for anyone who wants to figure this out with me or can learn from it:

```
public class MapChunkLoad {

    public static void main(String[] args) {
        short[] groundLayer;
        int mapWidth = 9;
        int mapHeight = 9;
        int chunkWidth = mapWidth / 3; //3
        int chunkHeight = mapHeight / 3; //3
        int characterX = 8;
        int characterY = 8;
        String map = "1, 1, 1, 1, 1, 1, 1, 1, 7, " +
                     "1, 8, 8, 1, 1, 1, 1, 1, 1, " +
                     "1, 8, 9, 9, 1, 1, 1, 1, 1, " +
                     "1, 1, 9, 9, 1, 1, 1, 1, 1, " +
                     "1, 1, 1, 1, 1, 1, 1, 1, 1, " +
                     "1, 1, 1, 1, 1, 1, 1, 1, 1, " +
                     "1, 1, 1, 1, 1, 1, 1, 1, 1, " +
                     "1, 1, 1, 1, 1, 1, 1, 1, 1, " +
                     "6, 1, 1, 1, 1, 1, 1, 1, 1";
        String[] strArr = map.split(", ");
        groundLayer = new short[chunkWidth * chunkHeight];

        //load chunk into groundLayer
        int arrayIndex = 0;
        int count = (characterX - (chunkWidth/2)) + ((characterY - (chunkHeight/2)) * mapWidth); //top left tile within chunk

        for (int y = 0; y < chunkHeight; y++){
            for (int x = 0; x < chunkWidth; x++){
                if (count > -1 && count < strArr.length){
                    groundLayer[arrayIndex] = Short.parseShort(strArr[count]);
                    System.out.println("arrayIndex[" + arrayIndex + "] = " + strArr[count]);
                } else {
                    groundLayer[arrayIndex] = 0;
                    System.out.println("arrayIndex[" + arrayIndex + "] = " + 0);
                }

                arrayIndex++;
                count++;
            }
            count += (mapWidth - chunkWidth);
        }

        System.out.println("");
        //print map grid
        int printcount = 0;
        for (int y = 0; y < chunkHeight; y++){
            for (int x = 0; x < chunkWidth; x++){
                if (x == chunkWidth - 1){
                    System.out.println(groundLayer[printcount]);
                } else {
                    System.out.print(groundLayer[printcount] + ", ");
                }
                printcount++;
            }
        }

    }
}

```

---
Tags: java, tilemap, memory-efficiency
---


# Question
Title: How can I set a MonoGame window's position?
How do I set the position of my window in MonoGame?

# Answer
Set the `GameWindow` object's `Position` property.

Note the, per the source as of this writing, that property only exists for Windows projects using DirectX as a back-end.
> 0 votes

---
Tags: monogame
---


# Question
Title: How do I have multiple audio sources on a single object in Unity?
I have an audio system set up wherein I have loaded all my audio clips centrally and play them on demand by passing the requesting audioSource into the sound manager.

However, there is a complication wherein if I want to overlay multiple looping sounds, I need to have multiple audio sources on an object, which is fine , so I created two in my script instantiated them and played my clips on them and then the world went crazy.

For some reason, when I create two audio Sources in an object only the latest one is ever used, even if I explicitly keep objects separated, playing a clip on one or the other plays the clip on the last one that was created, furthermore, either this last one is not created in the right place or somehow messes with the rolloff rules because I can hear it all across my level, havign just one source works fine, but putting a second one on it causes shit to go batshit insane.

Does anyone know the reason / solution for this ?

Some pseudocode :

```
guardSoundsSource = (AudioSource)gameObject.AddComponent("AudioSource");
guardSoundsSource.name = "Guard_Sounds_source";
// Setup this source

guardThrusterSource = (AudioSource)gameObject.AddComponent("AudioSource");
guardThrusterSource.name = "Guard_Thruster_Source";
// setup this source
   // play using custom Sound manager
soundMan.soundMgr.playOnSource(guardSoundsSource,"Guard_Idle_loop"
,true,GameManager.Manager.PlayerType);
   // this method prints out the name of the source the sound was to be played on and it always shows "Guard_Thruster_Source" even on the "Guard_Idle_loop" even though I clearly told it to use "Guard_Sounds_source"

```

# Answer
I can't speak exactly to the specific issue you are having, but I can say I am fairly certain you can add multiple of the same type of component to one GameObject. The best way I have found to do this is to access them is by using the "GetComponents" method call. Something like this should do:

`AudioSource[] allMyAudioSources = GetComponents<AudioSource>();`

This will return an array of AudioSources, which you can then assign to different variables and access independently without freaking things out. Something like this in C#:

```
AudioSource thrusterSource;
AudioSource guardSource;

void Start() {
    AudioSource[] allMyAudioSources = GetComponents<AudioSource>();
    thrusterSource = allMyAudioSources[0];
    guardSource = allMyAudioSources[1];
}

// These should no longer bug each other out!
guardSource.Play();
thrusterSource.Play();

```

EDIT: I thought it would be worth noting if it's not obvious, I have found the Components will populate the array in sequence from top to bottom. So it will help to keep that in mind when assigning those sound files.
> 2 votes

---
Tags: unity, audio
---


# Question
Title: Supersampling - Pixel color average calculation
I am currently trying to understand Supersampling.

Wikipedia says (or at least Wikipedia tells **me**) that multiple color samples are taken from **one** pixel to calculate the final result. But to my mind one pixel has exactly **one** color and logically, the average of an infinite amount of equal colors remains the same.

So, how can the resulting color differ from the original pixel's color?

# Answer
### You are thinking of pixels as if they are some atomic structure, indivisible; they are not.

Take a look at the following diagram from the Direct3D documentation on multisample rasterization:

Various triangulated objects are drawn here and the diagram shows a pixel structure with 4 samples (at fixed locations) per-pixel. Take a close look at the pixel in the second row of the first column; the triangle only partially covers this pixel.

If this diagram were rasterized using a single sample, then the color would be determined at the center of that pixel where the diamond shape is based on the triangle that covers it. However, this is 4x multisampling - the final (resolved) pixel color is the average of all 4 samples (one of which is not even covered by the triangle).

The key concept you seem to be missing is the final resolve. You cannot display all 4 samples on screen per-pixel and not every one of the samples is covered by the same geometry. You can get very different results when resolving from n-many samples to 1 or even simply changing the positions of the samples.
> 3 votes

# Answer
Color is computed for a zero-dimensional point. A zero-dimensional point is nice because you can say it is *definitely* either inside or outside a particular polygon.

A pixel occupies some small square (usually) area. Typically, a single point is sampled for each screen pixel, such as from the (0.5, 0.5) position within that pixel, and that value is used for the whole pixel.

Supersampling means to do that computation for more than one such point within each pixel's area, and then averaging the results appropriately. This has the effect of smoothing edges, since the pixel won't have to be "all or nothing" for the edge of a polygon that passes through it.

...hopefully the WP article will make more sense now!
> 0 votes

---
Tags: 3d, antialiasing
---