# Question
Title: Can you use a standard multi-thread if only reading unity objects?
First of all I know about coroutines and how to use them (they're awesome).

A friend of mine was telling me about the way the he implemented his saving system in a game he was working on, after asking him what he was using I found out that he is using system.threading and not coroutines to save data.

I know that Unity isn't thread safe but apparently he has had no issues with saving which leads me to wonder if it is ok to use normal threads as long as you're only reading data and no pre-existing data is modified in the gameworld? would this affect the game at all (other than some moving objects being slightly ahead of where they should be because of the time it took to get to that object and save it)?

# Answer
Saving in another thread while the game keeps running is dangerous. When the gamestate changes while the savegame file gets written, you will write a mixed gamestate consisting partly of the old state and partly of the new state. This can cause all kinds of weird and impossible to reproduce bugs when that savegame is loaded.

For example, consider you have a script which destroys one game-object and instantiates another in its place. Now consider what happens if the saving takes place exactly between these two operations. There are two possible outcomes: Either both will exist when the savegame is loaded or neither will. Either case might break the game in a way that the player can not continue. You have created the worst nightmare of every gamer: a broken savegame.

The deviousness of such problems is that they will appear completely random. Your friend's savegame system might work perfectly fine in 1000 tests, but at the 1001st time it might run into such a race-condition and screw up. And then never again until after release when the user-reviews of your game are suddenly full of people whining about their corrupted savegames and your testers fall into despair trying to reproduce the problem.

If you want to save in a separate thread, you need to write the complete gamestate to an in-memory data structure first and then start the thread to save that structure while your game keeps running with the original gamestate.
> 1 votes

---
Tags: unity, multithreading, savegame
---


# Question
Title: Aspect ratio of drawn quad messed up after rotating
When I draw a quad that is rotating the aspect ratio of the quad gets messed up and the size changes.

Gif of what is happening

I am confident it has something to do with the way I calculate the size because that is relative to the width and height of the screen, I just don't know why the aspect ratio would change since the aspect ratio of the screen doesn't change.

Code of transformationMatrix creation:

```
        Matrix4f matrix = Maths.createTransformationMatrix(
                new Vector2f(
                        gui.getPosition().getX() / Display.getWidth() * 2 - 1 + gui.getSize().getX() / Display.getWidth(),
                        -gui.getPosition().getY() / Display.getHeight() * 2 + 1 - gui.getSize().getY() / Display.getHeight()
                ), gui.getRotation()
                ,new Vector2f(
                        gui.getSize().getX() / Display.getWidth(),
                        gui.getSize().getY() / Display.getHeight()
                )
        );
        shader.loadTransformation(matrix);

```

The x size, y size, x position and y position are in pixels, if you put in 1600 pixels for x position and the screen is 1600 pixels wide it will fill the whole screen. The calculation that is done here will translate those sizes to a value that the shaders will display on the screen.

I had tried calculating the sizes in a different way:

```
gui.getSize().getX() / (float) (Display.getWidth() * Math.abs(Math.cos((Math.toRadians(gui.getRotation())))) + Display.getHeight() * Math.abs(Math.sin((Math.toRadians(gui.getRotation()))))),

```

but this does not work at all, my thought process was that if it is sideways it should use Display.getHeight to calculate the x size and if it is vertical it should use Display.getWidth. This does work for 0, 90, 180 and 270 degrees rotation, but in between it gets smaller and weird. Of course I've also done this for the x position but then cos and sin switched around.

video of this method

And this is the createTransformationMatrix method:

```
public static Matrix4f createTransformationMatrix(Vector2f translation, float rotation, Vector2f scale) {
    Matrix4f matrix = new Matrix4f();
    matrix.setIdentity();
    Matrix4f.translate(translation, matrix, matrix);
    Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0, 0, 1), matrix, matrix);
    Matrix4f.scale(new Vector3f(scale.x, scale.y, 1f), matrix, matrix);
    return matrix;
}

```

# Answer
Try this instead:

```
Matrix4f modelMatrix = new Matrix4f();
        modelMatrix.m00 =  2.0f / (float) Display.getWidth();
        modelMatrix.m11 = -2.0f / (float) Display.getHeight();
        modelMatrix.m30 = -1;
        modelMatrix.m31 =  1;

```

I have no idea what `gui.getSize().getX() / Display.getWidth()` was suppose to do, so I left it out from above. But if you intend to scale or translate some object after converting it to pixels, I recommend creating a second matrix with those transformation and multiplying them together to create a third matrix rather then modifying this one.

What I created above it an orthographic projection matrix which translates from pixel values e.i. \[0,width\] to \[-1,1\] and \[0,height\] to \[1,-1\]. This also means the origin is in the top-left corner. So if you now assume pixel coordinates and multiply any transformation with the projection matrix at the end, no distortions should occur.

Remember that the order you multiply matrices matter.

Example:

```
Matrix4f modelMatrix = new Matrix4f();
        modelMatrix.m00 =  2.0f / (float) Display.getWidth();
        modelMatrix.m11 = -2.0f / (float) Display.getHeight();
        modelMatrix.m30 = -1;
        modelMatrix.m31 =  1;

// No special trickery or dividing by width, just use pixel coordinates.
// The projection matrix takes care of converting the pixel coordinates.
Matrix4f modelMatrix = Maths.createTransformationMatrix(
    new Vector2f(
        gui.getPosition().getX(),
        gui.getPosition().getY())
    , gui.getRotation()
    , new Vector2f(
        1.0f,
        1.0f
    )
);

Matrix4f modelProjMatrix = Matrix4f.mul(projectionMatrix, modelMatrix, null);
shader.loadTransformation(modelProjMatrix);

```

The `projectionMatrix` can be shared by all of your geometry. Again I don't really understand what the `gui.getSize().getX()` is suppose to be doing in your code but I included it.
> 0 votes

---
Tags: opengl, java, transformation
---


title: Calculate ticks for animation delay

text:
# Question
Title: Calculate ticks for animation delay
Hi guys I am trying to calculate the correct elapsedTime for each frame in my animation.

Example I have a sprite called stance that has 20 frames I want to give each frame a tick delay property that determines how long that frame will last until next frame.

the question is how do I use the gameTime.elapsedTime to calculate the current elapsedTicks say for example the first frame has 20 ticks then

currentElapsedTicks += gameTime.ElapsedTime.Ticks?

# Answer
> 1 votes
Add a timer to keep track of your elapsed time. Take a look at the following:

```
float Timer;
const float FRAMES_PER_SECOND = 20;
const float TIMER = 1 / FRAMES_PER_SECOND;

void Init()
{
    Timer = TIMER;
}

public void Update(GameTime gametime)
{
    float elapsed = (float)gametime.ElapsedGameTime.TotalSeconds;

    Timer -= elapsed;

    if (Timer <= 0)
    {
        ActiveFrame = NextFrame();
        Timer = TIMER;
    }
}

```

# Answer
> 0 votes
I managed this stuff in love-2d: Here how i've done

```
anim.started=false
anim.curFrame=0
anim.accum = 0

function anim:update(dt)
    if anim.started then
        anim.accum = anim.accum+dt
        if anim.accum > anim.frameTime then
            anim.accum = anim.accum-anim.frameTime
            if anim.aType=="loop"then
                anim.curFrame=(anim.curFrame+1)%anim.nFrames
            end
        end
    end
end

```

This is lua code , you cane consider it as pseudo code. "anim" is a kind of "class" the stores "pointers" to each animation frame. `anim.curFrame` is the "pointer" at the frame currently rendered.

The idea is to accumulate delta time in `anim.accum` until `anim.accum` become grater than `anim.frameTime`.

---
Tags: xna, animation, sprites
---


# Question
Title: Libgdx problem while converting TextureRegion to Pixmap
I'm developping a Tile base game where I have to generate transition tiles. To do so, I have a method that generate those tiles from 2 existing one and 1 "filter tile". I use this method to make a pixMap from the region I retrieved from my TextureAtlas.

```
public Pixmap getPixMapFromRegion(TextureRegion region){

    Texture texture = region.getTexture();
    TextureData data = texture.getTextureData();
    if (!data.isPrepared()) {
        data.prepare();
    }
    Pixmap pixmap = data.consumePixmap();
    int width = region.getRegionWidth();
    int height = region.getRegionHeight();
    Pixmap px = new Pixmap(width, height, Format.RGBA4444);
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            int colorInt = pixmap.getPixel(region.getRegionX() + x, region.getRegionY() + y);

        }
    }
    return px;
}

```

Them I apply this method

```
public Pixmap generateMixedTile(TiledMapTileSet tileset, AssetManager assMan,String template, TextureRegion region1, TextureRegion region2) {
    TextureAtlas atlas = assMan.get("../core/assets/tuiles/MergeFilter.atlas")
    AtlasRegion region = atlas.findRegion(template);
    Pixmap templ = getPixMapFromRegion(region);
    Pixmap img1 = getPixMapFromRegion(region1);
    Pixmap img2 = getPixMapFromRegion(region2);
    Pixmap res = newPixmap(region.getRegionWidth(),region.getRegionHeight(),Format.RGBA4444);

    for (int y = 0; y < templ.getHeight(); y++) {
        for (int x = 0; x < templ.getWidth(); x++) {
            if(0xFF000000 == templ.getPixel(x, y))
                res.drawPixel(x, y, img1.getPixel(x, y));
            else
                res.drawPixel(x, y, img2.getPixel(x, y));
        }
    }
    return res;
}

```

It seems that after asking again and again for the same texture in the AssetManager, I get a Couldn't load file ../core/assets/tuiles/Water3.png Exception. But this happen after the system success a lot of time to access that same file.

So I don't know how I could handle that because I thought that using assetManager and Atlas was the bests practices

Any Idea of how to fix that or to do it in another way?

# Answer
> 0 votes
I found out that it was a lack of memory that helped me to open the picture.

---
Tags: libgdx, textures, exceptions
---


title: Using .svg in Unity

text:
# Question
Title: Using .svg in Unity
Creating resolution independent sprites is tough and memory consuming.

How can .svg assets be used in Unity for any kind of 2D game?

What are alternatives to .svg that can be used in Unity?

Can sprites with various shapes be generated within Unity?

We would like to create universal art assets that'll support all devices with different resolutions. (We'll handle the aspect ratio )

# Answer
Well, normally you would just produce 1 graphic at the highest resolution you will be publishing to. Then you would use the Unity tools for setting mip-map levels. You would then modify settings like 'pixel perfect' or 'texture type' (compressed, truecolor, etc.) to get the best look for the compression you choose.

