# Question
Title: Can you recommend a good beginners book or project for a young person?
I'm sorry if this question is a bit subjective but I'm sure you'll understand why.

I participate in a volunteer program, Big Brother Big Sister, and my match loves computer games and he'd love to make them. He's 16, and he's not that technical yet, I was showing him some html5 canvas stuff (I'm a web-dev, so it's easiest for me to explain that to him) but it's a little opaque to him, and of course the technology is still pretty limited.

What would be a good way for him to get into the fundamentals of making a game without having to know tons of code? Something like 3D Game Maker maybe?

---

Everyone, your answers have been really helpful, and I wish I could accept multiple answers, this will be really useful. Thank you all.

# Answer
One way to start making a game with no programming knowledge is to use one of the many game engines specifically tailored for a genre of game. And since they're designed with a single game genre in mind they usually don't even require you to learn a scripting language. To name a few:

* RPG Maker \- for 2D role playing games (I loved playing around with this when I was his age!)
* Visionaire Studio \- for point'n'click graphic adventures
* M.U.G.E.N \- for 2D fighting games

And although he might need to learn a bit of programming it shouldn't be that hard to use:

* Flixel \- A Flash game library, general purpose but with a lot of facilities to help make platformer games.
* GameMaker \- is also famous although I have never used it.

Also, since he's getting started, I do recommend starting with 2D games before moving on to 3D games.

I think RPG Maker would be a great place to start because while you don't need to write code directly, the way the event system is set up makes you need to think logically which is a must for a programmer.

You basically create events, set up the conditions for them being triggered, and add a series of actions with configurable parameters. You also have flags to set which would be the equivalent of variables, and you can control the flow of these events using conditionals and loops. All in all this sort of thinking will translate very well to real programming later on.

Visionaire Studio is also very similar to this but for another genre!
> 19 votes

# Answer
I'm upvoting David's answer, but started writing a big comment talking about other stuff so I'm just putting it as an answer.

GameMaker is probabl your best bet. He can start off by clicking and dragging Actions in response to Events. Then he can start learning to express these things in code with GML (Derek Yu's tutorial series is good).

After a while he'll start to ask, "Why can't I execute this type of code in this type of situation?"

That's when you start him with Python. Try going through Invent Your Own Games With Python. It starts with basic programming, guides you through making a couple of ASCII games (Hangman, Tic Tac Toe, etc.) then builds up to using PyGame.

And then he can coast on PyGame for a while :)
> 6 votes

# Answer
Not being directly a book about gamedev, this book from O'Reilly contains description of many interesting projects (among those also games) suitable for beginners and teenagers:

Coding4Fun from O'Reilly

I bought it for my own courses of XNA and never regretted, it has interesting projects and you describes the implementation step by step.
> 4 votes

# Answer
For someone of that age/ skill level, they should start **by building levels in their favorite game engine of choice**.

I'm not sure ***why*** this is the most overlooked but most obvious answer.

Many great games come with a level editor that allow many degrees of freedom.

***RPG***: Bioware's NWN 2 electron toolset series, Elder scrolls

***RTS***: Warcraft III's level editor is a fantastic RTS editor and even spun off it's own ***game*** ( league of legends and heroes of newerth ).

***FPS's***: Hammer for half-life 2

In short, there's no shortage of level editors to get started. Here. Building levels for your favorite game is probably the best place to start.
> 3 votes

# Answer
I would look at 3DBuzz.com and look up a tutorial for a 2D shooter for Unity, it is free and really easy to use, plus he can learn how engines work and start with little programming. It is a good way to get his feet wet and really see how programming works.
> 2 votes

# Answer
In my opinion, I have to agree with the people who answered Game Maker. You can get the basics for free and it's inviting for new game developers! It's pretty easy to make a basic game with the drag and drop actions and you can make even more with the actual coding language. If you try it out, you'll find that you can make some pretty great stuff.
> 0 votes

---
Tags: game-maker
---


# Question
Title: back-face (back-line) culling without winding order
In fooling around with my own 3D display engine I've been able to get a few modest features working, and I've come close with this latest one - line culling - but I fear in order to do it correctly I'll need to backpedal a little bit and start establishing more attributes in my basic wireframe objects. I'd like to avoid that if possible because I legitimately haven't needed it until now (maybe).

The basic '3d object' class is essentially just lists of lines, points, an RGB value for color, and a few self-transforming methods for basic movement and rotation.

```
class MyObject(object):
    def __init__(self, points, lines, color):
        self.points = points
        self.lines = lines
        self.color = color
    # insert methods for rotation/translation/etc

```

No vertex order, no collection of 'faces' or 'sides' or anything, just points and lines and a color.

I've tried to introduce a culling method into my view object that uses all the possible triangles that each line could be an edge with, and then checks the dot product of that triangle's outward-facing normal against the imaginary line from the camera to the shared point in the triangle (v0, pt\_a, etc).

```
def line_cull(self, shape):
    """Determine which lines should be drawn by comparing them against
    the triangles they could be a part of. If the triangle faces away from the
    camera, don't draw that line.
    """
    to_draw = []
    for line in shape.lines:
        a, b = line
        # get a list of the other lines that point a exists in
        other_lines = [m for m in shape.lines if a in m and m is not one]
        # treat point a as "vertex 0" and get the line from a to the camera
        a_to_cam = minus(a, self.camera)
        for line2 in other_lines:
            # get the correct point c
            if not a == line2[0]:
                line2 = line2[::-1]
            c = line2[-1]
            # get the vector of ab and ac for a cross product
            ab = minus(b, a)
            ac = minus(c, a)
            # find the middle of the triangle
            mid = [x / 3.0 for x in plus(a, plus(b, c))]
            # outwards is the direction vector from the shape's center
            # to the middle of the triangle. for whatever reason this
            # has been working better at orienting the normal than just
            # using the dot product to the center of the object
            outwards = minus(mid, shape.center)
            norm = cross(ab, ac)
            if dot(norm, outwards) < 0:
                norm = cross(ac, ab)
            if dot(norm, a_to_cam) < 0:
                if line not in to_draw:
                    to_draw.append(line)
    return to_draw

```

This works for certain shapes a lot better than others. Sticking to platonic solids for now - tetrahedrons and cubes are perfectly drawn, whereas octahedrons (especially rotating ones) have flickering back-end lines.

I did try to include a line about confirming the existence of line BC -- that is, the imaginary 'third line' in the triangle -- and all of a sudden, all my cubes disappeared! Because there would never be a third line in its series of right-angles, and so there was nothing to render anymore.

My question is -- do I **have to** establish faces/sides/etc in order for this to "just work", or is there a way to suss out which pairings should not be considered, without just excluding certain shapes from being rendered at all?

# Answer
> 3 votes
> My question is -- do I have to establish faces/sides/etc in order for this to "just work", or is there a way to suss out which pairings should not be considered, without just excluding certain shapes from being rendered at all?

Yes. The problem is that its completely ambiguous what a face even *is* in your formulation. Right now, you're implicitly assuming all points and lines are on the border of a solid object, and that they have a consistent "outside" and "inside".

However, without information about normals or the volumetric properties of the shape, you have no means of determining the correct orientation of each face. You're left trying to guess the normal from the fact that the shapes you are drawing just happen to be convex. This is a losing battle, in my opinion.

Why not introduce the concept of triangles and winding order? There's a reason graphics libraries do this, and you just rediscovered it. It's not that difficult to implement either. Just reinterpret every three points as a triangle and assume a winding order. Then the code doesn't have to do any checks to try to compute a face normal -- the work goes into properly modeling the shapes instead.

# Answer
> 0 votes
I would prefer to make this as a comment, but I don't have the rep yet.

While what you have isn't the easiest or most recommended way to go about that, it theoretically could work. You probably have a bug, my guess is that the cross product is trying to cross a line with itself on your more complicated shapes and returning a normal of length 0.

Also, if your normals point the wrong direction, you don't need to recross them, you can simply just negate all the values (manually, or multiply the normal by -1.0) and you'll have a normal pointing the opposite direction. And, cross products aren't guaranteed return normalized vectors, so you'll probably want to normalize the vectors you get out of them before you use them.

---
Tags: python, pygame, culling
---


title: How to combine VAO and shader language?

text:
# Question
Title: How to combine VAO and shader language?
I'm new and trying to draw a very simple quad with VAO and GLSL.

My definitions:

```
typedef struct SPos
{
    float x;
    float y;
} SPos;
SPos mVertices[6];
SPos mIndicies[6];
GLuint mVao;
GLuint mVertexVbo;
GLuint mIbo;

```

These are my steps:

