# Question
Title: Java single Array best choice for accessing pixels for manipulation?
I am just watching this tutorial https://www.youtube.com/watch?v=HwUnMy\_pR6A and the guy (who seems to be pretty competent) is using a single array to store and access the pixels of his to-be-rendered image.

I was wondering if this really is the best way to do this. The alternative of Multi-Array does have one pointer more, but Arrays do have an O(1) for accessing each index and calculating the index in a single array seems to take one addition and one multiplication operation per pixel.

And if Multi-Arrays really are bad, can't you use something with Hashing to avoid those addition and multiplication operations?

EDIT: here is his code...

```
public class Screen {
private int width, height;
public int[] pixels;

public Screen(int width, int height) {
    this.width = width;
    this.height = height;

    // creating array the size of one index/int for every pixel
    // single array has better performance than multi-array
    pixels = new int[width * height];
}

public void render() {
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            pixels[x + y * width] = 0xff00ff;
        }
    }
}
}

```

# Answer
Talking about the "best choice" is always difficult, as long as you did not specify the *task* that you intend to perform in all detail.

But here are several aspects to consider. First of all: Java is not C. The memory management is completely different, so one has to be *very* careful when trying to apply insights from one programming environment to another.

For example, your statement:

> The alternative of Multi-Array does have one pointer more, but Arrays do have an O(1) for accessing each index and calculating the index in a single array seems to take one addition and one multiplication operation per pixel.

As already pointed out in one of the linked answers: A "2D array" in C is mainly a syntactical convenience for addressing a single (1D) memory block. So when you write something like

```
array[y][x] = 123; // y comes first because y corresponds to rows and x to columns

```

in C, then this might actually be eqivalent to

```
array[x+columns*y] = 123;

```

So the argument of saving a multiplication is at least questionable here. A special case here is when you actually have an *array of pointers*, where each row is allocated manually with `malloc`. Then, the addressing scheme is different (and in fact, this may be considered as being closer to what Java does).

Additionally, Java is a language with a Just-In-Time-compiler, which makes comparisons at the level of single instructions (like multiplications) very difficult. You hardly ever know what the JIT does with your code. But in any case, you can *assume* that it will make it faster, and use the nastiest tricks that you can (not) imagine to do so.

---

Concerning the general strategy to use a 1D array for pixels, there is one reason to do this in Java (and from quickly skimming over the linked video, this reason seems to apply here) : A 1D array can conveniently be transferred into a `BufferedImage`.

This is one reason from a pure "convenience" point of view. But when talking about **performance**, there are other aspects that are far more important than a few multiplications. The first ones that come to my mind are

* Cache effects
* Implementation details

Two examples showing how they may affect performance:

## Cache effects

For the first one, you might consider the following example: It demonstrates the **significant** difference in performance between accessing pixels with

```
for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        pixels[x + y * width] = ...
    }
}

```

and with

```
for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
        pixels[x + y * width] = ...
    }
}

```

Summarized in a small test program:

```
public class PixelTestButNoBenchmark
{
    public static void main(String[] args)
    {
        long before = 0;
        long after = 0;
        double readTime = 0;
        double writeTime = 0;

        for (int size = 1000; size<=10000; size+=1000)
        {
            Screen s0 = new Screen(size, size);

            before = System.nanoTime();
            s0.writeRowMajor(size);
            after = System.nanoTime();
            writeTime = (after-before)/1e6;

            before = System.nanoTime();
            int r0 = s0.readRowMajor();
            after = System.nanoTime();
            readTime = (after-before)/1e6;

            System.out.printf(
                "Size %6d Row    major " +
                "write: %8.2f " +
                "read: %8.2f " +
                "result %d\n", size, writeTime, readTime, r0);

            Screen s1 = new Screen(size, size);

            before = System.nanoTime();
            s1.writeColumnMajor(size);
            after = System.nanoTime();
            writeTime = (after-before)/1e6;

            before = System.nanoTime();
            int r1 = s1.readColumnMajor();
            after = System.nanoTime();
            readTime = (after-before)/1e6;

            System.out.printf(
                "Size %6d Column major " +
                "write: %8.2f " +
                "read: %8.2f " +
                "result %d\n", size, writeTime, readTime, r1);

        }
    }
}

class Screen
{
    private int width, height;
    public int[] pixels;

    public Screen(int width, int height)
    {
        this.width = width;
        this.height = height;
        pixels = new int[width * height];
    }

    public void writeRowMajor(int value)
    {
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                pixels[x + y * width] = value;
            }
        }
    }

    public void writeColumnMajor(int value)
    {
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                pixels[x + y * width] = value;
            }
        }
    }

    public int readRowMajor()
    {
        int result = 0;
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                result += pixels[x + y * width];
            }
        }
        return result;
    }

    public int readColumnMajor()
    {
        int result = 0;
        for (int x = 0; x < width; x++)
        {
            for (int y = 0; y < height; y++)
            {
                result += pixels[x + y * width];
            }
        }
        return result;
    }
}

```

The details will vary, and heavily depend on the target system (and its cache size), so this is **NOT** a "benchmark", but shows that there may be a large difference. On my system, an order of magnitude, eg.

```
Size   7000 Row    major write:    46,73 read:    28,09 result -597383680
Size   7000 Column major write:   528,46 read:   500,53 result -597383680

```

The second influence may be even more tricky:

## Implementation details

The Java `BufferedImage` class is very convenient, and operations using this class can be blazingly fast.

The first condition for this is that the type of the image must be "appropriate" for the target system. In particular, I have never encountered a system where the `BuferedImage` types that are backed by `int[]` arrays have not been the fastest. That means that you should always make sure to use images of the type `TYPE_INT_ARGB` or `TYPE_INT_RGB`.

The second condition is more subtle. The engineers at Sun/Oracle employed some nasty tricks to make painting of `BufferedImages` as fast as possible. One of these optimizations is that they detect whether the image can be held in VRAM completely, or whether they have to sync the image with the contents of an array that resides in the Java world. An image that can be held in VRAM is called a "managed" image. And there are some operations that *destroy* the "managedness" of an image. One of these operations is obtaining the `DataBuffer` from the `Raster` of the image.

Again, a program where I tried to demonstrate the effect. It creates two `BufferedImage` instances. On one of them, it obtains the `DataBuffer`, and on the other one, it doesn't. Note that this is also **NOT** a "benchmark", and should be taken with a *huge* grain of salt. But it shows that obtaining the `DataBuffer` from an image can significantly reduce painting performance.

```
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.beans.Transient;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ImagePaintingTestButNoBenchmark
{
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI()
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        int size = 1200;
        BufferedImage managedBufferedImage = createImage(size);
        BufferedImage unmanagedBufferedImage = createImage(size);
        makeUnmanaged(unmanagedBufferedImage);

        final ImagePaintingPanel p = new ImagePaintingPanel(
            managedBufferedImage, unmanagedBufferedImage);
        f.add(p);

        startRepaintingThread(p);

        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    private static void startRepaintingThread(final JComponent c)
    {
        Thread t = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                while (true)
                {
                    c.repaint();
                    try
                    {
                        Thread.sleep(50);
                    }
                    catch (InterruptedException e)
                    {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    private static BufferedImage createImage(int size)
    {
        BufferedImage bufferedImage =
            new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = bufferedImage.createGraphics();
        Random r = new Random(0);
        for (int i=0; i<size; i++)
        {
            int x = r.nextInt(size);
            int y = r.nextInt(size);
            int w = r.nextInt(size);
            int h = r.nextInt(size);
            int c0 = r.nextInt(256);
            int c1 = r.nextInt(256);
            int c2 = r.nextInt(256);
            g.setColor(new Color(c0,c1,c2));
            g.fillRect(x, y, w, h);
        }
        g.dispose();
        return bufferedImage;
    }

    private static void makeUnmanaged(BufferedImage bufferedImage)
    {
        DataBuffer dataBuffer = bufferedImage.getRaster().getDataBuffer();
        DataBufferInt dataBufferInt = (DataBufferInt)dataBuffer;
        int data[] = dataBufferInt.getData();
        System.out.println("Unmanaged "+data[0]);
    }

}

class ImagePaintingPanel extends JPanel
{
    private final BufferedImage managedBufferedImage;
    private final BufferedImage unmanagedBufferedImage;

    ImagePaintingPanel(
        BufferedImage managedBufferedImage,
        BufferedImage unmanagedBufferedImage)
    {
        this.managedBufferedImage = managedBufferedImage;
        this.unmanagedBufferedImage = unmanagedBufferedImage;
    }

    @Override
    @Transient
    public Dimension getPreferredSize()
    {
        return new Dimension(
            managedBufferedImage.getWidth()+
            unmanagedBufferedImage.getWidth(),
            Math.max(
                managedBufferedImage.getHeight(),
                unmanagedBufferedImage.getHeight()));
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        long before = 0;
        long after = 0;

        before = System.nanoTime();
        g.drawImage(managedBufferedImage, 0, 0, null);
        after = System.nanoTime();
        double managedDuration = (after-before)/1e6;

        before = System.nanoTime();
        g.drawImage(unmanagedBufferedImage,
            managedBufferedImage.getWidth(), 0, null);
        after = System.nanoTime();
        double unmanagedDuration = (after-before)/1e6;

        System.out.printf("Managed   %10.5fms\n", managedDuration);
        System.out.printf("Unanaged  %10.5fms\n", unmanagedDuration);
    }

}

```