> Creating resolution independent sprites is tough and memory consuming.

What do you mean?

You're either creating your graphics in a vector program like Inkscape or Illustrator, or you create them in a raster program like Gimp or Photoshop. The difficulty is only determined by your comfort level with your toolset.

> How can .svg assets be used in unity for any kind of 2d game?

With a plugin: https://www.assetstore.unity3d.com/en/#!/content/38258

> What are alternatives to .svg that can be used in unity?

You can use the Unity LineRenderer or standard GL drawing methods. This Post has some good examples.

> Can sprites with various shapes be generated within unity?

They will be whatever shape you draw them.

> Would like creating universal art asset that'll support all devices with different resolutions.(we'll handle the aspect ratio )

This isn't a sentence. But, Unity won't change aspect ratio, unless you scale on only one axis.
> 6 votes

---
Tags: unity, 2d, assets, content-generation, svg
---


title: Python: Character name and raw_input

text:
# Question
Title: Python: Character name and raw_input
I have a few lines of code here for Python:

```
 # Asks for a name
def CC():
    print "..."
    tick.clock(3)
    print "Welcome...\
    What is your name, scared one?"
    name = str(raw_input("What is your name?").lower())
    # For debugging purposes
    print name

```

I want to run the code and ask the player what their name is with the line:

```
  name = str(raw_input("What is your name?").lower())

```

But every debugger I use online doesn't ask me for my name so i can only assume the code itself is wrong. I'm using Atom on Windows and i cant seem to find any useful run/debugging tools on there. Please send feedback on what it is I'm doing wrong in order to get the name of my character.*This is to help in the development of a game I am currently working on.*

Also I would appreciate it if you could tell me if there is a useful tool in Atom or online just for my sort of problem.

(P.S) I'm open to what I could do better. Thank you.

# Answer
I am not an expert on python either, but for some reason `tick.clock(3)` gives problems.

I also removed `str()` as it is useless. (Cleaner code is always better)

Try without that line:

```
# Asks for a name
def CC():
    print "..."
    print "Welcome...\
    What is your name, scared one?"
    name = raw_input("What is your name?").lower()
    # For debugging purposes
    print name

```

(Tested on Python 2.7, works). More exactly, Here (PythonTutor, The first debugger I found).

Answer:

```
# Asks for a gender ( Title )
def CC():
print "..."
print "Welcome...\
What is your gender, scared one?"
name = str(raw_input("What is your gender?").lower())
if name == "boy" :
    name = "Scared boy..."
    print name
elif name == "girl":
    name = "Scared girl..."
    print name
else:
    print "Are you a boy or a girl?"
    return CC()
# Initiates CC formula
CC()

```
> 0 votes

---
Tags: python
---


# Question
Title: Detect clusters of tokens on an x y grid
Ok, so I have a two dimensional grid working on integer x and y coordinates.

Each of this coordinates can have one and only one token on it.