1. Load Vertex, Fragment code (I'm sure that no mistake in this step) and get programID
2. Create VBO

```
glGenBuffers(1, &mVertexVbo);
glBindBuffer(GL_ARRAY_BUFFER, mVertexVbo);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(SPos), mVertices, GL_STATIC_DRAW);

```
3. Create IBO.

```
mIndices[0] = 0;
mIndices[1] = 1;
mIndices[2] = 2;
mIndices[3] = 3;
glGenBuffers(1, &mIbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * sizeof(GLuint), (GLuint*) mIndices,\
    GL_STATIC_DRAW);

```
4. Create VAO

```
glGenVertexArrays(1, &mVao);
glBindVertexArray(mVao);
glUseProgram(mProgram);

GLint posLoc = glGetAttribLocation(mShader.program, "a_posL");
glEnableVertexAttribArray(posLoc);
glBindBuffer( GL_ARRAY_BUFFER, mVertexVbo );
glVertexAttribPointer( posLoc, 2, GL_FLOAT, GL_FALSE, 0, 0 );

glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mIbo );
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

```
5. Render loop.

```
mVertices[0].x = -50.0f;
mVertices[0].y = -50.0f;

mVertices[1].x = 50.0f;
mVertices[1].y = -50.0f;

mVertices[2].x = 50.0f;
mVertices[2].y = 50.0f;

mVertices[3].x = -50.0f;
mVertices[3].y = 50.0f;

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(mVao);
glDrawElements( GL_TRIANGLE_FAN, 4, GL_UNSIGNED_INT, 0 );
// GLES2 swap function.
eglSwapBuffers ( esContext->eglDisplay, esContext->eglSurface );

```

These are my shaders

fragment:

```
#version 300 es
precision mediump float;

out vec4 oColor;
uniform vec4 unifColor;

void main()
{
    oColor = vec4(1);
}

```

vertex:

```
#version 300 es

in vec2 a_posL;

void main()
{
    gl_Position = vec4(a_posL, 1.0, 1.0);
}

```

Nothing is draw in the screen. What's wrong?

All above is follows a VAO tutorial on the internet.

I spend 1 day to debug and scan it very carefully but not work.

**EDIT:**

Thanks GOD. The problem is that I setted the data of mVertices in render step, have to set it before create VBO.

I'm still confuse that glBufferData need a pointer for data but Why I cannot pass the address of data then assign its value in later? Why I have to assign its value before bind it to VBO?

# Answer
> 1 votes
`glBufferData` makes a *copy of the data* and stores it in the VBO. This will then be uploaded to the gpu and the client can free/reuse the memory.

---
Tags: opengl-es2, fragment-shader, vertex-arrays
---


# Question
Title: Libgdx Sprite is not drawn when generated inside another class
I´ve built a gameloop where I generate new items depending on the elapsed time and want to place them somewhere on the screen. I use some randomness for the color and coordinates. For better design I want the sprites of these items to be generated by classes that contain additional information on these items. But I figured out that when doing so my sprites won´t be drawn. Sprites that are generated explictly inside my loop are perfectly drawn.

This is my current gameloop

```
public void loopGame(float delta) {

    Gdx.gl.glClearColor(255, 255, 255, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    timer.addDelta(delta);

    Gdx.app.debug("Bubbles", "Time: " + String.valueOf(this.timer.getCurrentTime()));

    batch.begin();

    Sprite freeBubble = new Sprite(new Texture(Gdx.files.internal("data/img/bubble_black.png")));
    freeBubble.setPosition(200, 200);
    freeBubble.draw(batch);

    Bubble newBubble = this.bubbleFlask.createNewBubble(timer.getCurrentTime());
    if (newBubble != null) {
        bubbles.add(newBubble);
        Gdx.app.debug("Bubbles", "Created new bubble!");
        Gdx.app.debug("Bubbles", "Attributes: " + newBubble);
    }

    // draw all bubbles
    for (Bubble bubble : bubbles) {
        Gdx.app.debug("Bubbles", "Drawing bubble");
        Sprite bubbleSprite = bubble.buildSprite();
        bubbleSprite.draw(batch);
    }

    batch.end();

}

```

The `freebubble` is perfectly drawn. `this.bubbleFlask` generates bubbles the way it is supposed to but those bubbles are not drawn inside the for loop. Debugging messages show me that the loop works as it should.

So you might guess that `bubble.buildSprite()` is broken. Here is this method:

```
public Sprite buildSprite() {
    Sprite sprite = new Sprite();
    sprite.setTexture(new Texture(Gdx.files.internal("data/img/bubble_black.png")));
    sprite.setPosition(300f, 300f);
    return sprite;
}

```

For the sake of demonstration I placed the same texture file here.

What am I missing here?

# Answer
> 1 votes
Seems like `buildSprite` is broken indeed. The `freeBubble` sprite is created with a different constructor, which seems to be the only difference between a properly drawn sprite and those made by `buildSprite`. Sprite's javadocs state that its parameterless constructor gives you instances that need more than just textures to be set. On the contrary, calling `new Sprite(texture)` gives you a ready sprite. From Sprite.java:

```
/** Creates an uninitialized sprite. The sprite will need
/** a texture region and bounds set before it can be drawn. */
public Sprite () {
    setColor(1, 1, 1, 1);
}

/** Creates a sprite with width, height, and texture region
/** equal to the size of the texture. */
public Sprite (Texture texture) {
    this(texture, 0, 0, texture.getWidth(), texture.getHeight());
}

```

---
Tags: libgdx, graphics
---


# Question
Title: Is there any way of creating primitive 2D shapes in unity?
I have read the whole unity manual and watched the videos on sprites but I have a question. Is there any way of creating primitive 2D shapes in unity? (I will be assigning trigger colliders to these as well). Or does one need to have a 3rd-party program even for basic primitive 2D shapes? My game really is very minimalist.

I did think about using particle system in a clever way but that won't have triggers and may not be as memory efficient for the several basic shapes that I am after.

# Answer
> 5 votes
Yes, the Mesh object used for the MeshFilter and MeshRenderer can be modified to create any kind of 2D shape you like.

You'd do this by generating a 2D mesh of triangles to represent the shape you want. The bonus to using a Mesh object is that you can automatically use that as a collider too. This means that your shapes have easy interaction with operations like click detection and ray casting.

The Unity Manual partially covers how to generate these. I made a video tutorial about it (sorry it's paid). There's also a number of YouTube tutorials of varying quality.

Further, it's completely possible to create a 3D model (that's 2D) in a 3D modeling application and import it into Unity. Again, this will use the Mesh object and you can use the generated mesh as a collision mesh too.

---
Tags: unity
---


# Question
Title: How can I make background elements wrap around the screen?
I'm looking to make my clouds wrap around the screen in my game (like the picture).

Right now it just continues off the screen. The current movement code is:

```
Cloud.center = CGPointMake(Cloud.center.x +0.032, Cloud.center.y)

```

# Answer
> 2 votes
One simple options is to just draw everything twice.

Consider a screenful of your background clouds and other stuff that you want to scroll:

```
+------+
| CC   |
|    RR|
+------+

```

(Assume that `CC` represents a cloud, and maybe `RR` represents a rock or some other background object.)

If you have a "second copy" (logically or physically) of this background data, you can arrange them so they're adjacent:

```
First:  Second:
+------+------+
| CC   | CC   |
|    RR|    RR|
+------+------+

```

You scroll the two tiles of background scenery across the view until one of them falls entirely out of view. At this point, you move (again, logically or physically) the background tile that is entirely off the screen back behind the tile that is currently *entirely* on the screen, and continue scrolling.

---
Tags: animation, ios, movement, xcode
---


# Question
Title: How does an energy-conservative Blinn-Phong-Fresnel model work?
What is a plausible, basic equation/pseudo-code for energy-conservative Blinn-Phong shading, including Fresnel with a coloured light-source?

The net gives so many alternatives that it's hard to figure out which I should use.

# Answer
I'm not very good with English, let's hope that the variable names are clear.

```
float3 half_vector = normalize( eye_dir + light_dir );
float n_dot_l = saturate( dot( normal, light_dir ) );
float n_dot_h = saturate(dot( normal, half_vector );
float h_dot_l = saturate(dot( half_vector, light_dir ));
// Amount of reflected energy based on angle
// usually is [f0 + (1-f0)*pow( 1 - l_dot_h, 5 )]
// f0 is another name for specular colour
// should be very low (< 0.17) and gray for dielectric
// should be high (> 0.7) for metals. 1.0 for crome.
float3 fresnel_term = FSlick( f0, l_dot_h );
// Reflected energy is not diffused, so we remove the fresnel
float3 diffuse_term = (1 - fresnel)*albedo/pi;
// implicit visibility term, can be substitute with SmithGGX for better results.
float visibility_term = 0.25;
float phong_blinn = pow( n_dot_h, specular_power );
// Check http://www.farbrausch.de/~fg/stuff/phong.pdf for reference
float blinn_normalization = ( specular_power + 8.0 ) / (8.0*pi);
float normal_distribution = phong_blinn * blinn_normalization;
float3 specular_term = fresnel_term * visibility_term * normal_distribution;
return light_intensity * (diffuse_term + specular_term) * n_dot_l;

```

Check this http://graphicrants.blogspot.co.uk/2013/08/specular-brdf-reference.html for reference.

Said that most of the game engine use GGX ( https://seblagarde.wordpress.com/2014/11/03/siggraph-2014-moving-frostbite-to-physically-based-rendering/ )
> 2 votes

---
Tags: glsl, lighting, graphics-programming, shading, pbr
---


# Question
Title: What is causing this character overlap during text rendering?
I'm trying to display text with a texture and font description created with BMFont in OpenGL 3.3, but whenever I display the text there is some overlap between certain characters.

Here is the text at normal 1.0x scale:

As you can see, the 'e' in "Hello" overlaps the next 'l' a bit (with the same happening for the 'r' in "world") and the 'w' in "world" overlaps the 'o' quite a bit. Here is a 3.5x scale image to make the overlap a bit more apparent:

I was wondering if someone would be able to explain to me why this is occurring and, if possible, explain how to fix it.

My method for generating the vertex mesh is as follows: (C++)

```
// position control variables
const float tscalex = 1.0f / _font.GetTexture().GetSize().x;
const float tscaley = 1.0f / _font.GetTexture().GetSize().y;
const float hspace  = _font.FindGlyph( ' ' ).XAdvance;
const float vspace  = _font.GetInfo().LineHeight;
float x = 0.0f;
float y = 0.0f;

// generate a quad for each character
char pchar = 0;
for ( uint i = 0; i < _text.length(); ++i )
{
    // apply kerning
    char cchar = _text[ i ];
    x += _font.FindKerning( pchar, cchar );
    pchar = cchar;

    // handle special characters
    switch ( cchar )
    {
        case ' ':
            x += hspace;
            continue;
        case '\t':
            x += hspace * 4;
            continue;
        case '\n':
            y += vspace;
            x = 0.0f;
            continue;
    }

    // get the character's glyph
    const Font::Glyph& glyph = _font.FindGlyph( cchar );

    int width  = glyph.Width;
    int height = glyph.Height;
    int left   = glyph.X;
    int top    = glyph.Y;
    int right  = glyph.X + width;
    int bottom = glyph.Y + height;
    float yy   = y + glyph.YOffset;

    float u1 = float( left   ) * tscalex;
    float u2 = float( right  ) * tscalex;
    float v1 = float( top    ) * tscaley;
    float v2 = float( bottom ) * tscaley;

    // create the quad
    uint16 count = uint16( _mesh.Vertices.Size() );
    _mesh.Vertices.Add( Vertex( Vec3( x,         yy,          0 ) * _scale, Vec3(), Vec2( u1, v1 ) ) );
    _mesh.Vertices.Add( Vertex( Vec3( x,         yy + height, 0 ) * _scale, Vec3(), Vec2( u1, v2 ) ) );
    _mesh.Vertices.Add( Vertex( Vec3( x + width, yy + height, 0 ) * _scale, Vec3(), Vec2( u2, v2 ) ) );
    _mesh.Vertices.Add( Vertex( Vec3( x + width, yy,          0 ) * _scale, Vec3(), Vec2( u2, v1 ) ) );
    _mesh.Indices.Add( count + 0 );
    _mesh.Indices.Add( count + 1 );
    _mesh.Indices.Add( count + 2 );
    _mesh.Indices.Add( count + 2 );
    _mesh.Indices.Add( count + 3 );
    _mesh.Indices.Add( count + 0 );

    // advance
    x += glyph.XAdvance;
}

```

# Answer
> 3 votes
Here is the why comment:

> Per Jason:
> You either haven't enabled alpha blending, haven't loaded the alpha channel, or have set the depth comparison function to GL\_LESS rather than the standard GL\_LESS\_EQUAL.

Here is the "how to fix it" comment:

> Per fastinvsqrt:
> Setting the depth function to `GL_LEQUAL` is what fixed it

---
Tags: opengl
---


title: Change sprite position

text:
# Question
Title: Change sprite position
I have Sprite and i want change my Sprite position when `score == 2`

```
 score = 0;
    auto bird = Sprite::create("bird.png");
        bird->setPosition(Point(-visibleSize.width, -visibleSize.height));
        this->addChild(bird);

if (score == 2)
{
bird->setPosition(Point((visibleSize.width / 2) , visibleSize.height / 2));
}

```

But when my `score == 2` position dosen't change to

```
Point((visibleSize.width / 2) , visibleSize.height / 2));

```

And it still remain at the previous position

what should i do

# Answer
> 0 votes
When in doubt PRINT OUT! ;)

```
cout << "THIS WORKED" << endl;

```

Use print in your if statement to see if your score is being hit. If not I suggest printing the score to see what it is at when you think its 2 or if its being displayed and you know for sure its 2 try

```
if(score >= 2){
    //See if that changes anything. ! :)
}

```

If you use the above if statement, after score is greater than 2 it will always set the position. You can do

```
if(score >= 2 && score < 2.99f){
   //Just for a test.
}

```

Just make sure you know what your score is being incremented by and make sure that the if statement is firing properly. Cheers:)