The actual impacts will here probably be even more dependent on the hardware (and the VM version!), but on my system, it prints

```
Managed      0,05151ms
Unanaged     6,27663ms

```

which means that obtaining the `DataBuffer` from a `BufferedImage` may slow down the painting by a factor of more than **100**.

(An aside: In order to avoid this slowdown, one can use the `setRGB` method, like in

```
image.setRGB(0, 0, w, h, pixels, 0, w);

```

but of course, this involves some copying. So in the end, there is a trade-off between the speed of manipulating the pixels and the speed of painting the image)
> 9 votes

# Answer
In my experience with Java arrays, I saw significant speed improvements by using a 1D array. Your results may vary, so it's important you do some testing of your own.

Consider that your primary use of this array is going to be essentially in the same way the data will be stored in RAM. This makes the memory allocation of a 1D array more beneficial. A multi-dimensional array is also going to require indexing calculations as well, they're just done behind the scenes.

With the correct level of abstraction, you can easily swap between the two methods and do some performance tests of your own.
> 1 votes

---
Tags: java, graphics, rendering, performance, pixel
---


# Question
Title: How to find collision detection side between two objects?
I am using box2D and I have two objects, one is bouncy ball and the other one is block. I'd like to find which side of the block is collided with, so I can only make the ball bounce when it hits the top.

I tried to implement many things like fixture data and by detecting position, using manifold but not get the accurate result. I also tried to calculate distance between two object but all went wrong.

# Answer
> 3 votes
On the collision, simply reference the relative positions of the two objects. If the ball is above the block, it struck the top. You *really* only have to check the y coordinate if you're sure a collision is happening. Something like the following:

Simply check to ensure the y coordinate of the circle is within a tolerance of the box half-height + the radius of the ball. You see that the ball on the left passes the test (its center is within the bounds) and the ball on the right fails (its center is out of the bounds).

# Answer
> 1 votes
Below is the code I came up with to register the side of a body that a collision occurred. I only have experience with Box2d in a javascript version: box2dweb. I am assuming this code doesn't work for your target platform, but I would guess that there is a similar solution using any Box2D implementation.

```
var listener = new b2ContactListener;

listener.BeginContact = function (contact) {

  //placeholder for contact point
  var manifold = new b2WorldManifold();

  //fill placeholder with contact "world" contact points
  contact.GetWorldManifold(manifold);

  //NOTE: m_pointCount is compared and not "m_points.length"
  //basically the b2WorldManifold starts with 2 points
  //but does not necessarily solve them
  var point_count = contact.GetManifold().m_pointCount;

  //add up midpoint intermediate values
  for (var i=0;i<point_count;i++){
    midpoint.x += manifold.m_points[i].x;
    midpoint.y += manifold.m_points[i].y;
  }

  //gets the midpoint of the contact points
  if (!(point_count <= 1)) {
    midpoint.x = midpoint.x / point_count;
    midpoint.y = midpoint.y / point_count;

  //only 1 point
  } else {
    midpoint.x = manifold.m_points[0].x;
    midpoint.y = manifold.m_points[0].y;
  }

  //use the Box2d user data field to map back to game object (ent)
  var bA = contact.GetFixtureA().GetBody().GetUserData();
  var bB = contact.GetFixtureB().GetBody().GetUserData();
  if (!bA || !bB) return;
  var A = bA.ent, B = bB.ent;

  //call each entities collision function with the midpoint of the collision
  A.onCollide(B,midpoint.x,midpoint.y);
  B.onCollide(A,midpoint.x,midpoint.y);

}

Entity.prototype.onCollide = function (other_ent,cx,cy) {

  var pos = this.body.GetPosition();

  //careful - gotcha here is that height of SetAsBox is in halves!
  var top = pos.y - this.h / 2;

  var side;

  // unless you are using "bullet" option for a fixture the
  // collision points are typically crossing into the body
  // thus .. adding minor amount of buffer to the top
  if (cy < (top + 0.01) ) {
    side = "top";
  } else {
    side = "not-top";
  }

}

//Box2d World object
world.SetContactListener(listener);

```

eg

---

This question was the closest that I could find to one I asked. I really wanted to answer your question with my own findings, but I was stumped, and had to ask my own question :)

There are a couple ways to solve this problem, but if you wanted to use collision information this should be somewhat viable.

---
Tags: ios, box2d, cocos2d-x
---


# Question
Title: How can I achieve a simple collision detection with Box2dWeb?
I'm a beginner in Box2dWeb, the version of Box2d for JavaScript.

I wrote a simple gravity system and I want to detect the collision between the box and the ground. When the falling box hits the ground, I want to execute simple function like

```
function sucs(){alert("the box on the floor!");};

```

this is my code

```
var CANVAS_WIDTH = 1024, CANVAS_HEIGHT = 700, SCALE = 30;

var b2Vec2 = Box2D.Common.Math.b2Vec2
        , b2BodyDef = Box2D.Dynamics.b2BodyDef
        , b2Body = Box2D.Dynamics.b2Body
        , b2FixtureDef = Box2D.Dynamics.b2FixtureDef
        , b2Fixture = Box2D.Dynamics.b2Fixture
        , b2World = Box2D.Dynamics.b2World
        , b2MassData = Box2D.Collision.Shapes.b2MassData
        , b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape
        , b2CircleShape = Box2D.Collision.Shapes.b2CircleShape
        , b2DebugDraw = Box2D.Dynamics.b2DebugDraw;

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

var world = new b2World(new b2Vec2(0, 8), true);

var fixDef = new b2FixtureDef();
var bodyDef = new b2BodyDef();
fixDef.density = 1.0;
fixDef.friction = 0.5;
bodyDef.type = b2Body.b2_staticBody;
fixDef.shape = new b2PolygonShape;
fixDef.shape.SetAsBox(20, 2);
bodyDef.position.Set(10, 400 / 30 + 1.8);
world.CreateBody(bodyDef).CreateFixture(fixDef);

fixDef.density = 1.0;
fixDef.friction = 0.5;
fixDef.restitution = 0.3;

bodyDef.type = b2Body.b2_dynamicBody;
bodyDef.position.Set(50 / SCALE, 0 / SCALE);
//bodyDef.linearVelocity.Set((Math.random() * 12) + 2, (Math.random() * 12) + 2);
 fixDef.shape = new b2PolygonShape();
 fixDef.shape.SetAsBox(25 / SCALE, 25 / SCALE);
 world.CreateBody(bodyDef).CreateFixture(fixDef);

 var debugDraw = new b2DebugDraw();
    debugDraw.SetSprite(document.getElementById("canvas").getContext("2d"));
    debugDraw.SetDrawScale(30.0);
    debugDraw.SetFillAlpha(0.5);
    debugDraw.SetLineThickness(1.0);
    debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
    world.SetDebugDraw(debugDraw);

var image = new Image();
image.src = "image.png";

window.setInterval(gameLoop, 1000 / 60);

function gameLoop() {

    world.Step(1 / 60, 8, 3);

    world.ClearForces();
    context.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);

    b = world.GetBodyList()
    var pos = b.GetPosition();
    context.save();
    context.translate(pos.x * SCALE, pos.y * SCALE);
    context.rotate(b.GetAngle());
    context.drawImage(image, -25, -25);
    context.restore();

    b = b.GetNext();
    pos = b.GetPosition();
    context.save();
    context.translate(pos.x * SCALE, pos.y * SCALE);
    //b.GetAngle()++;
    context.rotate(b.GetAngle());
    context.drawImage(image, -25, -25);
    context.restore();

    world.DrawDebugData();

};

```

# Answer
this is very simple to do with collision listeners. eg.

```
var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function (contact) {
  alert("the box on the floor !");
}
world.SetContactListener(listener);

```

A good api reference for box2dweb is http://www.box2dflash.org/docs/2.1a/reference/ this is actually for the flash version, but it is the closest to the api of the box2dweb javascript version that I could find
> 1 votes

---
Tags: collision-detection, javascript, box2d
---


title: How to make player rotate towards mouse

text:
# Question
Title: How to make player rotate towards mouse
I'm making a top down shooter with Three.js and Box2d. I'm displaying all of the graphics in 3d, but all of the physics are done in 2d, so it's sort of like super smash bros in a way.

Anyway, how can I make the player (a simple cube) rotate towards the mouse position? I've tried googling around, but I can't find much.

# Answer
First get the location of the mouse and the object. Then use Atan2 to get the angle between vectors. Use object as v1 in the method below and the mouse as v2. Then the float returned should be your new facing location for your object.

This is written in C#. Should be easy to convert.

```
    public static float AngleBetweenVectors(Vector2 v1, Vector2 v2)
        { return (float)Math.Atan2(v2.Y - v1.Y, v2.X - v1.X); }

```
> 0 votes

---
Tags: box2d, software-engineering, three.js
---


title: OpenGL - Calculating camera view matrix

text:
# Question
Title: OpenGL - Calculating camera view matrix
**Problem**

I am calculating the model, view and projection matrices independently to be used in my shader as follows:

```
gl_Position = projection * view * model * vec4(in_Position, 1.0);

```

When I try to calculate my camera's view matrix the Z axis is flipped and my camera seems like it is looking backwards.

My program is written in C# using the OpenTK library.

**Translation (Working)**

I've created a test scene as follows:

From my understanding of the OpenGL coordinate system they are positioned correctly.