The tokens have the capability of check and return an adjacent token given a direction in which to search (they'll return null in case nothing is there)

I now need an algorithm to check the grid for clusters of 3 or more adjacent tokens and add each cluster to a dedicated variable (meaning than, instead of just stopping after return one cluster, it needs to check for all clusters on the board)

I've been thinking for a while but came out with nothing, any help?

# Answer
Well, finding 3+ is easy if you realize that regardless of their respective positions to each other, at least one of them will *always* have at least two neighbors. Once you've found a location in the grid that is part of a triplet, use a floodfill algorithm to locate the entire cluster.

You won't be able to assign this to a "dedicated variable" but you *can* store the result into a list, then return the list.

I'd suggest that the list contains only the markers that detect that they are part of a cluster (i.e. only the tokens that have 2+ identical neighbors) and then working from that list removing duplicates (any token that has a matching neighbor that is also in the list can be removed, and for every removed token, all of *its* neighbors can also be removed). This will produce a list that contains 1 entry for each cluster (or very close to it).

Although if you're interested in having the *whole cluster* represented, then do the reverse, for each token, add all of its matching neighbors, rather than removing.

Floodfill, as a recursive algorithm, is really simple (pseudocode from Wikipedia):

```
Flood-fill (node, target-color, replacement-color):
 1. If target-color is equal to replacement-color, return.
 2. If the color of node is not equal to target-color, return.
 3. Set the color of node to replacement-color.
 4. Perform Flood-fill (one step to the south of node, target-color, replacement-color).
    Perform Flood-fill (one step to the north of node, target-color, replacement-color).
    Perform Flood-fill (one step to the west of node, target-color, replacement-color).
    Perform Flood-fill (one step to the east of node, target-color, replacement-color).
 5. Return.

```

You'd not be altering your map, but the basic process would be similar: for each token perform the action on every neighboring token, skipping completed locations and non-matching tokens.
> 2 votes

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


title: Fragment shader, tint color problem

text:
# Question
Title: Fragment shader, tint color problem
I am new to shaders, and I am trying to tint a texture to mark status of a enemy.

I am implementing shaders on OpenGL ES 2.0 (Mobile)

The problem is that with this shaders, I see the enemy without change (even if I assign de fragcolor to (1.0, 0 , 0 ,1.0), the real code is commented).

**Vertex shader**

```
uniform mat4 u_MVPMatrix;       // A constant representing the combined model/view/projection matrix.
uniform mat4 u_MVMatrix;        // A constant representing the combined model/view matrix.

attribute vec4 a_Position;      // Per-vertex position information we will pass in.
attribute vec3 a_Normal;        // Per-vertex normal information we will pass in.
attribute vec2 a_TexCoordinate; // Per-vertex texture coordinate information we will pass in.

varying vec3 v_Position;        // This will be passed into the fragment shader.
varying vec3 v_Normal;          // This will be passed into the fragment shader.
varying vec2 v_TexCoordinate;   // This will be passed into the fragment shader.

// The entry point for our vertex shader.
void main()
{
    // Transform the vertex into eye space.
    v_Position = vec3(u_MVMatrix * a_Position);

    // Pass through the texture coordinate.
    v_TexCoordinate = a_TexCoordinate;

    // Transform the normal's orientation into eye space.
    v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));

    // gl_Position is a special variable used to store the final position.
    // Multiply the vertex by the matrix to get the final point in normalized screen coordinates.
    gl_Position = u_MVPMatrix * a_Position;
}

```

**Fragment shader**

```
precision mediump float;        // Set the default precision to medium. We don't need as high of a
                                // precision in the fragment shader.
uniform sampler2D u_Texture;    // The input texture.

varying vec3 v_Position;        // Interpolated position for this fragment.
varying vec3 v_Normal;          // Interpolated normal for this fragment.
varying vec2 v_TexCoordinate;   // Interpolated texture coordinate per fragment.

// The entry point for our fragment shader.
void main()
{

    vec4 texVal = texture2D(u_Texture, v_TexCoordinate);
    gl_FragColor = (1.0, 0 , 0 ,1.0);//vec4(texVal.rgb, texVal.a)*(1.0, 0 , 0 ,1.0);

}

```

# Answer
The problem was there

```
 gl_FragColor = (1.0, 0 , 0 ,1.0);//vec4(texVal.rgb, texVal.a)*(1.0, 0 , 0 ,1.0);

```

it miss the vec4 name

```
 gl_FragColor = vec4(1.0, 0 , 0 ,1.0);//vec4(texVal.rgb, texVal.a)*vec4(1.0, 0 , 0 ,1.0);

```
> 3 votes

---
Tags: opengl, shaders, fragment-shader
---


title: Restricting Maximum Velocity in Space

text:
# Question
Title: Restricting Maximum Velocity in Space
I'm making a top-down 2D space ship game in which you rotate and thrust. I'd like to impose a maximum velocity for different engine types, meaning that a certain engine can only get you going up to a certain speed.

But I'd also like the ship to be able to travel faster than that maximum velocity, say if it were sent flying by a collision with a fast-moving asteroid.

I can't naively have the engines only apply impulse if the ship is moving at less than its maximum speed -- otherwise if an asteroid sent you flying to the right, you couldn't deliberately slow down because that would involve applying an impulse to the left.

But I'm not restricted to cardinal directions. If the ship is moving too fast to the right, I don't want it to accelerate to the right, but I would like it to be able to curve upward, which might involve applying some kind of impulse at say a 15 degree angle.

My other thought was to cap the maximum velocity of the ship at the maximum velocity of the engine, but then an asteroid collision could send you flying no faster than you engine's maximum speed, and that's undesirable as well.

How might I go about designing a system that allows one to reach velocities no higher than a set maximum from their own impulse, but still be able to steer their ship at higher velocities and still actually attain those higher velocities from external means?

**Edit**

Let's say my maximum velocity is 50 m/s. I'm traveling at 50 m/s at a 15 degree angle, which means my x velocity is 48.3 and my y velocity is 12.9. The ship is facing at a 30 degree angle (even though it's traveling along a 15 degree vector).

When I press the thrust button, I want the ship to trend toward that 30 degree angle of travel. Which means that its current angle of travel must be altered in some fashion. Right now I do so by applying impulses. But if I apply an impulse at a 30 degree angle, the ship's velocity will exceed is maximum (a good portion of that impulse is in the same direction as we're already going).

If I don't allow that impulse to be applied, the player can't adjust their course at all while they're moving too fast. And I'm not sure how to determine which components of an impulse would change a ship's velocity's angle without increasing its length.

# Answer
> 2 votes
This problem is a bit difficult to think about because it's unphysical -- engines have a thrust which equates to acceleration and not top speed. So I think to fully answer this question, you need to remove it from a physical framework and just think of it in terms of vectors.

To be clear, I will use "speed" whenever I am talking about the overall quantity of movement of the ship, and "velocity" when there is some directionality associated with it.

You can use the directionality of velocity to your advantage here. Your engine impulse can only add velocity in the direction of impulse if the velocity in the direction of impulse is below the "engine speed" rating. You need to consider vector addition here for this to work the way you want it to. If the player impulses in a direction that is not orthogonal to direction of motion, then ONLY the amount of impulse applied in the orthogonal direction will actually increase the velocity in that direction, which means that you can change direction. To disallow the player from actually increasing speed in this situation, you need to *remove* velocity from the previous direction of motion so that the speed stays the same (using that you can calculate speed by adding the orthogonal velocities in quadrature).

This would allow for maneuvers at higher than engine speed given that your original speed is over engine speed due to some external mechanism, but it would not allow for acceleration past engine speed in any given direction.

EDIT

Here's an example of what I mean (using the conditions you included in your edit):

You would presumably have an acceleration value of some sort from your engine specifications. Let's just say it's 1 m/s/s for the sake of argument. Let's say you press the thrust key and hold it down for 1s at 30 degrees while your ship is travelling at 50 m/s at 15 degrees (giving vx = 48.296 m/s and vy = 12.941 m/s). You would then need to apply a 1 m/s change somehow, while still maintaining 50 m/s overall speed. So, first we must figure out what part of that 1m/s is orthogonal to your original direction and then decompose the 1 m/s along that basis.

If you draw it out (I'm not sure how to draw here) you can see that you just need to undergo a 15 degree rotation, so the direction of thrust along your current vector is `1 m/s * cos(15)=0.966 m/s` and the direction orthogonal is `1 m/s * sin(15)=0.259 m/s`. Here comes the "difficult" part: you now need to calculate the new direction based on these values. We already determined that the thrust along the vector will not affect anything, so we can discard the 0.966 m/s change and just apply a 0.259 m/s change in the orthogonal direction.

Since we have forced acceleration to only be orthogonal, we know that this is a "circular" change in velocity (it only changes direction and NOT speed -- exactly what you want!). In this case, the orthogonal direction is 15 + 90 = 105 degrees, so decompose that into your original x-y basis and you get that `dvx = 0.259 m/s * cos(105) = -0.067 m/s` and `dvy = 0.259 m/s * sin(105) = 0.250 m/s`. It's important that you get your angles right, because that negative sign in dvx is how the magnitude stays the same! Put this together and your resulting velocity after 1s of thrust at 1 m/s/s is `vx = 48.296 m/s - 0.067 m/s = 48.229 m/s` and `vy = 12.941 m/s + 0.259 m/s = 13.200 m/s` which gives you `vt = sqrt(48.229*48.229 + 13.200*13.200) m/s = 50.003 m/s` which is 50 up to the precision we calculated (3 decimal places). The computer will maintain float or double precision, but you still might want to cap it at previous speed manually or those rounding errors will accumulate.

# Answer
> 0 votes
This is how I would do that (pseudo-code):

```
class Vector {
    var float x;
    var float y;

    function Vector (float angle, float magnitude); // constructor
    function add(Vector);                           // adds new vector to current vector
    function angle(float new_angle);                // returns or sets angle
    function magnitude(float new_magnitude);        // returns or sets magnitude
}

class Ship {
    position = new Vector(0, 0);
    velocity = new Vector(0, 0);
    max_speed = 10;
}

function update() {
    acceleration = impulse_key_pressed ? new Vector (ship.position.angle(), engine_power) : new Vector(0, 0);
    ship.position.add(acceleration);
    ship.position.add(asteroid_collision);
    if (ship.velocity.magnitude() > ship.max_speed)
        ship.velocity.magnitude(ship.velocity.magnitude() - 0.1);
}

```

Getting hit with an asteroid is just a one time addition of new acceleration to the current position. This acceleration is big enough to influence the current ship's velocity and increase it over its max speed. Afterwards the ship slows down gradually (by 0.1 of magnitude each update).

You can read up more on vectors e.g. in this answer.

---
Tags: 2d, physics, logic
---


# Question
Title: Adding new components and systems in my ECS requires lots of boilerplate code
I'm writing an entity component system for a project I've been working on. It's currently in a working condition, and overall i'm pretty happy with it, but I've noticed that adding new components and systems to it requires quite a lot of boilerplate code.

I've been researching ECS a bit, and I'm not entirely sure if that's normal or not. None of the things I've read mention how much boilerplate is typically necessary to add new components or systems.

Here is how I designed my ECS. The Entity class carries an id and a map of smart pointers to it's components. Entities are defined in YAML, and a factory class parses the YAML and creates all the components an entity needs. Entities are stored in the main engine class.

Systems hold a vector of nodes, each node containing only the components needed by the particular system. Each update, the system loops through the nodes, removing ones with invalid pointers and updating ones with valid pointers.

As of right now, boilerplate for component creation is not too bad. Each new component must also come with a function that returns an instance of itself, and the factory needs to have it's map of function pointers updated to include said function.

Boilerplate for making new systems is worse. The pointers in each node are hard coded. If a node needs to hold a lot of pointers to different components, things get messy quickly. The Node constructor lists every component pointer. The function for registering entities has to check if the entity contains any of the components. The update function has to check to validity of each pointer in the node.

Obviously all of these things need to be done, but making changes to the components a node holds requires updating the system in 4 different places, and creating a new component requires updating things in the factory class.

If lots of boilerplate code is the reality of working with entity component systems, then I'm alright with it because there are a lot of benefits. However, I'm not satisfied with not knowing if there is a better way to handle these things.

# Answer
> 2 votes
If your biggest problem is with the `System`s, switch from hand-written nodes to tuples. Then you can make some function and class templates to handle most of the work.

```
template <typename ...ComponentTypes>
class AbstractSystem {
  using Node = tuple<weak_ptr<ComponentTypes>...>;

  /* bunch of template boilerplate */
};

```

Though I really don't think that using `weak_ptr` is a good idea (which I assume you're doing since you mention "checking if a pointer is valid"). Your entities should register from systems upon destruction. `weak_ptr` isn't as efficient as raw pointers or even shared/unique pointers. It kind of negates half the point of even using the boilerplate-ridden and constrictive ECS pattern if you're going to slap in something like `weak_ptr` for every component access in your systems.

I don't know why your components "need a function that return an instance of itself." Such `Clone` functions fly in the face of what an ECS is actually supposed to be, as your components should be pure data (ideally, a POD `struct`) and not have any member functions at all. Your factory can be responsible for cloning the components it creates, perhaps via the standard copy constructor, for instance.

```
template <typename ComponentT>
class AbstractFactory {
  ComponentT* Create(yaml& data) {
    ComponentT* cmp = new ComponentT;
    /*...*/
    return cmp;
  }

  ComponentT* Clone(ComponenT* src) {
    return new ComponentT(*src);
  }
};

```

A theme you might be noticing here is that you have to make a lot of use of templates in a C++ ECS if you want to get rid of the excessive boilerplate they tend to require. Which means that you have to be OK with making use of said templates and paying the (sometimes extreme) compilation-time overhead they can incur. That can be taken to either extreme; some major game companies' engines still all but ban templates entirely while other (mostly hobbyist) engines are written with extensive and complex templates using things like Boost.Hana or MPL.

If you're dead set on the ECS form of component-based design, you might look into "simple" C++ ECS implementations like entityx for some inspiration.

# Answer
> 0 votes
Well, to me the description is a bit vague, but sounds like the main problem is with the entities/components logistics within your systems? If so, then why not just upgrade the way you build your systems?

These upgrades could come in flavor of abstraction and encapsulation, where the base system class has a set of abstracted pointer-keepers, which incapsulate all logistics on components, and the base system class has methods to add a keeper for a component type, a generic loop that runs through all the tracked entities with the corresponding components and a method to update your pointers, removing the obsolete ones. Also, for reducing the boilerplate code even more, filters can be generalized in a similar way to traverse and select entities in real-time (where needed) based on components they have..

Then a particular system derived from this class would, in the simplest case, only have a method like `update(EntityId id, HashMap<ComponentType, ComponentInstance>)`? *(the example is in Java, sorry, idk what would be the analogy in C++ but you get the idea)*.

All in all, this looks more like an OOP problem than something related to ECS concepts.

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


# Question
Title: How to disable Camera from tilting when following a game object?
I have a game character object which is followed by camera. Camera is child object of Character.

Using rigid body makes the character tilt in slopes and camera tilts too.

how do i stop camera tilting when character tilts?

# Answer
The answer is in your second sentence.

> Camera is child object of Character.

The Camera should not be a child of the character. This is what is causing the camera to tilt. A child will follow its parent's transform.

Remove the Camera from the Character. The script @Jon linked to will do what you want by modifying the camera transform, as the character moves without modifying rotation. So, your Camera shouldn't tilt at all.

If you need the camera to be a child of your character, @Jon offers another solution in the chat he links to that updates the Camera with an inverse rotation of your character.
> 1 votes

---
Tags: unity, physics, camera, rigidbody
---


# Question
Title: Drawing texture with smaller size results in pixelated image, even after applying filter
Can someone please help me resolve this issue. I've tried searching myself and the common answer suggested is to use a TextureFilter. I've tried doing that multiple times but nothing works. My png resolution is 1024x1024, and I'm trying to shrink it's size to fit on screen. This is the kind of result I'm getting, you can see that the circle looks very pixelated, despite the actual image having anti-aliased edges.

\[The original image is here.\]

Here's the code:

```
    SpriteBatch batch;
    Texture img;
    Sprite sprite;

    @Override
    public void create () {
        batch = new SpriteBatch();

        img = new Texture("circle.png");
        img.setFilter(TextureFilter.Linear, TextureFilter.Linear);

        sprite = new Sprite();
        sprite.setRegion(img);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(0,0,0,0);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();
        batch.draw(img, 0, 0, 128, 128); //draw texture -- reduced size
        batch.draw(sprite, 200, 200, 128, 128); //draw sprite -- reduced size
        batch.draw(img, 250, 250); //draw texture -- original size
        batch.end();
    }

```

# Answer
> 3 votes
As suggested in the comments, you should try to use Tri-Linear filtering and MipMaps. The reason using `TextureFilter.MipMapLinearLinear` results in a black box is that you haven't generated the texture with MipMaps. In order to do so, simply pass a second parameter to the Texture constructor as `true` like so:

```
img = new Texture("circle.png", true);

```

---
Tags: libgdx, textures
---


# Question
Title: Dealing with collisions across adjacent static bodies
**The Problem:**

I have the following setup:

A, B and C are rectangular static bodies in box2d. p is a circular dynamic body in box2d.

The movement of 'p' is solely controlled by the current gravity force of the world.

When 'p' collides with a static body (A, B or C) I play a bouncy sound. I handle this through a standard ContactListener. No problems there.

The problem arises when 'p' is on 'A' and traveling left towards 'B'. This causes another collision to fire (on 'B') which results in another bouncy sound which is unwanted. If however 'p' was to be traveling right and contacted 'C' I would want the sound to play (given enough velocity, etc).

**TL;DR** \- When sliding across multiple static bodies how do I effectively ignore collisions from a body that is on the same 'line' I'm already on?

**What I've Tried:**

I've tried numerous different approaches such as on collision tracking that normal as my 'ground' normal and ignoring collisions from the same normal. This works until I do something like make contact with 'C' which then becomes my new 'ground' normal. But having never lost contact with 'A' if I go back towards 'B' I will trigger another collision and we're back to square one.

**The Plea:**

Looking for code-based solutions or ideas if at all possible. I've considered trying something like a chain shape around my level's collidable areas, but with certain parts of my world being dynamic I don't feel like that's an adequate solution.

Thanks!

# Answer
If I understand the problem correctly, you were close to properly solving it.

Your approach with the normals is what you want, but instead of only saving the normal of the last collision, save a list of normals from all current collisions/overlappings. Then, play the sound whenever the new normal of the new collision is not yet present in the list.

In further detail, a "pseudo-implementation" would be like the following (to be applied regarding each obstacle with which collision happens/stops happening):

```
Vec2<> normals_list; //create a list to hold the normals
OnCollisionEnter(){
    Vec2 col_normal = Get.Collision.normal; //get the normal of the new collision
    int presence_in_list = 0;
    for(i=0; i < normals_list.Length; i++)
    {
        if(col_normal  == normals_list[i]){ presence_in_list; += 1; } //check how many times current collision's normal is already present within the list
    }
    if(presence_in_list == 0) { play.sound; } //if not present, play the sound
    normals_list.Add(col_normal); //add the normal of current collision to the list
}

OnCollisionExit{
    Vec2 col_normal = Get.Collision.normal; //get the normal of the new collision
    for(i=0; i < normals_list.Length; i++)
    {
        if(col_normal  == normals_list[i]){
            normals_list.Remove(normals_list[i]); //remove the normal from the list
            col_normal = Vec2(0,0); //to avoid deleting more than once, in case there were repeated normals in the list
        }
    }
}

```
> 2 votes

# Answer
Have you considered playing the sound when the direction of the ball changes? Or like add that as a condition, in addition to the already "collide with object" condition.
> 3 votes

# Answer
Ok, I'm piggy-backing on Skitskraj's answer here so if you like mine, upvote his/hers too.

**Solution:** Play the sound only if there is a new contact *and* there is a significant velocity change. I would suggest using the `postSolve` callback on the first iteration of the collision to determine if the impulse is above some threshold value required to generate the bouncing sound.
> 2 votes

# Answer
Since you're not strictely looking for code-based answers you might want to try:

Of course assuming it doesn't constrict your level design. (Skitskraj's answer is pretty good too tho)
> 1 votes