# Answer
> 0 votes
Adding to the print out suggestion and changing it to a \>= comparator to detect the problem given by Demetry, you should also investigate what's causing the current if statement to fail. My guess would be that you've actually incremented the score variable more than once before you ever even reach the if statement within the given game loop. Make sure that two different objects aren't trying to iterate the score or that you're properly iterating it in the first place.

Similarly, you may want to look into adding event handling into your program using the observer pattern or using a signal/slot api like those made by boost. You could design your program so that, for example, when the score integer iterates you send an event which gives it to the various objects that have registered with it. In this case, you could have a Bird class who receives a value every time the score iterates, and chooses to set its position based on conditions defined within the bird object. This would also enable you to ensure that the function will only be called once, and could even be called if you iterated score multiple times in a single frame.

I can't provide much more advice than that with the given code sample, but I think those will generally help you implement a system which will help make these types of situations much more straight forward in the future.

---
Tags: c++, cocos2d
---


title: How can I do unit testing in Unity?

text:
# Question
Title: How can I do unit testing in Unity?
How to implement Unit Test at Unity3D.

I wonder if it would be possible to extend the Unity editor to have some sort of testing framework in it.

* Is there any guideline to implement it?
* Any reference like book, blog?
* Any working example or project?

# Answer
I use with success NunitLite with the NunitLiteRunner plugin https://bitbucket.org/fddima/nunitlite/src/8a4e3c72f295?at=default

If you can be interested, I also blogged about IoC container that can help you with testing:

http://blog.sebaslab.com/ioc-container-for-unity3d-part-1/

http://blog.sebaslab.com/ioc-container-for-unity3d-part-2/

Edit: while the blog posts are still useful, you don't need nunitlite anymore nowadays. Unit Test Runner is now integrated in Unity. Unity Test Tools also adds more features on top of that: https://www.assetstore.unity3d.com/en/#!/content/13802
> 4 votes

# Answer
Regarding Unit Testing code at Unity3D, follow the resources
> 4 votes

# Answer
There is a free package with test automation tools provided by Unity Technologies in the Asset Store: Unity Test Tools
> 4 votes

---
Tags: unity, unit-testing
---


# Question
Title: How can I adjust my code to make the objects start dropping at a certain speed and then increase that speed over time?
I'm making a game in LibGDX where the player dodges falling objects. At the moment, my code makes each object (in this case 'DROPS') fall at random speeds. I'm wondering if anyone can suggest how to amend this code to make all the objects start falling at the same speed and have this value increase over time. Here is my current code:

```
for (int i = 0; i < amount; i++) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        float y = MathUtils.random(ManicMeltdowns.HEIGHT, ManicMeltdowns.HEIGHT * 3);
        float speed = MathUtils.random(2, 5);
        addEntity(new Drops(new Vector2 (x, y), new Vector2(0, -speed)));
}

```

I assume you have to adjust 'float speed', but I'm not sure how.

Many thanks.

-Edit- Here is the drops class:

```
public class Drops extends Entity{

public Drops(Vector2 pos, Vector2 direction) {
    super(TextureManager.DROPS, pos, direction);

}

@Override
public void update() {
    pos.add(direction);

    if (pos.y <= -TextureManager.DROPS.getHeight()) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        pos.set(x, ManicMeltdowns.HEIGHT);
    }

}

}

```

And here is the entity class:

```
public abstract class Entity {

protected Texture texture;
protected Vector2 pos, direction;

public Entity(Texture texture, Vector2 pos, Vector2 direction) {
    this.texture = texture;
    this.pos = pos;
    this.direction = direction;
}

public abstract void update();

public void render(SpriteBatch sb) {
    sb.draw(texture,  pos.x,  pos.y);
}

public Vector2 getPosition() {
    return pos;
}

public Rectangle getBounds() {
    return new Rectangle(pos.x, pos.y, texture.getWidth(), texture.getHeight());
}

public void setDirection(float x, float y) {
    direction.set(x, y);
    direction.scl(Gdx.graphics.getDeltaTime());
}

}

```

# Answer
> 1 votes
in drops.update:

```
@Override
public void update() {
    pos.add(direction);

    //add the speed difference for the next update
    direction.add(new Vector2(0, -acceleration));

    if (pos.y <= -TextureManager.DROPS.getHeight()) {
        float x = MathUtils.random(0, ManicMeltdowns.WIDTH - TextureManager.DROPS.getWidth());
        pos.set(x, ManicMeltdowns.HEIGHT);
    }

}

```

Then when creating just use a fixed speed.

---
Tags: java, libgdx
---


title: Curved Meters and Gauges

text:
# Question
Title: Curved Meters and Gauges
I'm wondering how people here on GameDev stack exchange would handle curved meter GUI elements for things such as life bars or energy bars.

My thought on the matter was that you could use a shader with a cutoff value and an image which has one channel dedicated to masking the image (alpha) and one that also has a gradient which I compare to a uniform float to determine whether or not the fragment should be fully transparent.

However, I've been running into some strange behavior when writing this shader. Specifically, the shader's output has a weird artifact where the cutoff begins that looks almost like ripped paper -- the line that indicates the end of the meter has a sloppy contour.

This image has some distortion effect going on with the pixels where the lifebar is supposed to end via the cutoff uniform. There's definitely got to be a better way of doing this same thing in a more tactful way. Shader code is below:

```
   CGPROGRAM
   #pragma vertex vert
   #pragma fragment frag

        sampler2D _MainTex;
        float4 _Color;
        float _Cutoff;

        struct Vert_IN {
            float4 loc : POSITION;
            float4 texcoords : TEXCOORD0;
        };

        struct Frag_IN
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };

        Frag_IN vert( Vert_IN input )
        {
            Frag_IN output;
            output.uv = input.texcoords;
            output.pos = mul( UNITY_MATRIX_MVP, input.loc );
            return output;
        }

        float4 frag( Frag_IN input ) : COLOR
        {
            float4 value = _Color;
            float4 valueFromMask = tex2D( _MainTex, input.uv.xy );

            value.w = valueFromMask.w;
            float desiredTransparency = step( valueFromMask.x, _Cutoff );
            value.w = min( value.w, desiredTransparency );

            return value;
        }

        ENDCG

```

(Again, the red channel of this image is actually a gradient mask used to determine where the cutoff point should be. Other channels were going to be used for something else (like special scrolling patterns or what not) )

Example of the asset used in the shader:

I'm assuming there's probably something I'm missing when using the step function that could help ease the fade-dropoff in order to make a better looking end result?

**What do you think is a good method for making curved meter GUI elements? Is there something wrong with the shader code presented above that causes this strange page tearing artifact?**

# Answer
Your graphic tool probably adds dithering (both Gimp and Photoshop does by default) which causes some pixels to be below or above the exact color value or you are using a compressed texture format which causes some pixels to have the wrong color value.

There might be an option in your graphic tool or texture importer to disable dithering or compression.

Here is an example of what happens in Gimp with dithering enabled in the gradient tool. The small section of the gradient has been scaled up and levels boosted using the `Colors->Levels...` tool to clearly show the gradient dithering.

Another option is using smoothstep to add a small gradient to the cutoff point. That would help hiding those errors.
> 4 votes

# Answer
Tearing is caused by the nature of `step` function. It outputs 0 or 1, causing pixel either to be rendered or not. If you try it with `smoothstep` function you will get smeared edge instead.

You can fix tearing artifact by rendering a line on top of the gauge (shown in green). Render the line with the same texture attached, just without the `step(` code - only the blue portion will be visible then.
> 3 votes

---
Tags: shaders, gui, graphic-effects, masking
---


# Question
Title: What are the implications of using multiple OpenGL Contexts on a single thread?
I'm trying to integrate two third-party OpenGL rendering pipelines into the same application, namely Cinder's OpenGL API for 3D drawing and backbuffer rendering, and Google Skia's API for 2D drawing. Unfortunately, Skia tends to trigger a lot of GL state changes in general use, and offers no functionality to reset the GL state. To make matters worse, Cinder (GLNext branch) tries to keep an internal record of all of its GL state changes so that they can be easily 'unwound', but bad things can happen if its internal representation becomes different from the actual GL state.

The easiest way to alleviate these problems was to create a new OpenGL context for use exclusively by Skia, performing context switches only when 2D updates were necessary. However, I've noticed some weird behaviours when I'm required to switch context more frequently, like certain draw calls failing or blend states flickering. Everything I've read about GL contexts indicates that they're meant for use in multiple threads or multiple windows. I've also read about context switches failing in certain circumstances? Is there anything terribly wrong with switching context in a single-threaded, single-windowed application?