The **model** matrix is created using:

```
Matrix4 translation = Matrix4.CreateTranslation(modelPosition);
Matrix4 model = translation;

```

The **view** matrix is created using:

```
Matrix4 translation = Matrix4.CreateTranslation(-cameraPosition);
Matrix4 view = translation;

```

**Rotation (Not-Working)**

I now want to create the camera's rotation matrix. To do this I use the camera's right, up and forward vectors:

```
// Hard coded example orientation:
// Normally calculated from up and forward
// Similar to look-at camera.
Vector3 r = Vector.UnitX;
Vector3 u = Vector3.UnitY;
Vector3 f = -Vector3.UnitZ;

Matrix4 rot = new Matrix4(
    r.X, r.Y, r.Z, 0,
    u.X, u.Y, u.Z, 0,
    f.X, f.Y, f.Z, 0,
    0.0f, 0.0f, 0.0f, 1.0f);

```

This results in the following matrix being created:

I know that multiplying by the identity matrix would produce no rotation. This is clearly not the identity matrix and therefore will apply some rotation.

I thought that because this is aligned with the OpenGL coordinate system is should produce no rotation. Is this the wrong way to calculate the rotation matrix?

I then create my view matrix as:

```
// OpenTK is row-major so the order of operations is reversed:
Matrix4 view = translation * rot;

```

Rotation almost works now but the -Z/+Z axis has been flipped, with the green cube now appearing closer to the camera. **It seems like the camera is looking backwards**, especially if I move it around.

My goal is to store the position and orientation of all objects (including the camera) as:

```
Vector3 position;
Vector3 up;
Vector3 forward;

```

Apologies for writing such a long question and thank you in advance. I've tried following tutorials/guides from many sites but I keep ending up with something wrong.

**Edit: Projection Matrix Set-up**

```
Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(
    (float)(0.5 * Math.PI),
    (float)display.Width / display.Height,
    0.1f,
    1000.0f);

```

# Answer
> 1 votes
The problem is that constructing the matrix out of the right, up, and forward vectors inherently sets up coordinates in which X points right, Y points up, and Z points forward. The Z axis in this coordinate system points the opposite of the direction it's "supposed" to point (for right-handed view space, as seen in your first diagram).

To fix the problem, you just need to build the view matrix using the camera's right, up, and *backward* (negative forward) vectors instead.

---
Tags: opengl, camera, matrix, opentk
---


# Question
Title: Download and open an zip file ingame on unity for android
I would like to know if it is possible to have a game that would download a rar or zip file from a website and extract it to the internal storage for use, and if it is a good option since i have to use a directory structure to open fbx models that have the texture on a folder with the same name of the fbx.

The App is made for android and the files should not be bigger than 30mb.

# Answer
Yes, you can use `System.IO.Compression` (there are more options out there, just google) and use whatever folder structure you want under the path defined by `Application.persistentDataPath`.

Normally with *Unity Pro* we use Asset Bundles to deal with remote assets, but what you ask is perfectly feasible.

Between both, it really depends on what you want to do, and which type of files you want to manage. If they are Unity asset files, I'd say to go with the Asset Bundles.
> 1 votes

---
Tags: android, unity, fbx
---


# Question
Title: Fixed timestep and interpolation question
I'm following Glenn Fiedlers excellent Fix Your Timestep! tutorial to step my 2D game. The problem I'm facing is in the interpolation phase in the end.

My game has a Tween-function which lets me tween properties of my game entites. Properties such as scale, shear, position, color, rotation etc. Im curious of how I'd interpolate these values, since there's a lot of them. My first thought is to keep a *previous value* of every property (colorPrev, scalePrev etc.), and interpolate between those.

Is this the correct method? To interpolate my characters I use their velocity; `renderPostion = position + (velocity * interpolation)`, but I cannot apply that to color for example.

So what is the desired method to interpolate various properties or a entity? Is there any rule of thumb to use?

# Answer
> 1 votes
For interpolation you'll need the previous state of your properties. So, the *previous value* solution should work just fine.

The generic formula for the classic lerp (linear interpolation) is

```
nextValue * alpha + previousValue * ( 1.0 - alpha )

```

where `alpha` is `accumulatedTime / timeStep` in this particular context.

However, in the case of color it's a bit different as the RGB color model doesn't really have a continuous dataset as a whole. It depends on how do you want to interpolate color. If you want to change the brightness, hue or color saturation, you could use the HSV/HSL color model and interpolate among one or more dimensions.

You can do the same with the RGB model, or any other model, but it really depends on how do you want to interpolate and what do you want to happen.

---
Tags: 2d, interpolation, fixed-timestep, timestep
---


title: Implementing movement on a grid

text:
# Question
Title: Implementing movement on a grid
I have a simple snake game, where I have other NPC snakes on the field. How do I calculate the movement of those other snakes so that they did not hit walls, and each other?

So far I have it like this:

I check for current coordinates and when there is a wall nearby I change direction to some other one. And so on, this way the snakes never collide the walls.

But not actually colliding other snakes, how do I prevent this?

I figured I could probe for the direction I'm heading and if there is anything there I would change direction too, but there is a set of situation where this won't work, for example if another snake will block off all exits later.

# Answer
> 2 votes
I can't think of a way to make it work 100% of the time but you can make the snakes choice more likely to be the best.

## Easier way

You can calculate which side of the snakes has more free squares. For example (see image below) with the snake 1. You can calculate that there is only 4 free squares on the right and much more on the left so it should probably go left.

An easy way to calculate the number of free squares would be with a recursive function. Pseudo code:

```
int num_free_square(positionX, positionY)
{
    int num = 1;

    if (arrayMap[positionX+1,positionY] == FREE)
    {
        num += num_free_square(positionX+1, positionY)
    }

    ... same for each direction

   return num;
}

```