---
Tags: collision-detection, physics, libgdx, box2d
---


# Question
Title: Why my game is running slowly if it was launched from a wpf application?
i have some issues why my GameEditor. I would start my XNA project from it, like a debug-client. It opens and all works fine, but it runs on 45 frames until I hide the wpf form. then the framerate goes up and remains there, even if I return the wpf form.

```
    private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
    {
        var gameAppDomain = AppDomain.CreateDomain("Game");
        gameAppDomain.ExecuteAssembly(@"..\..\..\WindowsGame1\WindowsGame1\bin\x86\Debug\WindowsGame1.exe");
    }

```

the game is a just a new xna game without any rendering, except my framerate counter.

```
/// <summary>
///     This is the main type for your game
/// </summary>
public class Game1 : Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    private FrameRateCounter frameRateCounter;

    public Game1()
    {
        this.graphics = new GraphicsDeviceManager(this);
        this.Content.RootDirectory = "Content";
    }

    /// <summary>
    ///     Allows the game to perform any initialization it needs to before starting to run.
    ///     This is where it can query for any required services and load any non-graphic
    ///     related content.  Calling base.Initialize will enumerate through any components
    ///     and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        // TODO: Add your initialization logic here
        this.frameRateCounter = new FrameRateCounter(this);
        base.Initialize();
    }

    /// <summary>
    ///     LoadContent will be called once per game and is the place to load
    ///     all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        this.spriteBatch = new SpriteBatch(this.GraphicsDevice);
        this.frameRateCounter.LoadContent();
        // TODO: use this.Content to load your game content here
    }

    /// <summary>
    ///     UnloadContent will be called once per game and is the place to unload
    ///     all content.
    /// </summary>
    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    /// <summary>
    ///     Allows the game to run logic such as updating the world,
    ///     checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        this.frameRateCounter.StartUpdateTimer();

        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        // TODO: Add your update logic here

        base.Update(gameTime);
        this.frameRateCounter.EndUpdateTimer(gameTime);
    }

    /// <summary>
    ///     This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        this.frameRateCounter.StartDrawTimer();
        this.GraphicsDevice.Clear(Color.CornflowerBlue);

        // TODO: Add your drawing code here

        this.frameRateCounter.EndDrawTimer(gameTime);
        base.Draw(gameTime);
    }
}

```

If I do the same for a WinForms application, I dont have that issue. My first try was to launch it in an TASK/Thread but then it crashes after 15-20 min if I have loaded my soundeffects. The event log says it was "XAudio2\_6.dll\_unloaded" with a access violation exception.

hre is my test game: https://www.dropbox.com/s/gtt49lwquyoo86e/WindowsGame1.zip?dl=0

# Answer
> 1 votes
Admittedly, this is an educated guess, so keep that in mind;

WPF being the parent domain in this case means that all subprocesses like the XNA game are issued handles from that domain. I don't really know enough about the architecture behind WPF to adequately explain what it would be doing to cause the slowdown. However, as a possible fix, try automatically minimizing and then restoring the game at launch?

---
Tags: xna, wpf, xaudio2
---


# Question
Title: Does the linear attenuation component in lighting models have a physical counterpart?
In OpenGL (and other systems) the distance attenuation factor for point lights is something like `1/(c+kd+sd^2)`, where `d` is the distance from the light and `c`, `k` and `s` are constants.

I understand the `sd^2` component which models the well known physically accurate "inverse square law" attenuation expected in reality.

I guess the constant `c`, usually one, is there to deal with very small values of `d` (and divide-by-zero defense perhaps?).

What role does the linear `kd` component have in the model, (by default `k` is zero in OpenGL). When would you use other values for `k`? I know that this is called the "linear attenuation" component, but what behavior does it simulate in the lighting model? It doesn't seem appear in any physical model of light that I'm aware of.

*\[EDIT\]*

It has been pointed out by David Gouveia that the linear factor might be used to help make the scene 'look' closer to what the developer/artist intended, or to better control the rate at which the light falls off. In which case my question becomes "does the linear attenuation factor have a physics counterpart or is it just used as a fudge factor to help control the quality of light in the scene?"

# Answer
> 21 votes
Light, from point-like sources, falls of with the square of the distance. That's physical reality.

Linear attenuation is often stated to appear superior. But this is only true when working in a *non-linear* colorspace. That is, if you don't have proper gamma correction active. The reason is quite simple.

If you're writing linear RGB values to a non-linear display without gamma correction, then your linear values will be mangled by the monitor's built-in gamma ramp. This effectively *darkens* the scene compared to what you actually intended.

Assuming a gamma of 2.2, your monitor will effectively raise all of the colors to the power of 2.2 when displaying them.

This is linear attenuation: \\$\frac{1}{k\_d}\\$. This is linear attenuation with the monitor's gamma ramp applied: \\$\frac{1}{k\_d^{2.2}}\\$. That's pretty close to a proper inverse-squared relationship.

But the actual inverse squared: \\$\frac{1}{sd^2}\\$ becomes: \\$\frac{1}{s^2d^{4.4}}\\$. This makes the light attenuation fall off *much* more sharply than expected.

In general, if you're using proper gamma correction (like rendering to an sRGB framebuffer), you shouldn't use linear attenuation. It won't look right. *At all*. And if you're not using gamma correction... what's wrong with you ;)

In any case, if you're trying to mimic reality, you want inverse-squared (and gamma correct). If you're not, then you can do whatever you need to for your scene.

# Answer
> 9 votes
**Flexibility**.

Because you might want your lights to fall off linearly. It's there to give you that degree of control. It doesn't really need to be physically accurate (and the entire phong shading lighting equations are certainly not physically accurate either).

Sometimes the quadratic model will give out light too fast near the source and leave "white glares" in the nearby surfaces. By providing a linear and constant coefficients, you have the flexibility to adjust the results to your liking

For example, when I implemented a raytracer, I found out that the inverse square law made my point lights fall off too quickly. I changed to a clamped linear model (where each light had a minimum and maximum radius, with linear interpolation in between) and it just looked better.

Edit: Just found a nice resource explaining this.

# Answer
> 6 votes
Okay, I’m going to have a guess at it.

### Preliminary observation

> In OpenGL (and other systems) the distance attenuation factor for point lights is something like `1/(c+kd+sd^2)`, where `d` is the distance from the light and `c`, `k` and `s` are constants.
>
> I understand the `sd^2` component which models the well known physically accurate "inverse square law" attenuation expected in reality.

The curve for `c+kd+sd^2` is a parabola, and so is the curve for `sd^2`; the difference is not as important as it may seem: they behave similarly at infinity, it’s just for small values that they’re different. **Whatever `k` means, it’s only meaningful when close to the light.**

### Preliminary simplification

Since this is an attenuation *factor* you could as well set `s == 1`, or divide each constant by `s` in the expression, and divide your light source’s power by `s`. There is one parameter too many in the formula.

You end up with:

```
1/(c/s+(k/s)d+d^2)

```

### Change of variables

… which is strictly equivalent to:

```
1/(A + D^2)

```

with `A == c/s - k^2/(4s^2)` and, more importantly, `D == d + k/2s`.

This `1/(A+D^2)` really looks like the usual `1/(c+d^2)`, doesn’t it?

### Conclusion

The `k` factor **advances or delays the light attenuation so that it only starts at a radius of `-k/2s`** (yes, it could also have "negative" radius, think of an imaginary point light inside an imaginary spherical mirror that would only let light out the second time). It appears that maths win again!

**Edit:** For a second I thought it was equivalent a spherical light, but it’s not. Most notably, it will not generate soft shadows.

### Usefulness?

My guess is that this parameter can be used by an artist to make a light appear like it’s closer (or further away) to the object in terms of illumination, but without moving it. Since point lights generate hard shadows, it may be a requirement that the light remains at a specific position.

# Answer
> 3 votes
The linear attenuation coefficient is the physical counterpart of light travelling into a medium. Without attenuation, light seems to travel in perfect void. When rendering "realistic" scenes, you want the air to attenuate the intensity of light over distance, and this attenuation is linear.