# Answer
> 2 votes
From what I understand (there's always room for interpretation and spec-lawyering) of the GL specs there is nothing wrong with switching contexts in a single-threaded single-windowed application.

You have probably hit some driver bugs the manufacturer hasn't tested against.

Try adding `glFlush()` or `glFinish()` before your context switch in theory it shouldn't be needed as the documentation for wglMakeCurrent (https://msdn.microsoft.com/en-us/library/windows/desktop/dd374387%28v=vs.85%29.aspx) says:

> Before switching to the new rendering context, OpenGL flushes any previous rendering context that was current to the calling thread.

And glxMakeCurrent (https://www.opengl.org/sdk/docs/man2/xhtml/glXMakeCurrent.xml) :

> Pending commands to the previous context, if any, are flushed before it is released.

Cinder is open source. I recommend adding your own `InvalidateAllCachedStates()` function that sets all internal states to impossible values forcing all GL states to be updated on the next Cinder draw call or your own `RestoreAllCachedStates()` to restore the GL to what Cinder expects.

Another option would be to record and restore all GL states yourself using a large amount of glGet() calls.

And a 3rd one would be to render the 2D to a FrameBufferObject in a separate thread and context and share the FBO texture(s) between the two contexts. But the task priority switching of what process/thread is using the GPU might cause performance issues on some drivers.

---
Tags: opengl, multithreading
---


# Question
Title: How to render specific FBO Texture attachment (assume attachment1) with 2 attached
1. Create FBO & its textures like normal.

```
// FBO & Texture
glGenFramebuffers(1, &mFbo);
glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
glGenTextures(2, mTexture);

for(int i=0; i<2; i++)
{
    // Init texture
    glBindTexture(GL_TEXTURE_2D, mTexture[i]);
    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, SCREEN_W, SCREEN_H, \
        0, GL_RGBA, GL_UNSIGNED_BYTE, 0 );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glBindTexture( GL_TEXTURE_2D, 0 );

    // attach to FBO
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0+i, GL_TEXTURE_2D, \
        mTexture[i], 0);
}
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glUseProgram(0);

```
2. Bind FBO and render it inside draw loop.

```
// Preparing FBO texture.
glBindFramebuffer(GL_FRAMEBUFFER, mFbo);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

GLuint at0[1] =  {GL_COLOR_ATTACHMENT0};
GLuint at1[1] = {GL_COLOR_ATTACHMENT0+1};

glDrawBuffers(1, at0);
// Filled texture attachment0 less white (transparency = 0.5f)
GUtils::VideoDriver::GetInstance()->DrawFillRect(glm::vec2(0,0), \
        SCREEN_W, SCREEN_H, glm::vec4(glm::vec3(1.0f/(1)), 0.5f));

glDrawBuffers(1, at1);
// Filled texture attachment0+1 white.
GUtils::VideoDriver::GetInstance()->DrawFillRect(glm::vec2(0,0), \
        SCREEN_W, SCREEN_H, glm::vec4(glm::vec3(1.0f/(1)), 1.0f));

glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

After all things I did above:

* texture attachment0 (mTexture\[0\]) will be filled in less white.
* texture attachment1 (mTexture\[1\]) will be filled in white.

**Right?**

I cannot understand when render FBO texture:

```
glBindTexture(GL_TEXTURE_2D, mTexture[index]);
glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0 );
glBindTexture(GL_TEXTURE_2D, 0);

```
1. mTexture\[0\] , screen = **white**. (It must be **less White**)
2. mTexture\[1\] , screen = **black**. (It must be **White**)

Firstly, Did i do a right way to render attached FBO texture or am I misunderstood fbo attachment?

Lastly, How can I fix this?

# Answer
To use **Multiple Render Targets** you need to use pixel shaders to tell the GPU where to send each color values.

```
layout(location = 0) out vec4 my_first_FBO_color_buffer;
layout(location = 1) out vec4 my_second_FBO_color_buffer;

void main() {
   my_first_FBO_color_buffer = vec4(0, 1, 0, 1);
   my_second_FBO_color_buffer = vec4(1, 0, 1, 1);
}

```

See What is the recommended way to output values to FBO targets? (OpenGL 3.3 + GLSL 330)
> 0 votes

---
Tags: textures, rendering, fbo
---


title: Race OOP structure

text:
# Question
Title: Race OOP structure
I am on a point that is totaly making troubles to me. In my "Test Program" I have a Character. This character have some stuffs (hp mp, weapon, attackPoint, armor, ...) but also a Race, that can be 4 coices (Gnome, Elf, Human, Ogre). So I was thinking to make 5classes : Race, Human, Elf, Ogre, Gnome. Thing is I don't know if this is a good idea... I though that Elf, Gnome human and ogre could be inherited from Race... What do you think about it ?

Character.h :

```
class Character
{
public:
   Character(int id);
   void display() const;
private:
   Gnome *gnome;
   Elf *elf;
   Ogre *ogre;
   int m_id;
};

```

Character.cpp :

```
Character::Character(int id) : m_id(id)
{
   if(m_id == 1)
      gnome = new Gnome();
   else if (m_id == 2)
      elf = new Elf();
   else if (m_id == 3)
      ogre = new Ogre();
}

```

# Answer
> 0 votes
This depends on how the race affects the character.

**1)** Do you just want to save the type, e.g. when checking if the user is an Elf to receive bonus damage when wielding an Elvish Blade?

Then you might just go with an enum:

```
enum Race {
  Elf = 0,
  Ogre,
  Gnome,
  Human
};

```

**2)** If you want to include special behaviour and/or properties, you can go with a class system, where Elf is a special class of the abstract base class Race.

```
public class Character {
    private Race race;

    public Character(Race pRace)
    {
       race = pRace;
    }

    public void Walk() {
       race.Walk();
    }
}

public class Elf : Race {
    public override void Walk() {
        ...
    }
}

```

---
Tags: rpg, architecture
---


# Question
Title: switch between player camera/non-camera positioning
Sorry if this sounds ambiguous. But I am writing a traditional top down game. And normally the player would be centered in the middle while moving the orthographic camera. However, I would like this to be dynamic. Therefore, use player.setPosition(x,y) near screen boundaries but center on player if its far from screen boundary.

This is some sample code:

```
public void centerCamOnPlayer() {
         camera.position.set(player.getX() + (player.sprite.getOriginX()),
                             player.getY() + (player.sprite.getOriginY()),
                             0);
}

public void update() {
     boolean shouldCenterOnChar = ???;
     if (shouldCenterOnChar) {
         centerCamOnPlayer();
     } else {
         player.setPosition(x,y);
     }
}

```

Therefore render will call update(). However how do I determine the shouldCenterOnChar? I tried using frustum.pointInFrustum but its only when the sprite moves completely out of screen. I'm sure there is a better way to switch dynamically. Any one has an idea? Tks!

# Answer
> 0 votes
It's probably simpler to set boundaries on the camera set:

```
camera.position.set(clamp(player.getX() + (player.sprite.getOriginX()),
                          minScreenX, maxScreenX),
                    clamp(player.getY() + (player.sprite.getOriginY()),
                          minScreenY, maxScreenY),
                    0);

```

---
Tags: java, 2d, libgdx
---


title: Planar scene graph

text:
# Question
Title: Planar scene graph
Suppose there are many line segments on a plane (2D scene) and I would like to redraw only small portion ("window") of the whole scene. The scene is dynamic, meaning one can add/remove/transform lines. Also, this being about drawing, it matters in what order the lines have to be redrawn (painter's algorithm, z-index). It is also possible to move a line in front of / behind of another line, effectively changing its painting order.

What data structure is suitable for this kind of problem?

I would like both the scene modifications and finding of the affected lines to be as quick as possible. One way to implement such scene graph is to use a simple list of line segments, sorted by z-index and during the redraw iterate through the list and if a segment fits the window, redraw. However, this has linear time complexity, and I would like to know if there is a faster way, preferably logarithmic.

# Answer
> 1 votes
Submitting my earlier comment as an answer:

So you are doing rasterization manually, without the use of a graphics library. If that's the case, you can emulate the depth buffer yourself. In addition to the color buffer, also store a z value in a separate image. Only write to the color buffer if the incoming z-value is less than or equal to the current z-value. If you don't have semi-transparent lines, this is probably the correct way to do it, as it requires no sorting.

If you want semi-transparency (and to some extent, anti-aliasing), you might have to sort the lines manually first.

---
Tags: algorithm, data-structure, scene-graph, space-partitioning
---


title: What is buffer "target" in OpenGL?

text:
# Question
Title: What is buffer "target" in OpenGL?
What is a *target* in OpenGL, actually? For example, in the function

```
void glBindBuffer(enum target, uint bufferName)

```

I know what the function does (more or less), but the target was only a copy/paste enum value from a modern OpenGL tutorial for me so far. Can you explain what it *is*, possibly with an example where it is not just a copy/paste value in object load method?

Should I think of it as a variable of that name with some semantics, in drivers where you can put reference to a buffer (regardless of the buffers previous binding)?

# Answer
The OpenGL specification uses the term "target" all over. It never offers a general definition of that term; consequently the definition of the term in general language is appropriate. A "target" in OpenGL is, as you surmise, simply a destination for something.

Buffers aren't the only thing with associated targets, though. There are targets for query objects, hints, et cetera. In most cases (all I can think of offhand), targets do refer to fixed, named "slots" in the logical pipeline and as such you will always be passing a particular enumeration value to a target parameter when you call into OpenGL.
> 6 votes

# Answer
Yes.

As per the OpenGL 4 docs,

> "When a buffer object is bound to a target, the previous binding for that target is automatically broken."

Each target is a slot which can be associated with one buffer. Each target will influence which buffer is used by specific commands which come after.

(Aside: just now I grepped my own codebase, which does quite a bit of geometry & texture manipulations, and the only use of glBindBuffer it has is `glBindBuffer(GL_ARRAY_BUFFER, x);`)
> 3 votes

---
Tags: opengl
---


# Question
Title: How do I get realistic sliding contact between objects in a voxel grid?
I have a 3D grid of voxels in my game. Entities walk around with simple physics that represents them as an axis aligned bounding box with velocity, mass and acceleration. The way I'm doing collision resolution is fairly simple. Here's some pseudocode:

```
function ResolveCollisions()
    // For each voxel that could intersect the bounding box...
    foreach (Voxel neighbor in VoxelGrid.GetVoxelsIntersecting(this.bounds))
        // Check a collision between the voxel and the bounding box
        if (neighbor.Collides(this.bounds))
            ResolveCollision(neighbor, bounds);

function ResolveCollision(Voxel neighbor, BoundingBox bounds)
     // Compute the contact normal and penetration distance between the two
     // boxes.
     [Vector3 norm, float dist] = ComputeMinPenetration(neighbor, bounds);
     // Snap the position so its no longer colliding
     this.position += norm * dist;
     // Reflect the velocity over the normal to perform an elastic collision.
     this.velocity = this.Restitution * Vector3.Reflect(this.velocity, norm);

```

This works pretty well for instantaneous collisions and bouncing, but fails for *sliding* contact. If an entity is sliding across a flat plane of voxels, for instance, it will rapidly bounce, and will sometimes end up colliding with the *sides* of the voxels instead of the *top*.

How do I get realistic sliding contact between the bounding box and a voxel grid, without bouncing or "toe stubbing?"

# Answer
> 1 votes
The problem with resolving collisions of an entity with voxels in an arbitrary order is that a collision with a voxel edge may be detected before a collision with a face which would have happened earlier.

In this diagram a sphere is sliding along a voxel floor (right to left). Its velocity vector (blue) has a downwards component due to gravity. If collision against voxel A is checked first, the resolution vector (red) will cause the sphere to kick up. This is obviously undesirable because that edge doesn't really exist. If voxel B had been tested and the collision resolved first (green vector) then the erroneous collision with A would never had happened.

So the solution is to check the voxels which share a face with the voxel containing the sphere's center first, then those voxels which share an edge, then those which share just a corner. This ensures that e.g. moving across a flat floor the entity will always be pushed up before it collides with the hidden edges of voxels making up the floor.

If this seems like an arbitrary hack, ask yourself if it is possible for a sphere to collide with the corner or an edge before it collided with a face of a neighboring voxel.

Your pseudocode above should work if you add a step to sort the voxels found in `GetVoxelsIntersecting` by Manhattan distance from the voxel containing the entity's center.

---
Tags: physics, collision-resolution, voxels, bounding-boxes
---


# Question
Title: Position GameObject sprite where I tap on the screen
I can't do one of the simplest things. When the player taps the screen, I want to put my sprite in that place.

```
public class Controller : MonoBehaviour {

    public GameObject ball;  // A GameObject with a SpriteRenderer

    void Start () {

    }

    void Update () {
        if (Input.GetMouseButtonDown(0)) {
            ball.transform.position = Input.mousePosition;
        }
    }

}

```

Well, this doesn't work. When I tap the screen, the sprite appears further up and right. This is how the scene looks:

Where the sprite is by default at (0,0).

Aha, the problem seems quite obvious: if I touch the screen at (0,0) (the bottom-left), the sprite would appear at (0,0) - but as you can see, "(0,0)" is the center of the screen rather than the bottom-left, thus appearing further to the top and right as described above.

The solution seems pretty clear: the position of the sprite should be `Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0)` to make up for this offset! So:

```
ball.transform.position = Input.mousePosition - new Vector3(Screen.width/2, Screen.height/2, 0);