(You would of course have to check if each square has already been counted and if you don't access space outside the array)

## Harder way

The previous solution is far from perfect. For example, on the following image the snake 1 would go right because there is only 1 square free on the left and 4 on the right. Although the next snake 3 move would have freed the path.

The solution could be to calculate the number of move the snake 1 would be able to do if the other snakes were changing direction randomly after meeting a wall. Before choosing a direction you calculate the deplacement of all the snakes during few moves.

This would require a lot of computation but you could stop at 10 moves for example and say : if the snake can go 10 moves on both way then I pick a random direction, else I go to the direction with the highest number of move. Although the choices of the other snakes will probably not be what you planned so the snakes will still be able to block each other.

---
Tags: architecture, grid
---


title: Eculidean space and vector magnitude

text:
# Question
Title: Eculidean space and vector magnitude
Below we have distances from the origin calculated in two different ways, giving the Euclidean distance, the Manhattan distance and the Chebyshev distance.

Euclidean distance is what we use to calculate the magnitude of vectors in 2D/3D games, and that makes sense to me:

Let's say we have a vector that gives us the range a spaceship with limited fuel can travel. If we calculated this with Manhattan metric, our ship could travel a distance of `X` if it were travelling horizontally or vertically, however the second it attempted to travel diagonally it could only tavel `X/2`!

So like I say, Euclidean distance does make sense. However, I still don't quite get how we calculate 'real' distances from the vector's magnitude.

Here are two points, purple at `(2,2)` and green at `(3,3)`.

We can take two points away from each other to derive a vector.

Let's create a vector to describe the magnitude and direction of purple from green:

```
|d| = purple - green
|d| = (purple.x, purple.y) - (green.x, green.y)
|d| = (2, 2) - (3, 3)
|d| = <-1,-1>

```

Let's derive the magnitude of the vector via Pythagoras to get a Euclidean measurement:

```
euc_magnitude = sqrt((x*x)+(y*y))
euc_magnitude = sqrt((-1*-1)+(-1*-1))
euc_magnitude = sqrt((1)+(1))
euc_magnitude = sqrt(2)
euc_magnitude = 1.41

```

Now, if the answer had been `1`, that would make sense to me, because `1` unit (in the direction described by the vector) from the green is bang on the purple.

But it's not. It's 1.41. 1.41 units is the direction described, to me at least, makes us overshoot the purple by almost half a unit:

So what do we do to the magnitude to allow us to calculate real distances on our point graph?

Worth noting I'm a beginner just working my way through theory. Haven't programmed a game in my life!

# Answer
Vector magnitude IS the "real distance" - no conversion necessary.

To see this, draw a scale diagram of your question on paper, and take some measurements with a ruler. Believe it or not, the distance between the green and purple dots really is bigger than the distance between the 0 and 1 ticks on the axis. About 41% bigger.

Here I've taken your diagram and made a tracing paper copy, then rotated it down to the x-axis so we can see this visually:

Another way to think about it is to draw a circle of radius one around the purple point:

Is the green dot outside the circle? Then it *must* be further away than a distance of one. It looks like the green dot is more than a third of the radius further away, but less than adding another half the radius, so somewhere in 1.33333... \< d \< 1.5

If you measure it, you can confirm that the Euclidean distance between these two points, sqrt(2)=1.414... correctly reflects the visible distance between them.
> 3 votes

---
Tags: vector
---


# Question
Title: Algorithm for optimal control on space ship using accelerometer input data
Does someone have a good algorithm for controlling a space ship in a vertical shooter game using acceleration data?

I have done a simple algorithm, but works very badly. I save an initial acceleration value (used to calibrate the movement according to the user's initial position) and I do subtract it from the current acceleration so I get a "calibrated" value. The problem is that basing the movement solely on relative acceleration has an effect of loss of sensitivity: **certain movements are independent from the initial position.**

Would anyone be able to share a a better solution? I am wondering if I should use/integrate also inputs from gyroscope hardware.

Here is my sample of code for a Cocos2d iOS game:

```
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    if (calibrationLayer.visible){
        [self evaluateCalibration:acceleration];
        initialAccelleration=acceleration;
        return;
    }

    if([self evaluatePause]){
        return;
    }

    ShooterScene * shooterScene = (ShooterScene *) [self parent];
    ShipEntity *playerSprite = [shooterScene playerShip];

    float accellerationtSensitivity = 0.5f;

    UIAccelerationValue xAccelleration = acceleration.x - initialAccelleration.x;
    UIAccelerationValue yAccelleration = acceleration.y - initialAccelleration.y;

    if(xAccelleration > 0.05 || xAccelleration < -0.05) {
        [playerSprite setPosition:CGPointMake(playerSprite.position.x +  xAccelleration * 80, playerSprite.position.y + yAccelleration * 80)];
    }
    else if(yAccelleration > 0.05 || yAccelleration < -0.05)
    {
        [playerSprite setPosition:CGPointMake(playerSprite.position.x +  xAccelleration * 80, playerSprite.position.y + yAccelleration * 80)];
    }

}

```

# Answer
> 1 votes
I think some of your problems might be caused by a naive calibration like:

```
calibratedAcceleration = currentAcceleration - initialAcceleration

```

When you're rotating your phone and not moving it then the acceleration returned will lie on a sphere with Earth G radius.

For example let's say your phone lies almost flat on the table - your acceleration X and Y values will be small and your method should work, but when you turn your phone 90 deg your acceleration X or Y will get its maximum value and your method will break. In practice, for rotations just around 15-30 deg you should start noticing some strange effects, like non-symmetrical steering in front-back directions.

To solve it you could store entire initial rotation, computed from initial acceleration vector and during the game compute actual rotation and a X/Y differences between them.

---
Tags: game-mechanics, control, user-experience
---


title: Slick and Timers?

text:
# Question
Title: Slick and Timers?
I'm making a game where I need events to happen in a precise amount of time. Explanation : I want that event A happens at 12000ms, and event B happens every 10000ms.

So "if"s should looks like this.

```
//event A
if(Ticks == 12000) //do things
//even B
if(Ticks % 10000 == 0) //do stuff

```

But now how can I have this "Ticks" value ? I tried to declare an int and then increasing it in the update method, I tried 2 ways of increasing it :

```
Ticks++;

```

It doesn't works because the update method is not always called every microseconds.

```
Ticks += delta;

```

It's kinda good but the delta is not always equals to 1, so I can miss the precise values I need in the if statements

So if you know how can I do events in a precise amount of time please tell me how can I do this

# Answer
> 2 votes
It's a simple change to logic really, simply use a `>=` test instead. If `Ticks` is greater than or equal to your trigger amount, you should fire the trigger. Then you use the `Ticks += delta;` to increment it. Additionally, you can create a more generic object to hold information for a single event.

```
class EventObject {
    float TimeSinceTrigger = 0;
    float TriggerInterval;
    boolean FireOnce;
    boolean Fired;

    public EventObject(float triggerInterval, boolean fireOnce) {
       TriggerInterval = triggerInterval;
       FireOnce = fireOnce;
    }

    public void update(float delta) {
        TimeSinceTrigger += delta;
    }

    public bool isReady() {
        if(FireOnce && Fired)
            return false;

        if(TimeSinceTrigger >= TriggerInterval) {
            //We're ready, if we fire only once, set our flag for that
            // otherwise, reset our time since trigger to fire again later.

            if(FireOnce)
                Fired = true;
            else
                TimeSinceTrigger = 0;

            return true;
        }
        return false;
    }

}

```

Then you can use that object like:

```
//Instantiate the objects
EventObject repeatingEvent = new EventObject(1000, false);
EventObject singleFireEvent = new EventObject(1000, true);

//At the beginning of your update loop:
repeatingEvent.update(delta);
singleFireEvent.update(delta);

//Wherever else in your update loop

if(repeatingEvent.isReady()) {
   RunRepeatingEventCode();
}

if(singleFireEvent.isReady()) {
   FireSingleEventCode();
}

```

With that, you're on your way to a robust event system. It could certainly use a lot of improvement. For example, keeping the event objects in a list, so you can stop updating them if they're done.

As for getting accurate delta time, you're on the right path. You `System.nanoTime()` would be used like:

```
long lastUpdate = System.nanoTime();

//In the update method

long currentTime = System.nanoTime();
long delta = currentTime - lastUpdate;
lastUpdate = currentTime;

```

---
Tags: java, slick, timer
---


# Question
Title: How do I put different textures on different walls? LWJGL
So far I have it so you are running around in a box, but all of the walls are the same texture! I've loaded up other textures for the walls (I want the walls a different texture than the floor) but it seems as if its being ignored... Here's my code:

```
        int floorTexture = glGenTextures();
    {
        InputStream in = null;
        try {
            in = new FileInputStream("floor.png");
            PNGDecoder decoder = new PNGDecoder(in);
            ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight());
            decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA);
            buffer.flip();
            glBindTexture(GL_TEXTURE_2D, floorTexture);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA,
                    GL_UNSIGNED_BYTE, buffer);
            glBindTexture(GL_TEXTURE_2D, floorTexture);

        } catch (FileNotFoundException ex) {
            System.err.println("Failed to find the texture files.");
            ex.printStackTrace();
            Display.destroy();
            System.exit(1);
        } catch (IOException ex) {
            System.err.println("Failed to load the texture files.");
            ex.printStackTrace();
            Display.destroy();
            System.exit(1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    int wallTexture = glGenTextures();
    {
        InputStream in = null;
        try {
            in = new FileInputStream("walls.png");
            PNGDecoder decoder = new PNGDecoder(in);
            ByteBuffer buffer = BufferUtils.createByteBuffer(4 * decoder.getWidth() * decoder.getHeight());
            decoder.decode(buffer, decoder.getWidth() * 4, Format.RGBA);
            buffer.flip();
            glBindTexture(GL_TEXTURE_2D, wallTexture);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, decoder.getWidth(), decoder.getHeight(), 0, GL_RGBA,
                    GL_UNSIGNED_BYTE, buffer);
            glBindTexture(GL_TEXTURE_2D, wallTexture);

        } catch (FileNotFoundException ex) {
            System.err.println("Failed to find the texture files.");
            ex.printStackTrace();
            Display.destroy();
            System.exit(1);
        } catch (IOException ex) {
            System.err.println("Failed to load the texture files.");
            ex.printStackTrace();
            Display.destroy();
            System.exit(1);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    int ceilingDisplayList = glGenLists(1);
    glNewList(ceilingDisplayList, GL_COMPILE);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(-gridSize, ceilingHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(gridSize, ceilingHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(gridSize, ceilingHeight, gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(-gridSize, ceilingHeight, gridSize);
    glEnd();
    glEndList();

    int wallDisplayList = glGenLists(1);
    glNewList(wallDisplayList, GL_COMPILE);

    glBegin(GL_QUADS);

    // North wall

    glTexCoord2f(0, 0);
    glVertex3f(-gridSize, floorHeight, -gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(gridSize, floorHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(gridSize, ceilingHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(-gridSize, ceilingHeight, -gridSize);

    // West wall

    glTexCoord2f(0, 0);
    glVertex3f(-gridSize, floorHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(-gridSize, ceilingHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(-gridSize, ceilingHeight, +gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(-gridSize, floorHeight, +gridSize);

    // East wall

    glTexCoord2f(0, 0);
    glVertex3f(+gridSize, floorHeight, -gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(+gridSize, floorHeight, +gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(+gridSize, ceilingHeight, +gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(+gridSize, ceilingHeight, -gridSize);

    // South wall

    glTexCoord2f(0, 0);
    glVertex3f(-gridSize, floorHeight, +gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(-gridSize, ceilingHeight, +gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(+gridSize, ceilingHeight, +gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(+gridSize, floorHeight, +gridSize);

    glEnd();

    glEndList();

    int floorDisplayList = glGenLists(1);
    glNewList(floorDisplayList, GL_COMPILE);
    glBegin(GL_QUADS);
    glTexCoord2f(0, 0);
    glVertex3f(-gridSize, floorHeight, -gridSize);
    glTexCoord2f(0, gridSize * 10 * tileSize);
    glVertex3f(-gridSize, floorHeight, gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, gridSize * 10 * tileSize);
    glVertex3f(gridSize, floorHeight, gridSize);
    glTexCoord2f(gridSize * 10 * tileSize, 0);
    glVertex3f(gridSize, floorHeight, -gridSize);
    glEnd();
    glEndList();

```

# Answer
You need to bind the texture before you draw the quads.

```
glBindTexture(GL_TEXTURE_2D, floorTexture);

// Draw floor quads

glBindTexture(GL_TEXTURE_2D, wallTexture);

// Draw the wall quads

```
> 2 votes

---
Tags: opengl, java, textures, lwjgl
---


title: MonoGame audio format

text:
# Question
Title: MonoGame audio format
MP4 AAC is a well supported playback format according to the docs, but the MonoGame content project only seems to compile MP3/WAV/WMA formats. I tried to put raw aac files in my android game but the content manager wouldnt load them, only raw wav files work, but they are large in size. I would like to know how to load aac or ogg audio files.

# Answer
Loading OGG files should work the same as MP3s. I have this working in my own games, as simply as (pseudocode):

```
var sound = ContentManager.Load("blah.ogg");
sound.Play();

```

The issue I ran into is that some devices (especially older ones) may not always work with every kind of file format.
> 1 votes

---
Tags: xna, monogame, monotouch
---


title: Optimal Compression for Speech

text:
# Question
Title: Optimal Compression for Speech
I'm designing a game that depends heavily on audio; I will have some 300+ speech files (most of them just a word or two long). This can very quickly escalate the size of my final game.

What's the optimal way to encode/compress speech files to keep the size minimal without getting audio artifacts?

Please address both per-file compression/encoding, and also zipping/compressing the set of all speech files together in your answer. Because I'm not sure which (or combination of both) factors will give me the best results.

**Edit:** I need this to run in Silverlight and Android, so I'm presumably stuck with only MP3 as my option (other than uncompressed wave files).

# Answer
> 6 votes
Speex is a great audio encoding designed from the ground up for use with speech.

With regards to compressing all your files together for distribution, a bare tarball or similar may be your best bet. When attempting to compress files that are already heavily compressed such as video and audio, you can sometimes end up with larger files by compressing them due to file headers and such. Be wary, but your mileage may vary.

# Answer
> 1 votes
Ogg/Opus is, as best I understand, one of the most compact speech formats available that does not significantly degrade the quality. I worked with it for a time in a former job, and the files compressed to a fraction of the size of the comparative Speex format, let alone the huge improvements over storing as an MP3 or wave. The only drawback is that there's a limited amount of pre-built material for doing the Ogg encoding/decoding. I recommend using the OpusFile library to save a lot of time and trouble.

The only other caveat is that you have a limited set of frequencies you can use natively between 8 kHz and 48 kHz and the libopus library defaults to 48k, so you'll have to downsample and upsample if you don't want to do a little modification of the source code (which I can aver is not difficult).

# Answer
> -1 votes
For human speech signal, there is no better choice than ADPCM coding.

---
Tags: android, audio, silverlight, compression
---


# Question
Title: Child object free movement on Parent object
Just to be straightforward, I am completely new to many aspects of coding and am searching for different specs and guidelines to aid me on my journey to crafting a *wonderful* game in Epic Games' **Unreal Engine 4**.

Okay, I know upon viewing this, some may have little to no clue what I mean, so I'll put it like this to explain what I mean :

Imagine a **third person game** with a simple model of a character. Now, say I have an **object as a torso** of a character in a game. Now Say I have an **object as a head** of the character. How could I **keep the head as a child of the torso**, but at the same time, allow it to **move with the camera angle**.

# Answer
> 1 votes
What I think you need is to create a `Player` object that will allow you to set up players position and orientation. Next, connect a `Torso` object as a child of `Player` so it moves and rotates with your main object.

Then connect a `Head` as the child of `Torso` so it moves with `Torso`, but can rotate in its own local space, so you can rotate a `Player` head.

At the end connect a `Camera` as a child of the `Head` and move it backward by some amount. This way a `Camera` will be always at some distance from the `Head`, looking at it, regardless of the `Head` orientation.

---
Tags: c++, character, unreal
---


# Question
Title: Unity 4.5 Sprite Packer does not pack images inside Resources folder
I'm trying to use the new Sprite Packer tool, but it doesn't work if I put the imagens inside Resouces folder, but inside any other folder it works.

is it a bug?

# Answer
> 5 votes
All files in the Resources folder exist in your built application (regardless of if they are used). This allows you to load them as needed with `Resources.Load`.

I believe Unity made the decision to prevent files in Resources being built into sprite-sheets because there would be two copies of the same sprite in the built app (which is wasteful).

This answer on the Unity forums uses the same explanation:

http://forum.unity3d.com/threads/248349-Unity-4-5-Sprite-Packer-does-not-pack-images-inside-Resources-folder

---
Tags: unity
---


# Question
Title: How should an object that uses composition set its composed components?
After struggling with various problems and reading up on component-based systems and reading Bob Nystrom's excellent book "Game Programming Patterns" and in particular the chapter on Components

I determined that this is a horrible idea:

```
//Class intended to be inherited by all objects. Engine uses Objects exclusively.
class Object : public IUpdatable, public IDrawable {
public:
    Object();
    Object(const Object& other);
    Object& operator=(const Object& rhs);

    virtual ~Object() =0;

    virtual void SetBody(const RigidBodyDef& body);
    virtual const RigidBody* GetBody() const;
    virtual RigidBody* GetBody();

    //Inherited from IUpdatable
    virtual void Update(double deltaTime);

    //Inherited from IDrawable
    virtual void Draw(BITMAP* dest);

protected:
private:
};

```

I'm attempting to refactor it into a more manageable system. Mr. Nystrom uses the constructor to set the individual components; CHANGING these components at run-time is impossible. It's intended to be derived and be used in derivative classes or factory methods where their constructors do not change at run-time. i.e. his Bjorne object is just a call to a factory method with a specific call to the GameObject constructor.

Is this a good idea? Should the object have a default constructor and setters to facilitate run-time changes or no default constructor without setters and instead use a factory method?

Given:

```
class Object {
public:
    //...See below for constructor implementation concerns.
    Object(const Object& other);
    Object& operator=(const Object& rhs);

    virtual ~Object() =0;

    //See below for Setter concerns
    IUpdatable* GetUpdater();
    IDrawable* GetRenderer();

protected:
    IUpdatable* _updater;
    IDrawable* _renderer;
private:
};

```

Should the components be read-only and passed in to the constructor via:

```
class Object {
public:
    //No default constructor.
    Object(IUpdatable* updater, IDrawable* renderer);
//...remainder is same as above...
};

```

or Should a default constructor be provided and then the components can be set at run-time?

```
class Object {
public:
    Object();
//...
SetUpdater(IUpdater* updater);
SetRenderer(IDrawable* renderer);
//...remainder is same as above...
};

```

or both?

```
class Object {
public:
    Object();
    Object(IUpdater* updater, IDrawable* renderer);
//...
SetUpdater(IUpdater* updater);
SetRenderer(IDrawable* renderer);
//...remainder is same as above...
};

```

# Answer
Ideally, your `Object` should have *no* explicit reference to its components: `IUpdater`, `IDrawable`, etc. It should rather maintain a list of pointers to a base class, ideally serialized from data:

```
class Object {
public:
    Object(const char* fromFile); // serializes _componentList
private:
    std::list< IComponent* > _componentList;
};

```

The rational is simple: the goal of a component-based architecture is to allow for modularity. If you reference everything explicitely you'll soon introduce direct dependencies between your components: removing them, adding new ones of replacing some will become a much more cumbersome task.
> 3 votes

---
Tags: c++, component-based
---


# Question
Title: Zelda-style top-down RPG. How to store tile and collision data?
I'm looking to build a Zelda: LTTP style top-down RPG. I've read a lot on the subject and am currently going back and forth on a few solutions. I'm using C#, MonoGame, and Tiled.

For my tile maps, these are the choices I can see in front of me:

1. Store each tile as its own array. Each one having 3-4 layers, texture/animation, depth, flags, and maybe collision(depending on how I do it). I've read warning about memory issues going this route, and my biggest map will probably be 160x120 tiles. My average map however will be about 40x30. The number of tiles might cut in half if I decide to double my tile size, which is currently 16x16. This is the most appealing approach for me, as I feel like I would know how to save maps, make changes, and separate it into chunks for collision checks.
2. Store the static parts of my tile map in multiple arrays acting as the different layers. Then I would just use entities for anything that wasn't static. All of the other tile data such as collisions, depth, etc., would be stored in their own layers as well I guess? This way just seems messy to me though.

Regardless of which one I choose, I'm also unsure how to plan all of that other tile data. I could write a bunch of code that would know which integer represents what tile and it's data, but if I changed a tileset in Tiled and exported it again, all of those integers could potentially change and I'd have to adjust a whole bunch of code.

My other issue is about how I could do collision. I want to at least support angled collision that slides you around the corners of objects like LTTP does, if not more oddball shapes as well. So do I:

1. Store collision as a flag for binary collision. Could I get this to support angles?
2. Would it be fine to store collision as an integer and have each number represent a certain angle of collision?
3. Store a list of rectangles or other shapes and do collision that way?

Sorry for the large two-part(three-part?) question. I felt like these needed to be asked together as I believe each choice influences the other.

# Answer
For collisions I would simply store a polygon per tile.
I don't know if you need three degrees of movement, but for two, this would be very simple. In that case I would simply store a convex polygon per tile. For example a triangle, quad, hexagon or whatever shape you need.
Then simply do circle (player) vs polygon (tile) or box (player) vs polygon (tile) collision detection. This can be done with SAT (Separating Axis Theorem). Maybe XNA already offers you something like that.
With this approach you'd automatically get nice sliding on slopes and stuff.

If I wasn't clear enough, I mean something like you see in this video (the red lines around the objects): https://www.youtube.com/watch?v=-Q6ISVaM5Ww
> 1 votes

# Answer
Well old zeldas for static geometry had everything collide as squares. You could just have an array of flags where a single bit was 'occupied'. If the bit is occupied then you just do a basic AABB to AABB test for collision. Not a terrible system for tile. You can also do something like 1 bit means texture 1, next bit means texture 2 and so forth if your not wanting to do alpha mapped textures or blending. That means a single 8-bit values can store a plethora of info. No reason to have an array per tile ... 1 Array per chunk with a width / height parameter should be fine or if you have a standard dimension of chunk you can do it that way.
> 0 votes

---
Tags: xna, c#, tiles, maps, monogame
---


# Question
Title: Create a trailing, ghosting effect of a sprite
I want to create a trailing, ghosting like effect of a sprite that's moving fast. Something very similar to this image of Sonic (apologies of bad quality, it's the only example I could find of the effect I'm looking to achieve)

However, I don't want to do this at the sprite sheet level, to avoid having to essentially double (or possibly quadruple) the amount of sprites in my atlas. It's also very labor intensive.

So is there any other way to achieve this effect? Possibly by some shader voodoo magic? I am using Unity and 2D Toolkit, if that helps.

# Answer
> 3 votes
While the particle system solution provided by LVBen does work, it's not the best suited solution when using 2D Toolkit for your sprites. The primary reason being is that it's impossible to sync up the ghost trail material in the particle system to the current sprite animation of the main prefab.

Here's the 2D Toolkit friendly solution I ended up using.

For the prefab in which you want the ghost trail to come from, attach an empty game object to it to act as the root. Under this root, attach any number of tk2dSprite or tk2dSpriteAnimator (depending if you want animated sprites or not) game objects (I added 4) and adjust their color alpha values as appropriate to achieve the ghosting/fading away effect.

In the top parent Update

```
// AmountToMove is a Vector3 of the amount we will translate this gameobject.
float y = (int)AmountToMove.y == 0 ? 0 : -AmountToMove.y;
float distanceFactor = 0.05f;
for (int i = 0; i < GhostingRoot.childCount; ++i) {
    // Based on the player's current speed and movement along the x and y axes,
    // position the ghost sprites to trail behind.
    Vector3 ghostSpriteLocalPos = Vector3.Lerp(
                                      GhostingRoot.GetChild(i).localPosition,
                                      new Vector3((-CurrentSpeed * distanceFactor * i),
                                                  (y * distanceFactor * i), 0),
                                      10f * Time.deltaTime);
    // GhostingRoot is the root gameobject that's parent to the ghost sprites.
    GhostingRoot.GetChild(i).localPosition = ghostSpriteLocalPos;
    // Sync the animations.
    // _ghostSprites is a List of the tk2dSpriteAnimator ghost sprites.
    _ghostSprites[i].Play(SpriteAnimator.CurrentClip.name);
    _ghostSprites[i].Sprite.FlipX = Sprite.FlipX;
}

```

This solution will create the trailing ghosting effect while syncing the animations of the ghost sprites with the main sprite.

# Answer
> 21 votes
You could easily do this with a particle system and a shader. Set up the particle system to release 1 particle every X milliseconds with a max of 3 particles. (Choose an X based on how far apart you want the trailing sprites to be.) For the particle, use the same image as the character's current sprite, but with a different material. Try some of the alpha blended shaders on the material to get the effect that you want on the trailing particles.

If you want to get fancier, you could adjust the max # of particles and other settings based on the character's current speed.

Here is an example that I was able to do with just 1 Quad, 1 sprite, 2 materials, and a particle system.

I attached the particle system to the Quad and set the quad to use the Sonic sprite. I'm using only the Emission, Color over Life time, and Renderer settings of the Particle System.

Max particles: 5

Simulation Space: World

Start Lifetime: 1

Start Speed: 0

Color over lifetime: Fade from White (Alpha 255) to Black (Alpha 0)

Renderer Material: Using same image as the original, but with "Particles/Alpha Blended" shader.

# Answer
> 4 votes
Just like the particle system solution, you can use 2dtoolkit to create the same effect. Add 3 children game object to the character with only a sprite attached to them. Change the alpha and coloring as needed. Then you can vary the sprite's local positions depending on the speed of the character:

```
myTransform.localPosition = characterSpeed * distanceFactor;

```

It saves a draw call (compared to particles) and gives you total control on the spread of the effect, if you want to do it smooth or staggered.

---
Tags: unity, sprites, graphic-effects
---


# Question
Title: Collision detection with heightmap based terrain
I am developing a 2D tank game. The terrain is generated by Midpoint Displacement Algorithm, so the terrain is represented by an array:

```
index --->  height of terrain
[0]   --->  5
[1]   --->  8
[2]   --->  4
[3]   --->  6
[4]   --->  8
[5]   --->  9
...         ...

```

The rendered mountain looks like this:

```
        *
  *     * *
  *     * *
  *   * * *
* *   * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
0 1 2 3 4 5 ...

```

I want tanks to be able to move smoothly on the terrain (I mean tanks can rotate according to the height when they move), but the surface of the terrain is not flat, it is polygonal. Can anyone give me some help with collision detection in this situation?

Thanks in advance.

# Answer
> 1 votes
You dont really need to do collision detection with the floor, since its expensive to calculate and im guessing the tanks are always touching the ground. All you need to do is to make the tanks height position equal to the one from your height index array. it will give the impression that the tanks are touching the floor but you are not actually calculating collision

# Answer
> 1 votes
Think of your terrain as a bunch of slanted lines. Each line has a 2 points. Each end has a height in y space. Every position between those two points has a height that is just an interpolation of the end points. So if you know the x for your tank (Tx), or for a point on your tank, you just need to calculate the height of the ground at that x. Then check to see if Ty is above Sy.

First determine which terrain line segment the tank (or point on the tank) is over. In my game I pre-sort the terrain segments so it's easier to find the right one quickly. Looks like you have them sorted as well.

Then assuming `[1].x` is bigger than `[0].x`, `[1].x-[0].x` is the x distance of that segment. Call it `Dx`. `[1].y-[0].y` is the height change or slant of that segment, `Dy`.

`Tx - [0].x` is how far through the x of that line segment your tank is.

So `(Tx - [0].x)/Dx` is a % through that segment (`Px`) represented 0-1. And `Px` is the same as `Py`. It is also the same % through the slant. Therefore `[0].y + Px*Dy` is the height of the ground at that Tx.

If your tank is a point you only have one `Tx` to solve for.

Let's say your tank is a box instead of a point. A cheap way to handle that is to do the above twice. Once for the front bottom of the tank tread and once for the back. This gives you a ground level for each end of the tank. You can easily calculate the angle the tank needs to be here. And yes rotating the tank does change the 2 points, which might require a couple passes. Or over several frames the tank would settle over the ground.

If you're worried that this would allow the tank to straddle peaks in the mountain, since you're only checking the front and back of the tread, then do the detection for 3 points: the front, middle and back. Then when going up over a peak the front of the tank will rise until gravity tips it over. It might straddle the peak a little between any two points. But this might look acceptable. Add more points if it's a problem.

To make the driving up over a peak look like the tank is tipping over it, you'd have to add some simple physics to the game. And that is outside the scope of this question. But the general idea would be to apply downward force (gravity) to probably only the front and rear collision detection points on your tank. Then detect for collisions on all, keep the points from passing through the ground. Then rotate the tank to the new angle. You might have to do 2 or 3 passes on the collision correction to keep it above ground. And you'd have to experiment to make it look good and also be fast enough. But with even 10 points and 5 passes it shouldn't lag.

Collision detection can be cheap. To make it cheap only do the math for a few points on your object. In the image above you see my 3d ship and then the collision detection points for it. I do 2d terrain detection in my game for a 3d space ship with over 700 tris, but I only detect for 20 points around the perimeter. I apply my ship rotation matrix to each point and then check for collisions and it works great and is fast.

# Answer
> 0 votes
If it is all quads it is just lerping between the values using modular arithmetic.

You have dx, dz which is the distance between nodes when scaled.

```
//Get your indices and normalized distances between.
float offsetX, offsetZ;
//this is how far the grid is offset...used to map it to indices
int Xindex = (int)((pos.x - offsetX)/dx);
int Zindex = (int)((pos.z - offsetZ)/dz);
float normModX = (pos.x - dx*Xindex)/dx; //should cache 1.0/dx as inverse_dx
float normModZ = (pos.z - dz*Zindex)/dz; //should cache 1.0/dz as inverse_dz

//Get your heights
float Y0 = Height[Xindex][Zindex];
float Y1 = Height[Xindex+1][Zindex];
float Y2 = Height[Xindex][Zindex+1];
float Y3 = Height[Xindex+1][Zindex+1];

 float height;
 //The exact way this is done depends on how your grid mesh is stitched together...
 //Now you are working with 2 triangles and you know the height of all 4 points.
 //Determine which triangle we are on. Then interpolate between the 3 heights.
 if(normModX/normModZ < 1.0f)
 {
   height = InterpolateHeights(normModX,normModZ,Y0,Y1,Y2);
 }
 else
 {
   height = InterpolateHeights(normModX,normModZ,Y1,Y2,Y3); /
 }

```

---
Tags: collision-detection, terrain, heightmap
---


# Question
Title: Can I have keyboard controls in an MMO and still do movement calcuation in the server?
I'm trying to decide between keyboard and mouse movement controls for a web-based multiplayer. It would be quite resource-intensive to use the WASD-keys and AJAX the server with controls every second.

Can I implement WASD-key movement and still have the server do all the movement calculations (to deter cheating)?

# Answer
> 3 votes
WASD is viable because for the best player experience the client (the browser) should be simulating actions based on inputs at the same time the server is verifying inputs as valid and sends you appropriate data back.

To put it in perspective, if you are playing a game and we figure on average it takes 100ms (arbitrarily picked this number - no real significance) for you to get a response from the server after pushing a button, as you already know it is going to feel awful to you as a player to wait 100ms before seeing your action occur on the screen ESPECIALLY when it comes to controlling your character.

So as I said, to resolve this you are going to simulate the action on the client as a best guess while the server validates the inputs. So if the player presses W the client knows that usually that means the character should move forward at a rate of 30 units per second and does so. If the player gets snared by a mob after 1 second but the client doesn't hear about it until 1.1 seconds that's ok because the server would have sent data about this snaring at the same time and as a result you can correct the client and put the player as snared in the correct position as opposed to the estimated position by the client. If your client is simulating properly, unless there is major lag the corrections should be minimal and possibly unnoticeable altogether.

Yes this approach means that the player could potentially do some silly client side trickery to make his game client do hackish things, but these hackish things won't actually occur on the server and your server isn't going to send back data that the player wouldn't otherwise normally be able to see because you you've confirmed everything server side. No hacks should get by if you've programmed the systems correctly.

It is my understanding that this is how a lot of games do it and it should work for your game as well. A really good read on this approach has been published by Valve for the Source Engine. You'll find a lot more technical information in that article and much more specific scenarios and other such information that you should find useful.

So to finally answer your question, yes you can implement fluid WASD controls while processing all your data server side (with client side simulation) to prevent hacking. You are not limited to only mouse movement.

# Answer
> 1 votes
1. When you are OK with excluding Internet Explorer 9 and below, you might consider to use WebSockets instead of AJAX. It is much more suitable for real-time games.
2. You do not need to notify the server every tick which key the user is holding down. It's enough to tell the server when the user starts pressing it and when the user is releasing it. The release-command should be accompanied by an exact position to avoid inconsistencies of the traveled distance due to fluctuating latency.

---
Tags: javascript, mmo, rpg, web, control
---


title: Avoid double compression of resources

text:
# Question
Title: Avoid double compression of resources
I am using `.png`s for my textures and am using a virtual file system in a `.zip` file for my game project. This means my textures are compressed and decompressed twice. What are the solutions to this double compression problem? One solution I've heard about is to use `.tga`s for textures, but it seems ages ago, since I've heard that. Another solution is to implement decompression on the `GPU` and, since that is fast, forget about the overhead.

# Answer
> 17 votes
The zip-format supports several different compression algorithms. You can use a different algorithm for each file in the archive. When you want to store already compressed files which do not benefit from additional compression (like PNG) in a zip-archive, you can encode these files with the "stored" algorithm which doesn't compress at all. The "Add to archive" dialog of 7-zip lets you chose this under "Compression strength".

But when you do not only have images but also other, more compressible resources in your archives, it might be quite tedious to choose the algorithm for every single file. In that case you might rather opt for an uncompressed image format in a compressing archive.

The TGA format knows a lot of different modes, of which some are compressed and some are not. When you do not want to use compression, make sure you pick the right one in the export options of the graphic editor you are using. Another non-compressing image format is BMP (Windows Bitmap).

Here is a test I made. I added the same image (an asset from my current project) in different formats multiple times to a zip-archive, some with "deflate"-algorithm on normal strength and one with "store". Sorry for the German GUI. 2nd column is uncompressed size, 3rd column is compression algorithm and 4th column is compressed size.

As you can see, deflate-encoding the PNG only saved a meager 0.3%, while the deflate-encoded BMP is reduced to one-tenth of the original file which is even smaller than the PNG version. This quite surprised me. I would have expected the PNG to be smaller because the compression method of PNG should be optimized for image-data while ZIP is not. A likely explanation is that my image editor (GIMP) added quite a lot of meta-information to PNG files which it doesn't do for BMP.

Uncompressed TGA behaved similar to BMP regarding filesize before and after zipping while the compression of the compressed TGA file was further improved by ZIP, although not as much as the uncompressed versions.

It might be worth to experiment with other algorithms than deflate and with other compression-strength setting. Which combination will have the best results will likely depend on the style of your textures. But you might also consider to benchmark the asset-loading of your game and have the decompression-performance influence your decision which setting you use.

**Bottom-line:** When you want to avoid double-compression while still having a low filesize, either use `PNG` with `Store` zip algorithm or `BMP` with a compressing zip algorithm.

# Answer
> 7 votes
Don't worry about it.

When the "deflate" algorithm used in .zip files encounters a block of data that's already well-compressed, like the pixel data of a .png image, it finds that it can't compress it effectively, and it will store it as literal uncompressed data. This takes very little overhead on the decompression end to copy out.

http://en.wikipedia.org/wiki/DEFLATE

# Answer
> 2 votes
Looks like some very good answers have been given already, but I thought I'd give one more:

```
What are the solutions to this double compression problem?

```

Solution: Do Nothing.

Rationale: There has been no problem stated - yes you are compressing the information twice, but why are you worried about this? Is the data size too big? Is decompression too slow? Is this more or less important than the dozens of features you could be adding, refining,testing and/or debugging at this moment in time?

# Answer
> 1 votes
If you use specialized formats such as PNG and OGG you won't need the compression of ZIP.

PNG, OGG and other already compressed formats won't get much smaller by compressing them again as ZIP. 100MB of PNGs compressed are still ~100MB.

Scripts, Configuration files and other text based formats benefit greatly from compression, however, typically they are tiny in comparison, they don't store that much data. If your game is 100MB, then the text-files maybe make 1MB of the whole game, even if you can make them 100KB through compression then you only won 900KB, less than 1%, hardly worth the effort.

You might even want to use the file system directly instead of using a virtual, zip based file system. It would make patching very easy: you can just swap out any files you modified.

---
Tags: textures, assets, compression
---


title: Non-perfect maze generation algorithm

text:
# Question
Title: Non-perfect maze generation algorithm
I want to generate a maze with the following properties:

* The maze is non-perfect. Means it has loops and multiple ways to reach the exit.
* The maze should be random. The algorithm should output different mazes for different input parameters
* The maze doesn't have to be braided. Means dead-ends are allowed and appreciated.

I just can't find the right resources on google. The closest i found was this description of the different types of algorithms: http://www.astrolog.org/labyrnth/algrithm.htm. All other algorithms were for perfect mazes.

Can anyone give me a website where i can look this up or maybe an algorithm directly?

# Answer
You can construct non-perfect mazes as DMGregory mentioned, starting with a perfect maze then deleting walls at random. However, it sounds like you may be after a maze that's not quite the same as a non-perfect one. The definition of a perfect maze is:

> A "perfect" Maze means one without any loops or closed circuits, and without any inaccessible areas. Also called a simply-connected Maze. From each point, there is exactly one path to any other point. The Maze has exactly one solution.

That is, as long as there is at least one loop, it's not a perfect maze. It doesn't have to have more than one solution to be non-perfect, but since this is GD.SE I assume multiple solutions is a lot more relevant.

So how does one make a maze with **multiple solutions**? You'd need to **remove walls that are along the solution path**. This can be done deliberately, or just randomly remove walls but check how many solutions there are using a maze solver.

This still might not create interesting mazes though; a maze might have multiple solutions but if you're only adding a tiny loop in the solution, gameplay-wise it won't feel like multiple solutions - maybe a shortcut at best.

On the maze classification page you've linked, there is this interesting section:

> Bottleneck finder: This means to find those passages or intersection points in a Maze such that every solution to that Maze passes through them. To do this, run the left hand wall follower to get the leftmost solution, and run the right hand wall follower to get the rightmost solution, where places the two solutions have in common are the bottlenecks. That technique however only works for Mazes that wall following will successfully solve. For other Mazes, to find bottleneck passages, find any solution to the Maze, and also run the blind alley sealer (which may make the Maze unsolvable if it treats an entrance or exit within the Maze as a large blind alley). Parts of the solution path that go through sealed off passages, are bottlenecks.

That is, **bottlenecks are passages that every solution passes through**. You can create mazes with multiple solutions that feel meaningful by making sure that the **length of bottlenecks is short** compared to your shortest solution.

Bottlenecks are very useful for games in a number of ways:

* Since players are **guaranteed to pass through them**, you can place things such as critical objectives, quest items, save points (depending on your game) here. If you have a limited budget for interesting content, you'll get the most bang-for-buck by making sure they are placed at bottlenecks.
* Conversely, you may want to place optional items or secrets outside the bottleneck so that the player may not always find them. Depending on the method you use to determine bottlenecks, you could also find out which areas of the maze are not covered by *any* solution, and place secrets there.
* Bottlenecks are natural **chokepoints**; this has implications that depend on the type of game, so design accordingly.
> 10 votes

# Answer
I find that the RougeBasin wiki has useful gamedev articles. I've used them for my non-rougelike games in the past.

See two maze algorithms here and here.

Here's one using depth-first search (a weapon of choice for maze generation) on Rosetta Code.
> 1 votes

---
Tags: algorithm, maze
---


# Question
Title: How to perform collision detection in 3D space?
I've got to write, what can be summed up as, a complete 3D game from scratch this semester. Up until now I have only programmed 2D games in my spare time, the transition doesn't seem tough, the game's simple. The only issue I have is collision detection. The only thing I could find was AABB, bounding spheres or recommendations of various physics engines. I have to program a submarine that's going to be moving freely inside of a cave system, AFAIK I can't use physics libraries, so none of the above solves my problem.

Up until now I was using SAT for my collision detection. Are there any similar, great algorithms, but crafted for 3D collision? I'm not talking about octrees, or other optimizations, I'm talking about direct collision detection of one set of 3D polygons with another set of 3D polygons. I thought about using SAT twice, project the mesh from the top and the side, but then it seems so hard to even divide 3D space into convex shapes. Also that seems like far too much computation even with octrees.

How do professionals do it? Could somebody shed some light.

# Answer
> 5 votes
GJK works on convex shapes, I might aswell use SAT. I have found information I wanted already. Here are some examples:

To sum it up, I'll be doing collision checks of a sphere or an elipsoid against multiple triangles that form a collision mesh. That seems to be how it's done and that was the information I was asking for, unless somebody can tell me different.

# Answer
> 1 votes
Hey I wrote about GJK in 3D here. SAT is slower than GJK http://in2gpu.com/2014/05/18/gjk-algorithm-3d/

# Answer
> 0 votes
Well, if it's not something very very demanding and state of the art, you could start by implementing the Gilbert collision detection algorithm. It can be made to be fairly fast and it will be fast, provided your collision geometry is not so detailed (and it needn't be!). That's how even some simulators do the trick.. anything more elaborate will, probably, take more effort into consideration.

---
Tags: collision-detection, 3d
---


# Question
Title: Change players state and controls in-game
I'm using Unity 3D

Let's say the player is an ice cube. You control it like a normal player. On press of a button, ice transforms (with animation) into water. You control it completely different than the ice cube.

Another great example would be: Player is human being and has normal FPS controls. On press of a button human transforms into birds and now has completely different controls.

Now, my question is, what would be easier and better:

1. make one object with animation transition and to stay in that state of anim. until button is pressed again
2. make two object: ice and water. Ice has an animation of turning into water. So replace ice (with animation) with water object

And if anyone knows this one too: how to switch between 2 different types of player controls.

# Answer
If your objects are not animated I'd make just a transform animation between first and the second. When you want to change the objects you just play the animation and stop at the end. If you want to change back, you just play the same animation backwards, to `0`.

When you objects have their own animations it gets more tricky so in such case I'd make separate objects and replace one with another when transition animation ends. This way you wouldn't have to worry about too many animations at the same time, in the same object.

According to different types of controls:

Implement both in your game, so you can play as the ice cube and as the water (with selection at compile time for now). Then store somewhere your current player mode and in all your input methods like MouseMoved, KeyDown, etc. add a simple `if( state == something )` and select which of your controlling code to run.
> 1 votes

---
Tags: unity, camera, state, control, controllers
---


# Question
Title: Colors set in Blender not displayed in XNA
I'm trying to create a colored 3D model for my XNA game in Blender. I don't want to use textures - I need only solid colors. Here's the model, as seen in Blender:

After exporting to FBX and opening in Visual Studio 2012 (some kind of built-in viewer I guess), the lightning isn't perfect but the colors are preserved:

But something's wrong when I try to display it using XNA:

Here's my code for displaying objects:

```
protected void DrawModel(GameObject obj, bool semitransparent = false, float angle = 0.0f)
{
    var transforms = new Matrix[obj.Model.Bones.Count];
    obj.Model.CopyAbsoluteBoneTransformsTo(transforms);

    foreach(var mesh in obj.Model.Meshes)
    {
        foreach(BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();

            Game.GraphicsDevice.BlendState = semitransparent ? BlendState.AlphaBlend : BlendState.Opaque;
            effect.Alpha = semitransparent ? 0.5f : 1.0f;

            if(obj is Player == false)
                effect.DiffuseColor = obj.IsHighlighted ? new Vector3(1.0f, 0.0f, 0.0f) : new Vector3(1.0f, 1.0f, 1.0f);

            effect.World = transforms[mesh.ParentBone.Index]*Matrix.CreateRotationY(angle)*obj.TransformMatrix;
            effect.View = ViewMatrix;
            effect.Projection = ProjectionMatrix;
        }

        mesh.Draw();
    }
}

```

**Why is the whole model white instead of colored?** I set colors of the parts by creating a new material and setting its *diffuse* component to the color I want. All other settings have their default values.

I thought that it's a matter of setting `effect.VertexColorEnabled` to `true`, but that gives me an `InvalidOperationException` saying `The current vertex declaration does not include all the elements required by the current vertex shader. Color0 is missing.`. Do I need some kind of shader that will understand Blender's vertex properties and will display the model correctly?

# Answer
It turned out that the problem was caused by explicit assigning some color to `effect.DiffuseColor`. It seems like setting this property also sets something inside the effect object and there's no value that works like a 'transparent' color.

After setting it to `Color.White.ToVector3()`, all textures are clearly visible, but the vertices without textures (only with colors) are plain white. On the other hand, after setting it to `Color.Black.ToVector3()`, everything becomes black.

I was setting `DiffuseColor` of the object to make it look selected/highlighted. As a workaround, a separate effect should do the work.
> 0 votes

# Answer
I would say that your vertex declaration isn't feeding the color to the vertex shader.

I think that the shader you are currently using is expecting a different kind of vertex declaration, which is why it is saying that it expects Color0. Can you post your shader code, or if you're using a standard one, just post the code that initializes all your various 3d effects?

A Vertex Declaration is a way for the program to communicate to the video device what kind of data it will be sending over. It's usually a simple struct with some information about a vertex that's relevant to the rendering method.

On the gpu side, there's a piece of shader code to define how the video card should process the information it receives. This includes a definition of the vertex declaration, which might look something like this in HLSL:

```
struct VertexInputType
{
    float3 position : POSITION;
    float3 normal : NORMAL;
    float2 tex : TEXCOORD0;
};

```

The problem is that you need to make sure that both sides of the equation have the same vertex declaration, or you'll run into trouble. Try looking for examples that make use of VertexPositionColor, and see how the effects are configured - Riemers' tutorials might have what you need. If you want to include a normal value, you might need to build your own vertex declaration.

*edit* \- I should note that I've never imported a mesh in xna, so the process might be different to my experience using 3d in xna, which always made use of geometry generated in-program.
> 0 votes

---
Tags: xna, blender, fbx
---


# Question
Title: Problem getting information about running processes with .GetProcesses() in Unity3D on OS X
I was going to ask this on Unity Answers, but I keep getting an error when trying to get to the site so thought maybe you guys could help. I've also tried the Unity3d subreddit and didn't manage to solve this there either.

I am attempting to get a list of all running processes on my **Mac** from my Unity application. The final idea is to check if *certain* applications are running (eg, TextEdit).

I first tried checking for an open application with GetProcessByName, but got this exception even though the process *is* running:

```
InvalidOperationException: Process has exited, so the requested information is not available.

```

Then I decided to go as simple as possible. I figured I'd just print out a list of *all* running processes to start off with. Here's my code:

```
    Process[] processes = Process.GetProcesses();
    GUI.Label( new Rect(x, y, 100, 20), "Process: " + processes.Length );
    y += 20;
    foreach (Process process in processes) {
        try
        {
            if (!process.HasExited)
            {
                GUI.Label( new Rect(x, y, 100, 20), "process: " + process.ProcessName );
                y += 20;
            }
        }
        catch (System.InvalidOperationException)
        {
            UnityEngine.Debug.Log("Holy batman we've got an exception!");
        }
    }

```

When I run this through the editor, here's what I see:

The number of running processes tends to fluctuate around the 200s, but the only process name being printed on screen is Unity.

If I try to print *all* processes by removing the HasExited if statement I get this (of course they don't all fit on the screen):

Which makes me think that it thinks every process except for Unity has exited...but I have quite a few unterminated processes running, so I wonder why it's not listing those? Basically I need to search through all currently *running* processes. Any ideas? Is there some sort of permission issue with not being able to access properties of external non-Unity processes?

**EDIT:** I should note that I've tried this both while running through the editor and after building. When run after building with !process.HasExited one process is listed with a blank name. I guess that might be the currently running application. The process count hovers around 240.

# Answer
The exception messages are a bit misleading. In fact, Mono reports the same exception (Invalid Operation) with different messages for a variety of different situations.

GetProcesses gets a list of all pids from the system and creates a new Process object for each one, but at this point it doesn't check if they're actually valid. When you call ProcessName on a Process object, it will:

1. Check if the Process has a valid pid. If not, it throws.
2. Try to get the process name from the pid. If it gets a null value back, it throws.

Notice that at no point is it actually checking if the process has exited or not. The HasExited flag only gets set when you check it, and ProcessName doesn't trigger that. The confusing bit is that there are exceptions that get thrown saying the process has exited when it's not the case, so don't trust the messages too much.

You can check the logic on Unity's Mono repo on github.

If you need to access multiple properties on processes in your Process\[\] array and/or you want to know how many valid processes there are, you should preprocess the array and extract the properties you want into an array of your own, to minimize the amount of exceptions you're likely to trigger and split that code from the actual drawing code, something like:

```
var procList = Process.GetProcesses();
var validProcesses = new List<Proc>();
for (int i = 0; i < procList.Length; i++) {
    try {
        validProcesses.Add(new Proc(){
            Name = procList[i].ProcessName,
            Pid = procList[i].Id
        });
    } catch {}
}

```
> 4 votes

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