# Answer
> 3 votes
The linear attenuation factor is there for cases where you might want to use linear attenuation for your lighting, but the key thing is - you don't *have* to use it (or any of the other attenuations factors, for that matter).

This allows you to tune your lighting to your own personal tastes. So just set any attenuation factor you don't want to 0 and the ones you do want to non-0 and it's done.

One specific example where you might want to use linear attenuation would be if the more mathematically correct inverse-square provides too fast a fall-off. Using linear you can get a result that can look more or less good enough (and with fewer lights in the scene); so you'd use 0 constant, 1 linear and 0 exponential.

It's interesting to note (but admittedly not relevant to this discussion) that point sprites in both OpenGL and D3D (and point parameters in OpenGL) use the same attenuation formula.

Also worth noting that OpenGL/D3D lighting is not strictly intended to be physically correct; it was never designed to be anything more than an acceptable approximation, and that should be borne in mind when querying anything relating to the way it works.

Of course, nowadays you'll most likely be using a shader so the old light formula is mainly of academic/historical interest only - you can write whatever light formula you want.

# Answer
> 1 votes
* `c` is the constant attenuation value for the light source.
* `l` is the linear attenuation. That's why it's multiplied by the distante to the light source.
* `s` is the quadratic attenuation, so it's multiplied by the square of the distance.

There's some more info in this link.

# Answer
> 1 votes
It's might derive from the fact that Z, in the words of the esteemed Eric Lengyel,

> is nonlinear because perspective-correct rasterization requires linear interpolation of 1/z -- linear interpolation of z itself does not produce the correct results. The hardware must calculate 1/z at each vertex and interpolate it across a triangle, so it's convenient to just write that value to the depth buffer instead of performing an expensive division at every pixel to recover z.
>
> The fact that you get more z precision closer to the near plane is just a side effect and has nothing to do with the motivation behind 1/z interpolation.

Depth buffer stores distances. Light uses distance for attenuation. It could be the relationship between the depth buffer and lighting implementations that necessitated this, though that would apply only if the lighting algorithm ran in screen space I suppose. Remember that it's better to always store a precalculated (or hardware calculated) inverse, than to have to perform division on the undivided value for each op per frame which needs it... and that tends to be a very large number of ops.

This is just a guess.

# Answer
> 1 votes
Just as an addenum: When using the openGL model to approximation a spherical light source all three coefficients make sense and are valid (not "to prevent overflows" or to have "artistical freedom"):

For a sphere with radius r we get:

1/(d/r+1)^2

this translates to

c = 1 k = 2/r s = (1/r^2)