```

... It didn't *quite* work. Look, if I tap on the top-left of my screen, I get this:

If I tap on the bottom-right:

And if I tap on the center, it works correctly. But that's the only scenario.

---

**How can correctly put my sprite wherever I tap on the screen?**

# Answer
Luckily, there's a method for this called `Camera.ScreenToWorldPoint`. You call it from a camera, pass a Vector3 where the `x` and `y` coordinates is the mouse position in pixels and `z` is the distance from the camera in world units. It then returns a world position as a Vector3.

In your example, you'd probably call it something like this:

```
const int DistanceFromCamera = 5;
ball.transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition + DistanceFromCamera * Vector3.forward);

```
> 2 votes

---
Tags: unity
---


# Question
Title: How to get asset/model name from (custom) Content Processor in XNA 4.0
I'm trying to make multiple animations for multiple models in XNA 4.0 and I need to get the name of the model/asset from the content processor which is a custom one (XNA default I think), I'm trying doing this by the split method which requires reading from a file the animations but I need to get the model's name to match it with the files because I'll have several files for several models.

```
public override ModelContent Process(NodeContent input,
                                         ContentProcessorContext context)
    {
        ValidateMesh(input, context, null);

        // Find the skeleton.
        BoneContent skeleton = MeshHelper.FindSkeleton(input);

        if (skeleton == null)
            throw new InvalidContentException("Input skeleton not found.");

        // We don't want to have to worry about different parts of the model being
        // in different local coordinate systems, so let's just bake everything.
        FlattenTransforms(input, skeleton);

        // Read the bind pose and skeleton hierarchy data.
        IList<BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton);

        if (bones.Count > SkinnedEffect.MaxBones)
        {
            throw new InvalidContentException(string.Format(
                "Skeleton has {0} bones, but the maximum supported is {1}.",
                bones.Count, SkinnedEffect.MaxBones));
        }

        List<Matrix> bindPose = new List<Matrix>();
        List<Matrix> inverseBindPose = new List<Matrix>();
        List<int> skeletonHierarchy = new List<int>();

        foreach (BoneContent bone in bones)
        {
            bindPose.Add(bone.Transform);
            inverseBindPose.Add(Matrix.Invert(bone.AbsoluteTransform));
            skeletonHierarchy.Add(bones.IndexOf(bone.Parent as BoneContent));
        }

        // Convert animation data to our runtime format.
        Dictionary<string, AnimationClip> animationClips;
        animationClips = ProcessAnimations(skeleton.Animations, bones);

        //split animations
        animationClips = SplitAnimations(animationClips["Take 001"], @"F:\Education\GP\GP\Animations\defs.txt");

        // Chain to the base ModelProcessor class so it can convert the model data.
        ModelContent model = base.Process(input, context);

        // Store our custom animation data in the Tag property of the model.
        model.Tag = new SkinningData(animationClips, bindPose,
                                     inverseBindPose, skeletonHierarchy);

        return model;
    }

```

I want to replace the "defs" with the model/asset name to make it load the correct animations. Sorry if my question is vague or redundant. Thanks in advance. Is there something wrong with the question ? .\_.!

# Answer
> 0 votes
Finally fixed by naming the parent joint of any model I have by the model's name then I get to read from the file I need by getting the name of the first bone in my mesh and excluding the extra '1' in the end of the string. Now each model will know which file to load for the animations without any fuzz.

# Answer
> 0 votes
I ended up doing something that might seem stupid and costly that I loop at all the files till I find the right one and ignoring the exception that I get if the animations doesn't match the model.

```
foreach (string file in Directory.EnumerateFiles(@"F:\Education\Animations", "*.txt"))
        {
            try
            {
                animationClips = SplitAnimations(animationClips["Take 001"], file);
            }
            catch (Exception e)
            {
                continue;
            }
        }

```

---
Tags: xna, xna-4.0, animation
---


title: OpenGl indices array

text:
# Question
Title: OpenGl indices array
I have a class `terrain` which create a grid of `Quad`s. I do it like this

```
for(int z=0; z<_length;z++){
            for(int x=0; x<_width;x++){
                vertices.push_back(vec3((float)x*250, 0.f, (float)z*250));
    }
}
for(int z=0; z<(_length-1);++z){
    for(int x=0; x<(_width-1);++x){
        int index = z*_width+x;
        Vertex _vertices[] = {
            Vertex(vertices.at(index),vec3(0, 0, 0)),
            Vertex(vertices.at(index+1),vec3(0, 0, 0)),
            Vertex(vertices.at(index+_width),vec3(0, 0, 0)),
            Vertex(vertices.at(index+1+_width),vec3(0,0,0))
        };

        unsigned short indices[]= {index,index + 1,index +
            _width,index + 1,index +  _width,index +  _width + 1};
        Quad quad(_vertices, 4, indices, 6);
        squares.push_back(quad);
        i++;
    }
}

```

The vertices and the logic are correct, but the indices aren't, for some reason. here is the output for this code : But when I change this indices to this :

```
            unsigned short indices[]= {0,1,2,1,2,3};

```

It works great :

The problem is I don't understand why this line

```
        unsigned short indices[]= {index,index + 1,index +
            _width,index + 1,index +  _width,index +  _width + 1};

```

doesn't work. And if it worked, my grid would consume a lot less ressources. If someone could explain me why it doesn't work, It would be great, thanks you. In case you need to know how I draw a Quad, here is the code :

```
class Quad{
public:
    Quad(Vertex *_vertices, int _n, unsigned short * _indices, unsigned short _numIndices){
        for(int i=0; i < _numIndices; i++){
            indices.push_back(_indices[i]);
        }

        for(int i=0; i<_n; i++){
            vec3 v = vec3(_vertices[i].position, _lengthPower);
            position.push_back(v);
        }
        glGenVertexArrays(1, &mVertexArray);
        glBindVertexArray(mVertexArray);

        glGenBuffers(1, &mPositionBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vec3)*position.size(), position.data(), GL_STATIC_DRAW);

        glGenBuffers(1, &mIndicesBuffer);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndicesBuffer);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned short)*indices.size(), indices.data(), GL_STATIC_DRAW);

    }

    void draw(){
        glEnableVertexAttribArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, mPositionBuffer);
        glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndicesBuffer);
        glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, 0);
        glDisableVertexAttribArray(0);

    }
    ~Quad(){

    }
private:

    std::vector<unsigned short> indices;
    std::vector<vec3> position;
    GLuint mVertexArray;
    GLuint mPositionBuffer;
    GLuint mIndicesBuffer;
};

```

I'm using, OpenGL, glm, glfw etc.

# Answer
The call `glDrawElements(..., indices.size(), GL_UNSIGNED_SHORT, 0);` tells your GPU roughly following:

```
for(unsigned short i = 0 /*last parameter*/; i < indices.size(); i += 3 /*3 vertices/triangle*/ )
{
   drawTriangle(VBO[indices[i]], VBO[indices[i + 1]], VBO[indices[i + 2]] );
}

```

Do you see what is wrong now? If the value of `indices[i]` is higher than your size of VBO, it is a problem.
Moreover, for VBO it is recommended to have around 1-4MB of vertices in it - only 4 vertices/VBO will very likely kill your performance. You might be interested in instancing instead.

*big edit reason: cant read right(solved in comments)*
> 1 votes

# Answer
Cause each quad have it's own VBO all the index in the VBO will go from zero to three. But you are sending index from 0 to \_width\*\_height as you were indexing the original array of vertexes (and not the subset you pass in each VBO). Basically you are rendering random memory.
> 1 votes

---
Tags: opengl, terrain
---


title: Player Gravity Questions

text:
# Question
Title: Player Gravity Questions
I've made it so that all entities have complex box colliders for hit detection purposes. These entities also have character controllers on them. The problem? Gravity, or lack thereof. When the character controller is of a certain size, gravity doesn't work. However, if you set it to a bigger size, one way too big to be usable, suddenly gravity works as expected.

I'm looking for one of two things: either a way to make character controllers work, or a way to replace character controllers and everything that they're dictating (movement, as well as gravity.) I've looked into using Rigidbodies, but the character falls to the ground (woo) and flops about on the floor on its back (not such a woo moment.)

I'm open to using Rigidbodies if that's the only alternative, but if you could point me to a good guide on how exactly to use them for players, I would appreciate it.

# Answer
> 1 votes
I'm not sure how you are getting the behavior you are getting with Character Controllers and gravity. **By default, there is no concept of "gravity"** **with a character controller.** This is something that must be implemented through code.

To work with a Character Controller, you should use the CharacterController.SimpleMove or the CharacterController.Move methods of the character controller. A good example of this comes straight from the Unity documentation for CharacterController here:

http://docs.unity3d.com/ScriptReference/CharacterController.Move.html

This will also cover setting up gravity for a CharacterController.

As far as CharacterController versus Rigidbody characters, it really depends on what kind of game you are trying to build. A CharacterController is good for nice tight movement and controls. These are often used in FPS shooter games. RigidBody's for characters are used if you want the physics engine to interact with your character. This is done by applying forces to the character.

There are a few helpful links that will show you when and why you would use a CharacterController versus a RigidBody on a character:

http://answers.unity3d.com/questions/7671/guidelines-for-using-rigidbody-collider-characterc.html

There is also a Youtube video that goes into more depth about this. Search for "Unity 3D - Rigidbody VS CharacterController \[UnityQuickTips\]" on youtube.

---
Tags: unity, collision-detection
---


# Question
Title: Unity 4.6 UI button AddListener sets the same callback to all items in List
I have this method that is looping through a list and sets values on the current item in the list. Everything works fine the lists values are correct exept the AddListener. All listeners on the elements are the exact same as the last element! I have no clue where to go from here. Why is all values working exept the callback? Can anyone explain this to me please. Thanks in advance

```
void PopulateList() {
        foreach (var item in itemList) {
            GameObject newButton = Instantiate(sampleButton) as GameObject;
            SampleButton button = newButton.GetComponent<SampleButton>();
            button.playerLabel.text = item.PlayerName;
            button.opponentLabel.text = item.opponentName;
            //sampleButton.myTurn.SetActive(item.MyTurn);
            button.myTurn = item.MyTurn;
            button.button.onClick.RemoveAllListeners();
            button.button.onClick.AddListener(() => test(item.callbackText)); // item.callbackText is just a a string
            button.playerTurnLabel.text = item.PlayerTurnText;
            newButton.transform.SetParent (contentPanel); // sets parent of button
        }
    }

void test(string whatever) {
        Debug.Log(whatever);
    }

public class SampleButton : MonoBehaviour {

    public Button button;
    public Text playerLabel;
    public Text playerPoints;
    public Text opponentLabel;
    public Text opponentPoints;
    public bool myTurn;
    public Text playerTurnLabel;

}

```

# Answer
Make a temporary reference:

```
Item tempItem = item;
button.button.onClick.AddListener( () => test( tempItem.callbackText ) );

```

For some reason lambdas like this don't work too well when accessing list elements through either index or iterator. It might have to do with how the lambda captures the variable.
> 4 votes

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


# Question
Title: How do OpenGL ES 2 engines typically handle automatic geometry sorting and batching?
I'm trying to write a basic OpenGL ES 2 engine that can automatically sort and batch a fairly flexible set of input draw descriptions.

When I say 'draw description' I mean the actual uniforms, state, the shader, etc required to issue a single draw command for some geometry described by a vertex/index buffer.

When I say 'sort' I mean order a list of draw descriptions so that unnecessary state changes are minimized (ie. sort by surface, then shader, then texture, etc)

When I say 'batch' I'm specifically referring to merging draw calls by merging multiple vertex/index buffers that share the same draw description.

**What I've tried**

It seems like if you can sort a list of draw descriptions, you can batch as well because you can group draw descriptions that compare identical. So I thought I'd create something like:

```
std::map<DrawDesc,std::vector<Geometry>,DrawDescComparator>

```

std::map sorts the DrawDescs and I can stash geometry for identical draw descriptions in std::vector for batching.

However, I'm having trouble creating a draw description object that encapsulates all the required information, and specifically allows it to be compared.

Some things are easy to describe and compare, like a shader which can be assigned a unique id. Other things get complicated; to check if blend state is the same between two draw descriptions I'd have to look at (blend\_enabled, equation\_rgb, src\_rgb, dst\_rgb, equation\_alpha, src\_alpha, dst\_alpha, and blend\_color) in the worst case:

```
bool CompareBlendState(DrawDesc a, DrawDesc b)
{
    if (!a.blend)
        return true;

    if (!b.blend)
        return false;

    if (a.equation_rgb != b.equation_rgb)
        // just use the underlying gl_enums for a consistent comparison
        return a.equation_rgb < b.equation_rgb;

    if (a.src_rgb != b.src_rgb)
        return a.src_rgb < b.src_rgb;

    //...

    if(a.etc != b.etc)
        return a.etc < b.etc;

    return false;
}

```

This is probably probably pretty inefficient. One possible way of making this nicer is storing blend state information in a std::bitset and just comparing the corresponding integer(s)

In general though, I feel like I may be barking up the wrong tree. There's way more state to compare (depth, cull modes, etc) and I don't want to create a difficult-to-maintain mess of code.

I'd like to know how other engines or libraries (unity, ue4, etc) typically handle this problem and if there's a common approach I've missed.

# Answer
> 4 votes
What you're doing may not be the most efficient, but it is still quite efficient, simple, flexible and commonly done. A more efficient, but code-wise more complex and less flexible solution would be to use different draw \`buckets' into which you put your drawables depending on the required state, e.g. you separate opaque from transparent meshes.

With your approach I suggest packing the \`draw description' into an integer. There is also no need for a tuple type (DrawDesc + geometry vector), just pack the geometry id right into that integer as well (what mesh needs to be drawn could be considered part of the DrawDesc, right?).

You should put the most expensive state changes into the higher bits and the least expensive ones into the lower bits. Then you can simply sort your data container using this number (simple "greater than" check, no branches, no structs). So you will get a scheme roughly like this:

```
typedef uint16_t DrawDesc; // may be 32 or 64 bits too)
std::vector<DrawDesc> drawables;

// put whatever info you need into this number, try to save bits.
// here: 5 shader bits (32 shaders), 9 mesh bits (512 meshes)
DrawDesc myDrawable = ((shaderID & 0x1f) << 9) | (meshID & 0x1ff);
drawables.push_back(myDrawable);

// Sort before drawing
std::sort(drawables.begin(), drawables.end());

```

You can now just iterate through the data container and count the consecutive elements that can be batched (and maybe cache the result somewhere).

Sadly std::map is one of the worst data containers the STL has to offer (memory allocations can occur, not as cache friendly as it could be, etc). But with this solution you can avoid a map anyway.

---
Tags: opengl-es2, batching
---


# Question
Title: How to make a stereoscopic 3D Game with SDL for iOS
I was looking up google for an answer the whole night but didn't find anything. Yesterday I found some VR demos and games on the AppStore, with stereoscopig (dual rendered) screens. So you put your phone into a google cardboard and experience a oculus rift like feeling. But how is that possible using C++ and SDL? Thank you very much.

# Answer
> 1 votes
I haven't used SDL or made anything for iOS so I might have missed something, but with that said.

I think your best bet would be to look into OpenGL ES (Embedded System), using OpenGL with SDL can be enabled with SDL\_SetVideoMode.

Normally you would be able to use quadbuffering for stereoscopy in OpenGL, but I don't think the ES allows for that, in that case you need to find details for how to enable it for your device first. A simple method would be to use anaglyph glasses, simply render left and right views and then use fragment shaders to render them both to the viewport with the correct tinting.

For anything else you would have to give more details about what hardware your targeting, hope it helps.

---
Tags: c++, graphics, ios, opengl-es, sdl
---


# Question
Title: Is topology of procedural meshes important?
I've been working on a project which involves generating 3d game models, mostly hard surface ones, procedurally. Do I have to worry about keeping the topology clean? Will topology affect texturing, or have any other consequences on the model that I haven't thought of?

# Answer
A clean topology mostly helps you to skin (add bone transforms) your model without it looking weird, as longer surfaces don't give you many points for the transform to work with. Many small triangles, or thin long ones, would add overhead to drawing the model to some extent and I seem to recall that they might cause some issues with mipmaping (but I can't recall any particular case I've seen it or find any references so I might be wrong about that part).

But if you use marching cubes (or any variation thereof) you would get a decent topology to begin with, and trying to fix the topology before you see any visual artifacts would probably fall under "premature optimization". Unless you're planning on adding bone transforms, then you need to pay attention so you create decent topology around the joints.
> 1 votes

---
Tags: procedural-generation, 3d-meshes, mesh
---


# Question
Title: Java LWJGL - How can I click to interact with objects?
I want to be able to click on a monster to walk to him and start attacking him. The part that doesnt make sense to me is the conversion between the mouse position, and the actual terrain position. There are camera angles to worry about, heights, seperate terrains, how is this done???? I am using Java LWJGL and rendering with OpenGL 4.4

# Answer
> 1 votes
Here's how I convert screen point to a ray in C++, but should be easily converted to Java:

```
void Scene::ScreenPointToRay( int screenX, int screenY, Vec3& outRayOrigin, Vec3& outRayTarget ) const
{
    const float aspect = Screen::Height() / (float)Screen::Width();
    const float halfWidth = (float)(Screen::Width()) * 0.5f;
    const float halfHeight = (float)(Screen::Height()) * 0.5f;
    const float fov = activeCamera->FOV() * (MathUtil::pi / 180.0f);

    // Normalizes screen coordinates and scales them to the FOV.
    const float dx = std::tan( fov * 0.5f ) * (screenX / halfWidth - 1.0f) / aspect;
    const float dy = std::tan( fov * 0.5f ) * (screenY / halfHeight - 1.0f);

    Matrix44 invView;
    Matrix44::Invert( activeCamera->ViewMatrix(), invView );

    const float farp = activeCamera->FarClipPlane();

    outRayOrigin = activeCamera->GetPosition();
    outRayTarget = -Vec3( -dx * farp, dy * farp, farp );

    Matrix44::TransformPoint( outRayTarget, invView, &outRayTarget );
}