(see http://imdoingitwrong.wordpress.com/2011/01/31/light-attenuation/).

Imho this approximation is better than using infinitesimally small point lights with no extend at all!

# Answer
> 0 votes
I have a different view/answer about the formula.

When we view a spot light, for example, actually we see the light scattering. So the formula of 1/d^2 is only for the emit light of that pixel. But the brightness in our camera of that pixel will have a more complicated formula, which will use light scattering theory. See the paper

"Epipolar Sampling for for Shadows and Crepuscular Rays in Participating Media with Single Scattering"

by Thomas Engelhardt, Carsten Dachsbacher But unfortunately they don't have a final simple formula for light scattering. I guess maybe the final GPU imitation effect would be similar to the linear and quadratic formula.

So I think the claim:

"if you're trying to mimic reality, you want inverse-squared (and gamma correct)" is not valid.

Actually I use the formula with linear and quadratic factors without gamma can mimic the glowing effects very well. Linear cannot.

In a short summary, the formula has the physical counterpart of light scattering.

---
Tags: lighting
---


# Question
Title: Ray tracing - BRDF using Cornell measured spectral data
I wrote a ray tracer that implements various BRDF models (Oren Nayar, Lamber, Torrance Sparrow and so on). Now I'm trying to implement a BRDF from measured data. I choose the Cornell database data available here:

http://www.graphics.cornell.edu/online/measurements/reflectance/spraypaints/index.html

I want to use them because there's a representation of the data as spectrum with 31 sample (my ray tracer use spectral data for light calculation and then convert them to CIE XYZ and then RGB values for the final image rendering).

Which is the correct way to use this data? Which sample technique must be used?

# Answer
There is no canonical "correct way" to approximate general functions. Sorry.

With that said, the very source you linked to has suggested the Lafortune representation. This representation has been described as "...compact and works well for hardware rendering..." in chapter 18 of GPU Gems.

Implementation details appear to be out of scope for this question.
> 2 votes

---
Tags: lighting, raytracing, pbr
---


title: 2D A* Path-Finding

text:
# Question
Title: 2D A* Path-Finding
I have this problem, which isn't really a problem, but I feel like it's some sort of glitch in my code maybe.

My pathfinder, to find a path from A to B, does this:

which is almost fine, it works great, but others I have seen do this:

which, appears less "robot-like", looks cleaner, more real I think.. what am I doing wrong? I've tried several different heuristics:

tested with all of these and more (that got removed), and all produce the same/similar results:

(Manhattan, Euclidean, MaxDXDY, Diagonal) can't post more than 2 links, but I tried all of those + more

So I really think at this point it's to do with my algorithm code, could anybody see any problems?:

```
    public virtual Path Find(Point start, Point end, Func<Node, Node, float> heuristic, bool cutCorners = true, bool memorizePath = false)
    {
        if (CutCorners != cutCorners) { CutCorners = cutCorners; if (precalculatedNeighbours) PrecalculateNeighbours(); }
        if ((start == end) || !InBounds(start) || !InBounds(end)) return null;
        else
        {
            Node source = Nodes[start.X, start.Y], goal = Nodes[end.X, end.Y];
            if (memorizePath && memoryDictionary.ContainsKey(source) && memoryDictionary[source].ContainsKey(goal)) return memoryDictionary[source][goal].Clone();
            var open = new HashSet<Node>();
            var closed = new bool[Width, Height];
            while (!open.Contains(goal))
            {
                var current = open.LowestFScore(source);
                open.Remove(current);
                closed[current.X, current.Y] = true;
                foreach (Node neighbour in Neighbours(current))
                {
                    if (closed[neighbour.X, neighbour.Y]) continue;
                    float gScore = (current.GScore + neighbour.CostFrom(current));
                    if (!open.Contains(neighbour)) open.Add(neighbour);
                    else if (gScore >= neighbour.GScore) continue;

                    // 1st param - set parent, 2nd - gScore, 3rd - fScore
                    neighbour.Record(ref current, gScore, (gScore + heuristic(neighbour, goal)));
                }
                if (open.Count == 0) return null;
            }
            return ConstructPath(source, goal, memorizePath);
        }
    }

```

# Answer
> 2 votes
There is nothing wrong with your algorithm, it finds the shortest path. Want you want you can do with a extra step after your path is found. Usually its called something like 'SmoothPath'

* first compress the path: you're only interested in the important points, the important ones are the ones where the direction changes: in this example the startPoint, the endPoint and the one point where you change direction (g:12, f112)
* then you start with the startPoint and use a linedrawing algorithm (Bresenham) to see if you can skip a point, by trying to draw the line directly to the point after that. (in this case the endPoint) if that succeeds you can try the next point up until you cannot 'see' the point anymore. rinse and repeat (until the endPoint).

this way in your example you learn you can get rid of that middle point and are only left with two points as a path (the start and end)

* then you use that same line drawing algorithm to draw a line between them and voila

here's a link with pictures: http://deepnight.net/bresenham-magic-raycasting-line-of-sight-pathfinding/

# Answer
> 0 votes
This answer sort of tries to solve the question in a different way than you ask, but is useful in the context of games development, especially since your code appears to be working and finding a short path.

Is there any place you store X & Y coordinates in nodes ? because you could apply interpolation by using a catmull rom spline by taking all the points and lerping them to make a more natural route human like route.

http://gamesnorthwest.net/resources/modules/co2301/materials.html -- \< if you check week 12 there is an example program in a engine called TL(its visual studio 2013 modification using DirectX9/10) , its C++ but you can use the lecture notes and formula in the program to apply it.

https://www.youtube.com/watch?v=CFKWkYb1KZg \<\< video here shows what it looks like.

---
Tags: c#, xna, monogame, path-finding
---


# Question
Title: How to write a custom shader in Unity 3D that lights up a specific pixel or group of pixel?
I'm making a FPS game in Unity, and I want the environment to light up as the player is shooting on his environment. The map would be entirely put in darkness at the beginning, but as the player shoots the environment, it would be rendered with its "real texture". So say I have a tree. First it is entirely black or greyish, but if I shoot somewhere, I would see some green. To accomplish this, I'm using a raycast to get the impact point and so I can access any renderer of the point that the player is shooting on. I guess the next step would be to write a custom shader to light the exact pixel that is shot. Do you have any idea how I could write this shader or another way of doing this effect?

Regards

# Answer
So basically you are looking to paint your environment as it is shot?

1. Apply 2 textures to your object, the main texture being pure black, the secondary being the actual coloured texture.
2. Grab the point on the object that the mesh was struck
3. Convert this point into the x,y coordinate on the texture itself
4. Grab the pixel (and maybe surrounding pixels) and adjust the alpha of the main texture to 0 to reveal the one underneath

Check this docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html

There are probably some other better ways of achieving this, but I believe that this would work, in fact I might even try it out.
> 1 votes

---
Tags: unity, shaders, hlsl, graphic-effects
---


# Question
Title: understanding spatial hash function behaviour and Knuth for int64
I implemented open-indexing sparse 2D spatial HashMap, and I'm quite satisified with performance ( ~30-70 CPU cycles to get object at particular location for size ~16 Milion objects ).

However, I don't understand behaviour of hashFunction. Just by trial and error I found out that best performing for my case is slightly modified Knuth's hash function:

`return i * 2654435761 >> 8;`
( original Knuth's hash function is `return i * 2654435761 >> 16;` )

with this hash function I get no more than 1-2 buckets maped to the same hash (when capacity is sufficient) ... the histogram looks like: `689780 without collision (buckets mapped to same hash)
358791 with 1 colision
5 with 3 collisions`

but I have no idea why, and why it is performing better with `>>8` than `>>16`), and if this behaviour is general or somehow specific for my settings

I also tried other hash functions which are used as pseudo random generators .. some are here:

```
inline ULONG hashFunc( ULONG i ) {
// see http://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
//return  ( ( 2166136261UL ^ i ) * 16777619 );              // VERY BAD
//return  ( 2166136261UL ^ (i * 16777619) );                // VERY BAD
//return ((i >> 16)^i);                                     // NOT WORKING
//return ( i * 2654435761 >> 16 );                          // Knuth's multiplicative method // GOOD
return ( i * 2654435761 >> 8 );                             // GOOD, even better than Knuth for map size 2^16 ( 65536 fields )
//return ( i * 2654435761 >> 16 ) ^ i;                      // REASONABLY GOOD but worse than pure Knuth
//i = ((i >> 16) ^ i) * 0x45d9f3b; i = ((i >> 16) ^ i) * 0x45d9f3b; return  ((i >> 16) ^ i);                                        // REASONABLY GOOD but worse than pure Knuth
//i = ((i >> 16) ^ i) * 0x45d9f3b; return  ((i >> 16) ^ i); // LESS GOOD
//i = ((i >> 16) ^ i) * 0x3335b369; i = ((i >> 16) ^ i) * 0x3335b369; return  ((i >> 16) ^ i);                                        // LESS GOOD
};

```

all are performing worse than Knuth or modified Knuth. ( Just empirical observation, no idea why )

**The questions:**

1. Do you have experience that some other hash function performs better for such job ?
2. Do you understand the behaviour?
3. Do you know how to properly make analogy to Knuth 32bit for 64bit integer ( because if I understand it correctly, the 32bit golden ratio multiplicator is prime number, I'm not sure If it is easy to get multiplicator with such property for 64bit )

---

**some details for explanation:**

I have to say that I use the hash function somewhat differently than is common:

1. First I discretize `double x,y` to `uint16 ix,iy`
2. Then I compute `bucket` index as `uint32 bucket = (iy<<16)+ix;`
3. Then I compute the `uint hash = hashFunc()&mask` where `mask = capacity -1` and `capacity` is power of 2 ( `&mask` is basically `modulo capacity` ). I know that many people recommend use prime-number capacity for hashmap, but I find it tricky to find proper prime number during resize-ing, and also `&` is faster than `modulo`.

My hashmap is open-indexing, and it is able to realize if the object is in particular particular grid tile (ix,iy = bucket ) without actually dereferencing the object pointer, which I think gives it speed advantage.

each memory field of the hashmap stores not only pointer to the object `TYPE* object` but also the bucket index `uint32 bucket` to which the object belong and number of objects `uint n` with the same hash. The bucket index is used to check if object belong to particular (ix,iy) position or if it was mapped to that hash by chance (when there are collisions). I do not store hash since I think it is faster compute it on the fly than use more memory.

( you can see code here ( HashMap | HashMap2D | test\_HashMap2D) If you are interested

# Answer
First of all, for uniformly distributed data, Knuth’s function `i * 2654435761 >> 16` **is definitely better** than `i * 2654435761 >> 8` because it shuffles more bits. An explanation follows.

Consider the multiplication of numbers `WXYZ` and `PQRS` (all these letters representing arbitrary digits in any base) and see how the digits get added together in the end:

```
WXYZ * PQRS =    WP WQ WR WS
            +       XP XQ XR XS
            +          YP YQ YR YS
            +             ZP ZQ ZR ZS
            —————————————————————————
            =  A  B  C  D  E  F  G  H

```

You can see that the last digit of the result, `H`, only depends on `Z` and `S`. Whereas the digit in the middle, `E`, depends on all digits of the initial numbers. A good hash function of this form will therefore try to pick digits in the middle of the multiplication result, for better shuffling, hence the `>> 16` for a 32-bit hash.

Now what does it mean if your test results are not what the theory predicted? The theory may be wrong, but we’re talking about Knuth, so I’d be more tempted to say that **the test is wrong**. And indeed `TestApp` creates points with coordinates between `-150.f` and `150.f`, but your `map` object is set up to store values between `-16384.f` and `16384.f`. In other words, in the end you are hashing a series of numbers `WXYZ` where `W` hardly ever changes, making the higher bit values useless to the final result. I hope this makes it also clear to you **why** the `>> 8` shift is giving you better hashes.

I’m not sure how you’d want to fix the test, but you could for instance insert points in this way instead:

```
points[i].set((ix + randf()) * map.step * 0x7fff / nside,
              (iy + randf()) * map.step * 0x7fff / nside);

```
> 6 votes

# Answer
For MLCG constants you want an odd number that's a multiple of five (assuming no explicit modulo). That'll be a weak PRNG. For Weyl like generators in integer you want an irrational scaled and rounded to odd...golden ratio and sqrt of two are good choices. That will give you a weak low discrepancy sequence. Neither of these tend to work well for hashing.

Starting from the point where you have quantized and packed the coordinate what I would suggest is to pass that through a bit finalizer that performs well with low entropy inputs (keys). One or two xorshift multiple sequence as an example.

A method to improve the current scheme would be to change the shift and mask N bits to shift off all but the top N bits as per Sam's answer.
> 0 votes

---
Tags: mathematics, algorithm, space-partitioning
---


# Question
Title: picking 3D objects rendered using instancing
i have a peice of code that renders a 3D image, say a cube. I require 3 cubes in in different locations, this is done using instancing and i am able to render the cube in 3 different locations. However, i now need to pick any of the 3 cubes. I am pretty new to DirectX(11) and searches online did not yeild any answers. So how i pick an object when i only have a single set of vertices(triangle) used for the render?

# Answer
> 2 votes
Picking is not generally performed by the GPU so the use of instancing shouldn't matter.

Your CPU-side code presumably knew where the cubes where in order to put their transforms into the instance buffer. Hence it can do a ray-AABB test by transforming the picking ray into the space of the cube in the cube's local space.

Happily, the local space for the cube's AABB is just the unit AABB. You need only transform the picking ray by the inverse of the transform matrix you used for each cube's instance in the instance buffer.

The ray can be generated by creating a ray from the camera position through the point on the near-Z plane corresponding to the mouse location.

---
Tags: 3d, directx11, picking
---


# Question
Title: Recap on how a camera works in 3d Space?
*This may be marked as a duplicate, but I have been trouble thinking about a camera.*

I understand that there is a "camera transform," or view matrix. However, this is multiplied with every vertex in the scene when the camera is looking towards the negative Z axis at the origin. Do I move the camera around and then find a translation, rotation matrix to transform the camera to the origin, looking at the negative Z axis and multiply each point by this matrix (in addition to the camera transform later)? Or do I simply always keep the camera at the origin looking towards the negative Z axis, and "move" the world around it? If this is the case, how do I move the world around it? I am looking for the most efficient one.

*NOTE: NOT USING OPENGL OR DIRECTX OR ANY OTHER API OUT THERE*

# Answer
Both options are basically the same.

In the end you do have a bunch of vertices that you multiply by `mModel * mView * mProjection`.

If you move the camera within the world, that transformations go into `mView`. If you move the world around - into `mModel`.

`mModel` is actually constructed of many matrices guiding how objects and sub-objects are positioned within the world. So what you get is:

```
mSubSubModel * mSubModel * mModel * mIdentityWorld * mCamera * mProjection
// mIdentityWorld being identity matrix (can be skipped)

```

Now see how it is equivalent to:

```
mSubSubModel * mSubModel * mModel * mWorld * mIdentityCamera * mProjection
// mIdentityCamera being identity matrix (can be skipped)

```
> 1 votes

---
Tags: 3d, graphics, camera, matrix
---


# Question
Title: How to add user created data to drop down menu options
So I'm trying to make it that I can have a dropdown that will have user created info appear in it.

```
List<engines> engineList = new List<engines>();
public Dropdown engineSelect;

public class engines
{
    public string engineName;
    public int featureNumber;
    public int totalDevPoints;
    public string optimizedGenre;
    public engines(string name, int feature, int totalPoints, string opt)
    {
        engineName = name;
        featureNumber = feature;
        totalDevPoints = totalPoints;
        optimizedGenre = opt;

    }
}
engines playerEngine = new engines(engineName, numFeature, 0, whatGenre);

```

Pretend player set engineName, numFeature, and whatGenre with text fields. I wanted to have it that the drop down would add in whatever new engines the player makes. How would I do that? I want to have it say select engine: and then the player would pick from dropdown from engines they made(only saying engine names).

# Answer
Dictionary, which stores your data value against a key. Whatever the data value would be and whatever the key would be. It is very flexible.

You can use `Dictionary` for that purpose. With `Key-Value` pair of `string` and `engines`. Add all engines in that `Dictionary` against their names. Then add only names in list and upon selecting, get engine corresponding to that name.

For example,

```
// Declaring Dictionary for engines against string key.
Dictionary<string,engines> _dEngines = new Dictionary<string,engines>();

// Creating list of string in which each value will represent the relative engine.
List<string> engineList = new List<string>();

public Dropdown engineSelect;

public class engines
{
    public string engineName;
    public int featureNumber;
    public int totalDevPoints;
    public string optimizedGenre;
    public engines(string name, int feature, int totalPoints, string opt)
    {
        engineName = name;
        featureNumber = feature;
        totalDevPoints = totalPoints;
        optimizedGenre = opt;

    }
}

engines playerEngine = new engines(engineName, numFeature, 0, whatGenre);

// Adding engine to dictionary
_dEngines.Add("Engine1",playerEngine);

```

Now upon selecting from Dropdown item, let say if you select `"Engine1"` then you can get value by,

```
engines selectedEngine = _dEngines["Engine1"];

```

Hope this helps.
> 1 votes

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


# Question
Title: ArgumentNullException Parameter name: format
I have made a simple game using **Unity** with **Vuforia** and exported for Android and iOS. It works fine on Android, but on iOS it crashed and gave the error:

> ```
> ArgumentNullException: Argument cannot be null. Parameter name:
> format at System.Type.GetTypeFromHandle (RuntimeTypeHandle handle) [0x00000] in :0
> at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
> at System.String.Format (IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
> at System.String.Format (System.String format, System.Object[] args) [0x00000] in :0
> at UnityEngine.Debug.LogFormat (System.String format, System.Object[] args) [0x00000] in :0
> at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
> at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
> at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
>
> ```
>
> (Filename: currently not available on il2cpp Line: -1)

# Answer
First, you should try to replicate the issue in the Editor. The Editor runs the assemblies in debug, which should provide more information in the stacktrace you copied (like the line number, and all).

You can use the code formatter, which gives the current stacktrace:

```
ArgumentNullException:
Argument cannot be null.
Parameter name: format
at System.Type.GetTypeFromHandle (RuntimeTypeHandle handle) [0x00000] in :0
at System.String.FormatHelper (System.Text.StringBuilder result, IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
at System.String.Format (IFormatProvider provider, System.String format, System.Object[] args) [0x00000] in :0
at System.String.Format (System.String format, System.Object[] args) [0x00000] in :0
at UnityEngine.Debug.LogFormat (System.String format, System.Object[] args) [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0
at Vuforia.TrackerManager.InitTracker[T] () [0x00000] in :0

```

Now, what is happening, is that in Vuforia's trackermanager, there's a Unity.Debug.LogFormat call, that is trying to pass a null argument. You should report that to Vuforia's dev.

It's either a bug on your side (not setting up things correctly, not getting rid of them properly, not having access to certain resources on iOS; can be anything, really), or theirs. If it's theirs, do a bug report to them. Or ask them. They should have some support. Or look at their doc/FAQ.
> 2 votes

---
Tags: unity, ios, vuforia
---


# Question
Title: Prediction of collision place and time in Unity
I have two moving objects. I have chosen trajectories for objects that they would definitely collide if they don't change speed or trajectory. Is there easy way to check at which point and time the objects will collide with given parameters (current object positions, their velocity vectors and speeds or any other parameter accessible from Unity)?

# Answer
> 0 votes
I think the easiest way would be to just simulate forward in time until the collision happens. Take copies of all the relevant datum (positions, velocities) and loop, incrementing everything until you detect the collision.

To figure out when it will happen, take the game time before you do the above and each time you loop, add X to it, where X is the average frame time that you've been calculating in anticipation for this moment. Hopefully that will give you a decently accurate answer.

Note: I've not used Unity very much, hence the distinct lack of a helpful code sample in my answer, but hopefully this will help a little. It's how I would first try doing it, at any rate.

---
Tags: unity, collision-prediction
---


# Question
Title: How to enforce touching within a ring shape?
I'd like to have the player moving the finger within the shaded ring:

The game should be able to detect "out-of-boundary" events once the finger moves outside the ring. How can I accomplish this?

# Answer
Presumably you have the center point of the ring (`c`), and the radius of the inner and outer segments of the valid portion of the ring (`ri` and `ro`, respectively)

Then, given any touch point `p`, you simply need to perform two point-in-circle tests. The touch is valid (within the ring) if it is both outside the inner circle and inside the outer circle. A point `p` is within a circle of radius `r` with a center at `c` if it satisfies the inequality:

```
(p.x - c.x)^2 + (p.y - c.y)^2 < r^2

```

So you need

```
BOOL insideInner = pow((p.x - c.x), 2) + pow(p.y - c.y, 2) < (ri * ri);
BOOL insideOuter = pow((p.x - c.x), 2) + pow(p.y - c.y, 2) < (ro * ro);
BOOL isValid = !insideInner && insiderOuter;

```

to determine if the current touch point is valid (\`isValid). You get updated touch positions every touch or drag event, which you can feed to the computation and determine if the touch ever leaves the valid area.

Note that you can factor out a bunch of that math to avoid repeated computation.
> 5 votes

---
Tags: mathematics, input, geometry, touch, trigonometry
---


# Question
Title: Change button sprites in scrollview Unity3D_5.2
I have a scroll view with lots of buttons on it. when i press one button, that button needs to change the sprite and stay like that. if any other button (or same one) is pressed previous button needs to revert back to original sprite.. here is some example

button 2 was pressed and changed sprite, it stays like that untill it is pressed again or any other (in this case button 3) is pressed

# Answer
> 0 votes
You should use UIToggle with Toggle Group instead of doing it manually.

You can create multiple Toggle buttons having same Toggle Group then so only one button (toggle button) will be enabled at a time.

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


# Question
Title: SVD vs Normal decomposition for BRDF compression
In the slides over here by NVidia, they describe methods for BRDF compression. They first create a BRDF matrix where each column(or row) corresponds to a single light direction (or outgoing view direction). This matrix is then compressed by decomposing it either by using SVD or Normalized decomposition. My question is that they claim SVD gives better results than Normalized decomposition for similar compression sizes. Does anyone know what could be the possible reason for this?

# Answer
> 1 votes
The singular value decomposition produces the Eigenvalues with largest magnitude, and their corresponding Eigenvectors. If one were to decompose every Eigenvector of a matrix, they have performed a Principle Component Analysis.

The principal components represent the 'n'-dimensional axes on which the most variance is encoded. Therefore they can be used as lossy compression; they optimize which normal vector in the 'n'-space to direct a scalar value, such that the line defined by this normal best represents the information in the original matrix.

---
Tags: rendering, lighting, compression, pbr
---


# Question
Title: Image rendering with additional space around it
When I try to display an image that is 400 pixels wide and 800 pixels high, it is not displayed this way. Instead it is diplayed like this: Instead it is displayed like this

You can see at the bottom and a few pixels right to the phone some thin white lines, I did not add this manually and it is not part of the picture, the picture is perfectly cropped around the phone.

When in my fragment shader I add `+ vec4(1, 1, 1, .5)` it shows the area that the phone should have covered. Image

**Code for creation of an object that holds info about the image:**

```
GuiTexture phone = new GuiTexture(loader.loadTexture("phone_cropped"), Display.getWidth() / 2, Display.getHeight() / 2, 2, 400, 800);

```

**The loadTexture method:**

```
public int loadTexture(String fileName) {
    Texture texture = null;
    try {
        texture = TextureLoader.getTexture("PNG", new FileInputStream("res/" + fileName + ".png"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    int textureID = texture.getTextureID();
    textures.add(textureID);
    return textureID;
}

```

**The line that calls the render class to render the image**

```
guiRenderer.render(guis);

```

**The transformation matrices that the image is multiplied by:**

```
float width = gui.getWidth() / 2;
        float height = gui.getHeight() / 2;

        Matrix4f modelMatrix = new Matrix4f();
        modelMatrix.m00 = 2.0f / (float) Display.getWidth();
        modelMatrix.m11 = 2.0f / (float) Display.getHeight();
        modelMatrix.m30 = -1;
        modelMatrix.m31 = 1;

        shader.loadModel(modelMatrix);

        Matrix4f transformationMatrix = Maths.createTransformationMatrix(
                new Vector2f(
                           gui.getxPos(),
                        - (gui.getyPos())
                ), gui.getRotation()
                ,new Vector2f(
                        width,
                        height
                )
        );

        shader.loadTransformation(transformationMatrix);

```

**Vertex shader code:**

```
gl_Position = modelMatrix * transformationMatrix * vec4(position, 0.0, 1.0);
textureCoords = vec2((position.x+1.0)/2.0, 1 - (position.y+1.0)/2.0);

```

This does not happen to all images, when I load in an image that is square and I try to display it with width 400 and height 800 it works perfectly. Image

With different images it yields different extra space.

All images are `.png`. The phone image is 1009x2057 pixels. I also tried to use a phone that was 2048 pixels high (1006x2048) since this is a power of 2, that still yields a white line on the side but does look better: image

The square (3rd image) that was elongated to look like a rectangle and does display correctly is 256 x 256 pixels.

All displayed images have a slight rotation because without rotation the little white thin lines don't always show up, the rotation did not change anything about the images.

To load images I use slick utils TextureLoader class.

# Answer
You load your images like this:

```
texture = TextureLoader.getTexture("PNG", new FileInputStream("res/" + fileName + ".png"));

```

However if you read through the source code of slick you'll see that internally it is represented as `TextureImpl` which was the following documentation.

> A texture to be bound within JOGL. This object is responsible for keeping track of a given OpenGL texture and for calculating the texturing mapping coordinates of the full image. Since textures need to be powers of 2 the actual texture may be considerably bigged that the source image and hence the texture mapping coordinates need to be adjusted to matchup drawing the sprite against the texture.

So since neither the height nor the width is a power of two slick will scale up the texture to the closes power of two. So if the image is 400x800, the resulting texture will be 512x1024 where the created space will be filled with a transparent black color. It also seems that slick loads the texture slightly incorrectly where some of the right wraps around to the left side of the textures creating that "line". That same happens at the top of the texture where it will wrap to the bottom. So the "line" is actually the volume and power buttons on the iPhone.

To avoid this you have at least three options:

* Always load images that have sides that are power of two.
* Use Slick's calculated texture coordinates, e.g. `texture.getHeight()`.
* Load the images yourself and avoid the power of two limitation.
> 3 votes

---
Tags: opengl, java, lwjgl, image
---


# Question
Title: Collision Responses with many different types
I'd like to write an efficient Collision Response code, that does not use instanceof/type checks that often (if possible)

my current implementation is something like this:

```
GameObject.collidesWith(GameObject other)
{
    if(other instanceof ConcreteType1)
    {
        //do response with Concrete Type 1
    }else if (other instanceof ConcreteType2)
        // do response with Concrete Type 2
    }
}

```

`GameObject` is the base class of everything. Is there a possibility to avoid instanceof and type checks?

# Answer
This is the part I currently need to work on for my own game..

What I've reasoned out so far is that I can have a `CollisionBox` on the `GameObject` which contains all the collision boundary information. Collisions are checked by `GameObject.isColliding(other)` \- where the two `CollisionBoxes` compare whether they intersect.

```
if (gameObject.isColliding(other))
{
    gameObject.doCollision(other);
}

```

then the `GameObject` has a `doCollision` method which is overridden for various `GameObjects`

```
public GameObject
{
    CollisionBox collisionBox;
    CollisionType collisionType;

    public void doCollision(GameObject other)
    {
        switch(other.CollisionType)
        {
            case Inelastic: //etc
            case Elastic: //etc
            case Consumable: //(this one is for bullets, upgrades, pickups -
                // things you collide with but the collision doesn't affect motion)
        }
    }
}

```

As you can maybe guess, `CollisionType` is an enum which is assigned to `GameObject`.

---

That was my initial plan anyway. Now I hope to take some inspiration from Collision detection and response in an Entity System \- though I'll still probably end up with some type of "collisionType enum" to broadly group a type of collision.
> 2 votes

---
Tags: collision-detection
---


title: Transform components in ECS

text:
# Question
Title: Transform components in ECS
Many game engines I've seen which are based on an **Entity Component System**. It has some kind of a **Transform Component** as a necessary component attached to all of their entities. While this does seem to make kind of sense considering an entity is only some kind of property bag and a collection of components and transformations are world space behavior *(hence just part of the composition)*. I've noticed two other things which are very weird:

* **Transform components** are used to build up the hierarchy between entities as they have a parent entity as well as child entities
* **Transform components** are specialized for only a single kind of world space, e.g. 2D or 3D.

Examples:

* The Unity3D engine. Entity children and parents seem to be accessed through the **Transform Component** of each entity. Also, the **Transform Component** features coordinates in 3D vectors.
* The **Xenko Game Engine** (previously Paradox3D), which can bee seen on GitHub.

So, is this a common practice? Best/worst practice? What's the reason behind having:

1. a fixed **Transform component**,
2. making the **Transform component** only suitable for one world space
3. using the **Transform component** as an hierarchy graph?

# Answer
> 3 votes
The `TransformComponent` idiom is common in most component-based engines, not just ECS engines (note that with Unity there are no "Systems" related to `MonoBehavior` objects, so it's not *really* an ECS, at least in the C# portion).

A lot of engines literally do hardcode the existence of the `TransformComponent` and make the transform built in to the core `GameObject` ("Entity") objects. There is not a strong industry preference one way or the other in my experience; I've heard well-reasoned but non-definitive arguments for both approaches. True ECS architectures of course must have a separate `TransformComponent` as there isn't any actual `Entity` object in which to hardcode such a component.

Game object hierarchies do tend to be built into the concept of a `TransformComponent`. The primary gameplay use of the object hierarchy is specifically for the *transform hierarchy*. It's thus most convenient to reuse the idea of the transform hierarchy if you need object organization. This can seem wasteful in some engines where "global" objects are frequently used for non-spatial background systems (this is common in Unity for example) but isn't really a big deal.

I can't think of any particularly strong reason to have separate 2D and 3D transforms. No engine I've used in any significant capacity has done that. 2D is a clean subset of 3D so you can readily reuse the 3D transform for 2D purposes. The few possible reasons I can think of for separating these are vastly outweighed by the complexity of an engine needing to support both.

---
Tags: unity, c#, game-design, entity-system, component-based
---


# Question
Title: How to read a custom binary file made with Adobe air into Unity 3D & C#
I have a custom data file from a project that was authored in actionscript some years ago by another developer. I am porting parts of the project over to Unity 3D. I don't have any documentation for the original project (I hope to speak to the original developers at some point but I cannot wait for that).

The file is a special bitmap that represents the positions of objects on a grid. The custom file is created using an editor created in Adobe air. I believe (not knowing any better) that the source code I have for the file decoder is the same source from the editor. I don't have the editor source code.

Where I am getting into trouble is the binary file. From what I can tell at the moment, the file is a compressed byte array on the Adobe air side of things. I don't believe I can just load the compressed file with Unity3D as a resource object. I would like to decompress the file and use it as an asset in Unity.

I am trying to figure how to decompress the binary file. I have tried viewing the file contents in a hex editor to establish what the compression format is with no joy; I have not done anything specifically like this before . I have tried to use gzip and a few other apps to decompress the file.

Form what I have read in the action script documentation that the default compression should be zlib.

Here is some edited code from the original project for decoding the bitmap:

```

import flash.utils.ByteArray;

public function decode(byteArray:ByteArray):Boolean
    {
        var i:uint;
        var j:uint;

        if(colourMap!=null)
        {
            colourMap.dispose();
            depthMap.dispose();
        }

        byteArray.uncompress();
        byteArray.position=0;

        var fileVersion:String=byteArray.readUTFBytes(FILE_VERSION.length);

        if(fileVersion==FILE_VERSION)
        {
            numWidth=byteArray.readUnsignedInt();
            numHeight=byteArray.readUnsignedInt();

            if(numWidth==0)
            {
                numWidth=30;
                trace("WARNING FOR SOME REASON WIDTH WAS 0 FROM FILE");
            }

            if(numHeight==0)
            {
                numHeight=30;
                trace("WARNING FOR SOME REASON HEIGHT WAS 0 FROM FILE");
            }

```

Here is a hex dump of the initial part of the binary data file:

78 da ec bd 55 cf 6c 5d 76 a5 79 7c 53 2a ff 8c

# Answer
> 0 votes
I am able to de-compress the data file using an answer from here:

https://unix.stackexchange.com/questions/22834/how-to-uncompress-zlib-data-in-unix

The printf is creating a gzip header to coax gzip into decompressing the byte stream.

```
printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" |cat - somedata.raw |gzip -dc

```

Where "somedata.raw" is the compressed byte stream.

To save the uncompressed data to a new file I changed the above to:

```
printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" |cat - somedata.raw |gzip -dc > uncompressed_data.raw

```

I viewed a hex dump of the head of the new file & it was what I expecting.

```
0000000 42 37 31 2d 30 2e 32 00 00 00 31 00 00 00 21 01

```

The first 3 characters are B71 which what I am expecting it relates to the a version number in the data file.

Heh heh, it has been years since I had to think about ASCII code.

---
Tags: file, compression
---


# Question
Title: Is it efficient to use Lua to store game data?
I'm new to Lua and I'm wondering, is it efficient to use Lua to store game data (such as monster's description, spells).

My problem is this: when I try to create a monster object every second, I have to run the Lua file and get the data repeatedly, which I think may be not efficient.

Before I try to use Lua, I use XML to store data: at the beginning of gameplay, I read the "monster.xml" file once, and keep it in the memory, and every time I need to create a monster, I just refer to it.

Is this XML approach more efficient than the Lua one ? Or are there other better solutions?

# Answer
> 17 votes
Lua was actually designed to be an efficient data file format. It's original use was to load huge geographical data sets. Actual scripting/logic features came later. Even with all the new scripting features, it is still used by its original authors to store and load large data sets.

That is not to say that Lua is the most efficient choice. That will depend on a number of factors, but in general tightly packed binary data is the most efficient (disk access times are much longer than processing/parsing time).

Since you said you are having trouble deciding, here's the best answer I can give you: it doesn't matter. It really, really doesn't matter. Pick which ever you find easiest and most comfortable to use, implement it, and move on to making your actual game. "Best" solutions always lose out to "actually working" solutions in the real world. If you stop and worry and get paralyze over every "which is better" question you have during development, you will never ever actually have a working product. If you choose wrong, you can always go back and change the code later.

# Answer
> 3 votes
I think that the problem here is not lua or xml but the design. IMO you should use a fatory pattern coupled with a prototype. Your lua script should be used to create a new prototype of monster, then your factory will create new "instances" of this monster (cloning the prototype). This way you have to run your script only once.

However, if all of your monsters have different stats then you can run an other script per monster to select the prototype to use and setup these stats. This avoid to rerun the common part of the script multiple times.

# Answer
> 3 votes
I have a small library called Luatable that I use to do this very thing. It loads a Lua file and keeps it in memory, then allows you to access the data with (I think) a very intuitive interface.

Here's a small example.

Lua code that describes a monster:

```
monster = {
    health = 100,
    name "Troll",
    lootTypes = { "gold", "chain_armor" }
}

```

Accessing this data from C++:

```
Luatable::Value definition;
Monster monster;
definition.loadFromFile("Troll.lua");

troll.health = definition["monster"]["health"].asInt();
troll.name = definition["monster"]["name"].asString();
Luatable::Array& lootTypes = definition["monster"]["lootTypes"].asArray();
for (int i = 0; i < lootTypes.size(); ++i)
{
    monster.addLootType(lootTypes[i].asString());
}

```

There are more examples in the readme on the Bitbucket page.

# Answer
> 0 votes
**It does not matter!**

You said you load the file at the beginning of gameplay. I infer that it's being loaded during the loading screen. If you have a sufficiently slow HDD (e.g. in a low end laptop from 2008), parsing a file is still faster than reading it from disk, no matter which format you use.

Even if you later have to change it, this is where proper design comes in. Programming practices like TDD are encouraged because they make you split classes correctly. In this case you have a class that creates a monster from data, and if you later find out it needs to be faster, you simply replace it with a different class.

---
Tags: lua, data
---


title: Rotation, what is the Matrix?

text:
# Question
Title: Rotation, what is the Matrix?
From a previous question, thank you very much by the way, but what on earth is the `Matrix` of? I'm very new to Mono/XNA and finding any meaningful documentation is practically impossible.

```
point = Vector2.Transform(point, Matrix.CreateRotationZ(AngleToRotate);
point += originPoint;

```

**Edit:** I would like to rotate my 2D game world around my character who is in the center of the view port. I was kindly given the above function, which I'm sure with the knowledge how to use it, would be exactly what I'm looking for. However, I don't have that knowledge. I understand what vectors are, but I have no idea what the matrix is generated from.

# Answer
> 2 votes
In this case, the matrix is generated from the call to `Matrix.CreateRotationZ`, which is a function (a static method of the `Matrix` class). It creates a 4x4 tranformation matrix which describe a rotation about the Z axis. The formula for constructing that matrix can be seen here, as `Rz`. Extending that the 4x4 form used for the `Matrix` class, it would look like this:

```
cos(theta) -sin(theta) 0 0
sin(theta)  cos(theta) 0 0
    0           0      1 0
    0           0      0 1

```

`theta` is the desired rotation angle (your `AngleToRotate`).

In addition to the linked Wikipedia page, you may want to read The Matrix and Quaternion FAQ.

# Answer
> 0 votes
The thing you currently have is a `transformation matrix` Transfomation Matrices are way, to easily represent a the position, rotation and scale of an object in 3d or 2d scene, a 2d scene only needs a 3\*3 matrix, a 3d one usually uses a 4\*4, but 2d transformation can be represented in a 4\*4 matrix too, but it just wastes space. The matrix is oriented like this:

Translation matrix (x, y and z coordinates)

```
1 0 0 x
0 1 0 y
0 0 1 z
0 0 0 1

```

Scale matrix (again, x, y and z values)

```
x 0 0 0
0 y 0 0
0 0 z 0
0 0 0 1

```

Rotation matrix is a bit more involved, it is different on x, y and z axis, this is for example the z axis (for 2d rotation basically:

```
cos(theta) -sin(theta) 0 0
sin(theta) cos(theta)   0 0
0                0                   0 0
0                0                   0 0

```

By multiplying these matrices together in a strict way (translation * rotationxyz * scale), ypu get the trabsformation matrix.

Also, matrices are used in many more ways, like ptojection matrices, wich help to convert from 2d semi-ortographic projection to e.g perspective projection, or view matrix, wich defines the camera's position, you too have a view matrix.

If you multiply together the projection, the view and the model/transformation matrix, you get a modelviewprojection (MVP) matrix, wich is used, to get the screen positions of models or sprites.

To rotate your world around, you need to multiply every point with the rotation matrix you have, and you get the transformed position, wich look like it is rotated around.

---
Tags: rotation, matrix
---