```

Then you just test a ray-AABB intersection with your objects' AABBs.

---
Tags: opengl, java, lwjgl, mouse
---


# Question
Title: How can I create a precise touch in Unity
Is there a way so that I can touch an object precisely?

I have these aerial cars and there pretty tiny like 32 by 32 and it's hard to touch them using a raycast. I thought I'd spawn an object with a circle collider on it on the first touch and destroy it after the touch.

# Answer
> 1 votes
A collider probably isn't the best way to solve this issue.

The first thing I'd consider is the size of the cars. It's hard to infer from just the information in the question, but have you considered if the cars are just too small for users to easily manipulate? Raycasts are little imprecise for touches, but if the cars are too small, even with a spherical check you might find that it's not too easy to move them.

If you find that the size of the cars is acceptable, or you can't change the size, you can move on to changing the method you use to detect the touches. Unity has several methods of casting for objects all documented in the `Physics` class.

These include `Physics.SphereCast`, which is similar to `Physics.Raycast`, but allows you to specify a radius for the check in addition to the other parameters.

`Physics.SphereCastAll` is similar to `Physics.SphereCast`, but returns all objects that were hit, not just the first one. This is mirrors the fact that a single touch can overlap multiple objects.

Note that `Physics.Raycast` by default has settings enabled that cause it to return hits on Colliders you set up as Triggers (This can be turned off). The two functions I mentioned above have no such setting, and cannot be configured to hit Triggers. This could be an issue if your current setup requires the cars have Triggers. To get around that you could use `Physics.IgnoreLayerCollision` and `Physics.IgnoreCollision`.

# Answer
> -1 votes
We had the same problem and decided to use third party assets. My advice is to use EasyTouch. It's pretty good.

---
Tags: unity, raycasting
---


title: Are lightmaps also considered textures?

text:
# Question
Title: Are lightmaps also considered textures?
I want my game to support phones with max texture size of 1024 so my texture atlases are 1024. My question is: are lightmaps also considered textures and their max size must be 1024? Or they can have higher dimensions like 4096?

# Answer
Yes, lightmaps are textures. Lightmaps are a record of the lighting value for a surface at a particular point, and the way we represent "surface data for a particular point" in modern 3D graphics is with textures.

Unity's lightmapping implementation uses Beast. The default lightmap atlas size limit is 1024x1024. Terrain, per the documentation, allows you to specify an arbitrary lightmap size. The documentation does not mention a limit, but this thread suggests the limit is 4096x4096.

That thread also notes that you can chance the size of *regular* lightmap atlas textures via scripting, by setting `LightmapEditorSettings.maxAtlasWidth` and `LightmapEditorSettings.maxAtlasHeight` to any value up to 4096.

However, if you are self-imposing a limit of 1024x1024 for your textures you will not want to exceed that in the setting of any lightmap sizes, because that will cause the creation of larger textures.
> 1 votes

---
Tags: unity, textures, performance, texture-atlas, lightmap
---


# Question
Title: Libgdx Box2D and Screen Viewport Scaling
I am currently having problems getting an easy to manage system of scaling my units for use with box2D. Normally I would create virtual units to go along with me viewport and camera but since I am using a screen viewport this is not as easy as it seems. I have tried scaling my viewport by setting the units per pixel to 1/100 which will then scales my world by 100 times. Then I set set my sprite batch projection to be 1/100 as well as my tiles map renderer scale to be 1/100 this led to my box2D elements of size .64 to be 64 pixels large which leads to a good looking simulation as well as a good size. The only problem is then any sprite I use must also be scaled with a scale of 1/100. Also my scene 2d HUD must also be scaled. This works but it is confusing to manage and very time consuming to write out all the scaling etc. I am looking to see if there is a way to use world units where 1 world unit is 100 pixels to make my box2D elements and use screen coordinates for the rest of my drawing etc. Also if there is an easier way to do this that I am not thinking of please let me know. I will try to post code later tonight when I am back at my computer.

EDIT: I created a test project to work on just the scaling factor of my game and here is my test code.

```
@Override
public void create () {
    camera = new OrthographicCamera();
    camera.translate(new Vector3(camera.viewportWidth / 2, camera.viewportHeight / 2, 0));
    vp = new ScreenViewport(camera);
    vp.setUnitsPerPixel(1/100f);

    batch = new SpriteBatch();
    img = new Texture("badlogic.jpg");
    sprite = new Sprite(img);
    sprite.setScale(1/100f);

    world = new World(new Vector2(0, (float) -9.8), true);
    BodyDef bdef = new BodyDef();
    bdef.type = BodyType.DynamicBody;
    bdef.position.set(1, 1);
    body = world.createBody(bdef);
    FixtureDef fdef = new FixtureDef();
    PolygonShape shape = new PolygonShape();
    shape.setAsBox(1, 1);
    fdef.shape = shape;
    body.createFixture(fdef);

    dr = new Box2DDebugRenderer();

    map = new TmxMapLoader().load("Levels/bricksTest.tmx");
    mapRenderer = new OrthogonalTiledMapRenderer(map, 1 / 100f);
}

@Override
public void render () {
    camera.update();
    sprite.setX(body.getPosition().x - sprite.getWidth() / 2);
    sprite.setY(body.getPosition().y - sprite.getHeight() / 2);
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    mapRenderer.setView(camera);
    mapRenderer.render();
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    sprite.draw(batch);
    batch.end();
    world.step(Gdx.graphics.getDeltaTime(), 6, 2);
    dr.render(world, camera.combined);
}

@Override
public void resize(int width, int height) {
    vp.update(width, height, true);
}

```

This code runs and produces the expected results, but I feel there has to be some easier way. Also ignore any of the size numbers/horrible sloppiness of this code because this is only a test project and is not from my actual game.

This is a picture of the final result. Note: The box2D box is not the same size as the image because I wanted the box to be about the size of a character from my game for this test. I also moved the position of the box to x = 5 and y = 5 so it is easier to see.

# Answer
I think the only way to achieve a good result with Box2D is scaling things down. I use two OrthographicCameras for my games, one for HUD stuff and another to Box2D related stuff. Also, I use methods for scaling images and elements down.

Here's an example of what I'm talking about. (It's not a working example. Just illustrating...)

```
private final float SCALE = 10;//WORLD_TO_STAGE_SCALE
private OrthographicCamera camera, hudCamera;
private SpriteBatch batch;
private Sprite background;
private Sprite ball;

private static final int WIDTH = 1280;
private static final int HEIGHT = 720;

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

    //Camera used for Box2D related images
    camera = new OrthographicCamera(scale(WIDTH), scale(HEIGHT));
    camera.position.set(scale(WIDTH)/2, scale(HEIGHT)/2, 0);
    //Camera used for HUD
    hudCamera = new OrthographicCamera(WIDTH, HEIGHT);
    hudCamera.position.set(WIDTH/2, HEIGHT/2, 0);

    //This ball is related to a Box2D body, so I need to scale it
    ball = new Sprite(new Texture(Gdx.files.internal("ball.png")));
    adjustSize(ball);
    //Background is drawn by hudCamera, so no need to change its size
    background = new Sprite(new Texture(Gdx.files.internal("background.png")));
}

@Override
public void render() {
    camera.update();
    hudCamera.update();

    //Drawing Box2D related images
    batch.getProjectionMatrix().set(camera.combined);
    batch.begin();
    ball.draw(batch);
    batch.end();

    //Drawing HUD stuff
    batch.getProjectionMatrix().set(hudCamera.combined);
    batch.begin();
    background.draw(batch);
    batch.end();
}

//methods for making scaling easier
public float scale(float valueToBeScaled) {
    return valueToBeScaled/SCALE;
}

public Image adjustSize(Image imageToBeScaled) {
    imageToBeScaled.setSize(scale(imageToBeScaled.getWidth()), scale(imageToBeScaled.getHeight()));
    return imageToBeScaled;
}

public Sprite adjustSize(Sprite spriteToBeScaled) {
    spriteToBeScaled.setSize(scale(spriteToBeScaled.getWidth()), scale(spriteToBeScaled.getHeight()));
    return spriteToBeScaled;
}

public Button adjustSize(Button buttonToBeScaled) {
    buttonToBeScaled.setSize(scale(buttonToBeScaled.getWidth()), scale(buttonToBeScaled.getHeight()));;
    return buttonToBeScaled;
}

```
> 3 votes

---
Tags: libgdx, box2d, scale
---


# Question
Title: How to handle a Block World like Minecraft
I want to write a simple game with a block world like in Minecraft. My theoretical question is what is the best way to handle this block informations during playing. My first Idea was a huge array but this will cause running out of memory I think. Maybe I have to only load the blocks near the player.

How can I handle the loading of needed block informations from a file and the holding only of needed ones in memory?

# Answer
There are a couple different ways to store the data for a game with blocks like Minecraft.

The way I believe Minecraft does it is breaks the world up in the 16x16x256 Chunks. The chunks around the player are loaded into memory when the player starts the game, then a background thread loads more as you walk around. Here is a video that shows it: http://www.youtube.com/watch?v=oR\_ZdJH9eho.

Another way to do it is to break the world up into an Octree. Michael Goodfellow wrote a blog about implementing a cube world with this data structure: http://www.sea-of-memes.com/LetsCode1/LetsCode1.html. The Octree is nice because it gives you some built in compression, but it will probably be a little harder to work with then an Array.

About keeping the "only needed ones in memory?" This is a little harder since you have to ask what is "needed". If you have NPCs that live in another part of the world with AI that interacts with the environment then you "need" a lot more of the world to be in memory. Voxel world data can get very large very fast, so it is best to try to keep the least possible amount in memory. (IE, only have NPCs near the player).

The graphics engine will "need" every block not completely surrounded by other non-transparent blocks. The usual way to render the world is to build a single mesh that contains the vertices for every visible block. This is much faster to draw since you are only making 1 call to the draw methods for 65,536 blocks (in Minecraft size chunks). Since the graphics engine will need to build this mesh, it generally needs to know all the cubes in a chunk. Note that this is why when you see through the floor in Minecraft, a lot of the world is invisible. This is because every block that is surrounded on all six sides is skipped. I believe Minecraft also reduces the number of vertices by combining horizontal sides of the same kind of texture into one box with the texture repeating.

My advice would be to go with the 16x16x256 chunks. Store them in an Array since you will need fast iteration and editing due to building the mesh and game logic (collision detection, adding/removing blocks, ect). Then load as many chunks in a circle around the player as you can. Scale the number of chunks up or down for better or worse computers.

The loading of Chunks will be a huge hit on performance, so put it in a thread that runs it over time. Make it so you can completely load 3 new Chunks during the time it takes a player to walk from one end of a chunk to the other.
> 8 votes

# Answer
I may not have the best way of explaining it but I will try.

I think the best way to understand how to make it more efficient is to understand Voxels. Minecraft is voxel based, it just uses cubes instead of spheres, etc, etc.

Basically a voxel is a 3D shape that can have a dynamically changed volume and when the volume changes, so does the shape. A Chunk is an X by X by X set of voxels. So for example, you can have a chunk that has 16x16x16 voxels and then you can have X number of chunks. You will have a distance set, that if the player is further than N away from any chunks, don't include them in your calculations. This is kinda similar to clipping distances but would need to apply to each chunk as well. This way, you can have it so that you can always have your player in the center Chunk of a, say, 3x3 set of Chunks.

So what you would have is a class to handle the individual Voxels. We will call it Voxel\_cl. And then you would have a class to handle the chunk of voxels, called Chunk\_cl. And then you would have some world class that generates all the chunks that would generate the voxels, called World\_cl.

So now instead of a huge array of everything, you would have an array of 9 Chunks at any time and in the chunk class, you would have an array of 4096 voxels.

Please note that this is a pretty simple explanation. I am currently working on something using voxels so I figured I would throw in my input =-)

For some more info on voxels, check http://en.wikipedia.org/wiki/Marching\_cubes
> 2 votes

# Answer
You could try to just make visible surfaces render, the computer handles block data in the background, while the renderer only works with what you see. 8x8 chunks would be easier for it to handle.
> 1 votes

---
Tags: c++, voxels, minecraft-modding, data
---


# Question
Title: Difference between Update method and FixedUpdate in Unity?
i am starting to learn Unity3d and one of the confusion i get is difference between `Update()` and `FixedUpdate()`.

I am following Lynda Unity 2D game development tutorial there, the instructor uses `Update` method, the player has RigidBody2D component and Box collider, he uses the `Update` method to translate the player, but when i do same in `Update` the player doesn't move but when i do it in `FixedUpdate`, everything works. He is giving tutorial from Unity 4.3 and i am taking the course in Unity 4.6.

Where should i use `Update` and `FixedUpdate`?

# Answer
> 15 votes
I was going to write this as a comment, but it ended up being rather long winded so I've turned it into an answer.

The current answers are mostly correct, but a few things mentioned are misleading/wrong.

In general, *most* game-play related tasks will go in `Update`.

For example, you don't want to be polling for input in `FixedUpdate` (not because of performance, but because the calls simply won't work correctly). AI falls in the same boat.

*Continuously* updated physics are the *only* gameplay related task that `FixedUpdate` should be used for. *Non-continuous/once-in-a-while* calls to things like `Physics.Raycast`, or even `Rigidbody.AddForce` belong in `Update`. My mention of `Rigidbody.AddForce` is seemingly contrary to what might be implied by the documentation, but the key is Continuous vs Non-continuous.

One huge reason why only continuous physics belong in `FixedUpdate` is the actual nature of `FixedUpdate`. Other answers have mentioned how FixedUpdate is called at a fixed `interval, but that's slightly misleading. In reality, a script is passed a time in Time.deltaTime`/`Time.fixedDeltaTime`* which doesn't correspond directly to the actual time between calls, but rather the *simulated* time between calls.

(\*`Time.deltaTime` and `Time.fixedDeltaTime` are the same value when called in `FixedUpdate` \[Unity is able to tell if the current call to `Time.deltaTime` originated during `FixedUpdate` and returns `Time.fixedDeltaTime`\])

Naturally the same way `Update` can't be called in a constant manner because of varying performance, neither can `FixedUpdate`. The key difference is, each frame, if `FixedUpdate` hasn't been getting called often enough to average out to the correct interval between calls, it gets called multiple times (or isn't called the average is too high). This is what the docs on Execution Order refer to in saying that FixedUpdate can be called multiple times a frame:

> ... FixedUpdate: FixedUpdate is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high...

This doesn't affect Physics because of the nature of the rest of the execution order and the engine, but just about anything else you put in `FixedUpdate` will be affected, and it will cause issues.

For example, if you put AI processing inside `FixedUpdate` there's no reason to assume that the AI won't skip updates for multiple frames in a row. Additionally, each time \`FixedUpdate falls behind, your AI will update multiple times in a single frame before things like physics and player input/movement are processed, which is a waste of processing at the very least, but is also extremely likely to cause hard to track down bugs and erratic behavior.

If you need to do something at a fixed interval use other methods Unity provides such as `Coroutines` and `InvokeRepeating`.

And a small note on `Time.deltaTime` and when to use it:

The easiest way to describe the effect of Time.deltaTime is it changes a number from unit per frame, to unit *per second*. For example, if you have a script with something like `transform.Translate(Vector3.up * 5)` in Update, you're essentially moving the transform at a rate of 5 meters *per frame*. That means if framerate is low the movement is slower, and if framerate is high, the movement is faster.

If you take that same code and change it to `transform.Translate(Vector3.up * 5 * Time.deltaTime)` , the object is being moved at a rate of 5 meters *per second*. That means no matter the framerate, the object will move 5 meters every second (but the slower the framerate, the jumpier the object's movement will appear since it still moves the same amount every X seconds)

In general, you want your movement to be per second. That way no matter what speed the computer is going at, your physics/movement will behave the same way, and you won't have strange bugs popping up on slower devices.

And there's no point in using it in `FixedUpdate`. Because of what I mentioned above, you'll get the same value each call (the Fixed Update Timestep value), and it won't do anything to your values. Movement/Physics defined in `FixedUpdate` is already going to be in units per second so you don't need it.

# Answer
> 4 votes
The `Update` function is called every frame. Its frequency depends on how fast the computer is able to render images. On a slower computer, `Update` is called less frequently than on a faster one. If you do time-based calculations, you can normalise them using `Time.deltaTime` which tells you how long it has been since the last time `Update` has been called (caveats apply).
You will generally use `Update` to perform display-related tasks (e.g. updating a UI element)

The `FixedUpdate` function is called at fixed intervals. No matter how often the image refreshes, `FixedUpdate` will be called `1/Time.fixedDeltaTime` times per second
You will generally use `FixedUpdate` to perform gameplay related tasks (e.g. updating physics)

# Answer
> 2 votes
From: http://unity3d.com/learn/tutorials/modules/beginner/scripting/update-and-fixedupdate

The time-step used in FixedUpdate is not variable.

If your game starts to lag, when it catches up, you don't want \>10seconds of physics in one update, so it is typically done in FixedUpdate which is called on a fixed-interval.

For example:

```
Update(float elapsedSeconds)
{
  Position += Velocity * 34.23423; //Windows Update is self-important
}
FixedUpdate(float elapsedSeconds)
{
  Position += Velocity * 0.0166; //60fps
}

```

Where:

```
Update(34.23423)

==

FixedUpdate(10.0)
FixedUpdate(10.0)
FixedUpdate(10.0)
//4.23423 + 5.76577 game-seconds later...
FixedUpdate(10.0)

```

# Answer
> 2 votes
`Update` is called as fast as possible. The variable 'Time.deltaTime' is set to the actual amount of time that passed since the last call. If lag or something similar slows down the game, `Update` will still be called only once once the lag is over, with a high value of `deltaTime`.

`FixedUpdate` is called at regular intervals. It will never be called more often than the ratio specified in 'Time.fixedDeltaTime'. If lag or something similar slows down the game, `FixedUpdate` will be called multiple times in quick succession to enable the game to catch up. `Time.deltaTime` is set equal to `Time.fixedDeltaTime` before `FixedUpdate` is run, but this is just a fudge to make it easy to migrate code between the two.

Generally, `Update` should be used for interpolable behaviours and `FixedUpdate` for behaviours that must be computed step-by-step, or that depend on those that do, such as physics based movement. If you are writing any kind of loop in `Update` along the lines for `for(time=0;time<=deltaTime;time+=someStep)...` then you should probably be doing it in FixedUpdate instead.

---
Tags: unity, 2d, rigid-body-dynamics
---


# Question
Title: XNA - How to use One Rectangle in sprites for collisions
I'm new to XNA and game development in general. If I want to make an object solid so my character cannot pass through it, I would use several Rectangles to make the collision more "realistic"

What I do is to use the method Intersects() with both;

This are two Rectangles that will be solid. (Highlighted in Red):

And I wonder if there is a way to use one rectangle to achieve something like this:

# Answer
Unfortunately, there is not. By definition, a rectangle has four points, and the new figure has six.

This is something to do with the library, however you could most likely create a wrapper around a few rectangles that has a similar API to the XNA rectangle class. This, I think, is the only way to accomplish something like this excepting @SteveH's solution.
> 0 votes

# Answer
The closest you can do something like this:

```
If(not in red rectangle)
   return;//no collision
else
   if(not in blue rectangle)
       //run collision code

```
> 0 votes

# Answer
Here's another trick that can be helpful:

If you plan to set up a large group of these, you can first test a rectangle that encompasses the component rectangles, then test the interior rectangles individually.

For `P[1]` we check whether it intersects `R[ab]`. Since it doesn't we don't have to check `R[a]` or `R[b]`.

`P[2]` intersects `R[ab]`, so we have to check `R[a]` and `R[b]`.

`P[3]` intersects `R[ab]`, so we check `R[a]` and `R[b]` and find `R[b]` intersects it.

If `R` contained a lot of rectangles, we could save a lot of time by checking the union first.
> 0 votes

---
Tags: xna, collision-detection
---


# Question
Title: How can I draw sprites in layers based on their Y position?
I am trying to figure out the most efficient way to draw sprites in a way that they layer properly based on their Y position.

Lets say I have four objects of the same class named A, B, C, and D, and they all must be drawn. Their respective Y positions are 12, 16, 13, and 17. If I draw A then B then C then D, they will draw and lay over the tops of each other in a weird manner. I want to draw them "largest y is closest." I know you could probably use a sort routine to sort them all based on Y, but I would imagine that would generate a huge amount of lag because of all the calculations, especially when you're needing to draw about fifty or sixty objects.

What's the right way to go about drawing them? How would I modify this to include two different types of objects with similar properties (ie, "creatures" and "projectiles" ?)

# Answer
> 2 votes
Sort them based on their Y position and draw them. You are over-thinking it. Only worry about the performance if you implement it, it appears slow and you discover (via scientific profiling) that the sorting is the bottleneck.

Fifty or sixty objects is pretty trivial, all things considered. It's very possible you could achieve reasonable performance using a *bubble sort* that way, depending on what else is going on (and the sorting algorithms supplied to you in the .NET standard library will be more efficient than bubble sort).

---

There are a few other techniques you can employ, however:

* If you know the objects, or some subset of the objects, will not move much you can also consider storing them in a list that remains sorted (or a regular list where you just insert new objects into the appropriate positions).
* If are rendering in 3D space (despite being a 2D game), you can give each sprite a depth (Z) coordinate equivalent to it's layer order, and rely on depth buffering to cause sprites to be drawn correctly. This avoids the CPU-side sorting, but does involve additional work (if you're not already doing it) to treat all the objects as being in 3D space (such as preparing an orthographic projection).
* Since you're using XNA, if you're using `SpriteBatch`, there's a `Draw` overload that takes a layer value. This layer value can be used to order the sprites accordingly.

# Answer
> -1 votes
I would recomend you to not use this technique, but instead use layers.

In my opinion, layers are the best alternative (of those which I know). Then you would just add each sprite to one of your layers and just loop through each of them with a simple loop, and render the content of each of them.
If that rendering technique doesn't suit you, then you could implement it in any other way, but I strongly recomend you to use layers!

If using layers, you can get rid of the sorting, which will take much performance when the game grows in size. That's why layers was invented, I think.

Good luck!

---
Tags: xna, visual-studio, draw-order, visual-basic
---


title: Unity joystick input acting strange

text:
# Question
Title: Unity joystick input acting strange
After setting up my joystick axes in Unity and sweeping them around I find that the Y-axis jumps to the opposite direction in certain positions.

So, when I press up on the joystick, the input will often indicate that it's pointing down. It will also sometimes do this in the opposite direction. It's somehow tied to the x-axis position, making it especially weird.

# Answer
The default Unity project settings include some joystick axes already. So looking further down, we find the same axis defined again!

Removing the extra axis definitions fixes the problem.
> 2 votes

---
Tags: unity, input, joystick
---


title: First Person Camera Target

text:
# Question
Title: First Person Camera Target
I have a camera at position P, and a normalized direction vector D (where the camera is facing). I want the target of the camera to be 5 units forward from the position. Here's my attempt:

```
F = (0, 0, 5) // forward
target = P + (D * F)

```

The obvious problem is that `D * F` can eventually reach (0, 0, 0), which would cause the target to be equal to the initial position. I feel like I'm missing something even more obvious than the problem here but, how would I properly have the target be 5 units forward?

# Answer
I was missing something incredibly obvious that makes me feel ashamed to have posted this question. All that needed to be done was to set `F = (1, 1, 5)` instead of zeroing out the coordinates I didn't need. It's like I forgot how to multiply.
> 0 votes

---
Tags: opengl, c++, camera
---