title: Voxel engine artifacts

text:
# Question
Title: Voxel engine artifacts
There are white little dots between blocks at random places, mainly at very near blocks. They disappear when I move the mouse and change the view direction.

I use Vertex Arrays with `glVertexAttributePointer` to send the data directly to the shader. The shader only adds some fake light based on the face direction and draws the pixels.

What could be the reason for the small white artifacts?

Chunk render code:

```
public void renderChunk() {
    glPushMatrix();

    glTranslatef(pos.x*world.chunkSize.x, 0.0f, pos.z*world.chunkSize.z);

    glBindBuffer(GL_ARRAY_BUFFER, vao_id);

    glVertexAttribPointer(world.game.positionAtt, 3, GL_FLOAT, false, 32, 0);
    glVertexAttribPointer(world.game.normalAtt, 3, GL_FLOAT, false, 32, 12);
    glVertexAttribPointer(world.game.texCoordAtt, 2, GL_FLOAT, false, 32, 24);

    glDrawArrays(GL_TRIANGLES, 0, arraySize / 8);

    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glPopMatrix();
}

```

Vertex Shader:

```
attribute vec3 in_position;
attribute vec3 in_normal;
attribute vec3 in_texcoord;
varying vec2 texture_coordinate;
varying vec3 normal;

void main()
{
    gl_Position = gl_ModelViewProjectionMatrix * vec4(in_position, 1.0);
    normal = in_normal;
    texture_coordinate = in_texcoord;
}

```

Fragment Shader:

```
varying vec2 texture_coordinate;
varying vec3 normal;
uniform sampler2D texture;

void main()
{
    float add;

    if (normal.x == 1.0 || normal.z == 1.0) {
        add = 0.65;
    } else if (normal.y != 1.0) {
        add = 0.8;
    } else {
     add = 1.0;
     }
         gl_FragColor = texture2D(texture, texture_coordinate) * add;
     }

```

Enlarge the image by click it to notice the artifacts.

# Answer
I had the same problem with a recent game I'm working on. I guess you are using one big texture with all the block textures in it (like Minecraft does it)?

If so these white pixels appear because of rounding errors in the shader that lead to "empty" texture spots. This occurs even if you do not use texture interpolation (which is the case with your game obviously).

You can circumvent the problem by modifying the texture coordinates to add a little margin. This way the rounding error won't lead to a lookup outside the texture. This may not be the best solution but when it comes to float values you always have to take care of possible rounding problems.

Another way to fix that would be to use one of the more recent GLSL versions that offer a integer based texture lookup method.
> 6 votes

# Answer
If you build your meshes more carefully, ensuring you are reusing vertices wherever possible, you should be fine: That is, you must not duplicate vertices per face as then the GPU rasteriser will see them as two discrete objects and sometimes fail to rasterise the in-between space (thus defaulting to the GL's clear colour) due to floating point limitations; whereas had you *shared* the vertices between these same two faces, the rasteriser would have seen each fragment as either belonging to one face *or* to the other, but *never* to the space behind them (sky).

Polar rightly notes that Minecraft has these artifacts too. They are only noticeable when you are above a certain depth (y), because the sky(box) colour changes to grey/black once you hit the Deeps, so you won't notice fragments of blue sky shining through. That's one reason they're not as evident as they are in your engine.

The greater reason why your artifacts are more evident than Minecraft's is because the latter constructs RLE-based columnar meshes; that is, the stack of voxels (in y) at every (x,z) location is a single mesh rather than a mesh per block or per face (as you seem to have!), with the texture presumably procedurally generated for the the correct columnar sequence of voxel types. So in MC you won't experience noticeable sky pixels on the ground surface, or on the edges of columns, or vertically between cells; only between columns, and thus much less frequently than in your case, where you seem to have seams all over the place, including on cubes' upper edges.

(P.S. This should also greatly reduce your upload bandwidth and potentially number of draw calls.)
> 6 votes

# Answer
If you look closely at the dots, you'll see that they're all on the cube edges. The *most likely* explanation for this is that when you calculate the voxels positions in the viewport (screen), the rendering algorithm isn't seamless - that is, when they are converted from 3D to 2D, there are areas in the 2D which are never mapped to by the 3D world. If you're drawing the edges with a line, which is again quite likely, the line algorithm may miss out the odd pixel.

On the subject of Minecraft (see my comment about graphics and copyright on your post), Minecraft itself has these glitches from time to time - they aren't entirely unexpected. On the other hand, they can be quite annoying - I don't personally know a solution to this off the top of my head; if you really need to remove them, then you'll have to experiment, or ask someone else. Personally though, I wouldn't notice them if the game was any good - I'd be too absorbed in it to see such tiny graphical glitches.
> 3 votes

---
Tags: opengl, glsl, lwjgl, voxels
---


# Question
Title: Can't move bone on blender. "Location" transform grayed out
I'm trying to move a bone on Blender. I can't do anything with it at all. I've searched through the menus and noticed the Location transform is grayed out.

# Answer
> 3 votes
This is because the bone is connected to its parent, which is normal.

1. Change to Edit mode
2. Make sure the same bone is selected
3. Under Relations as in your screenshot, uncheck Connected
4. Go back to Pose mode

Now you can give the bone an absolute location.

EDIT: If you expect to move a bone and have the connected parent bones follow, you could use IK (Inverse Kinematics). You can easily add this as a modifier on the bone.

---
Tags: blender
---


title: 3D turret tracking in XNA 4.0

text:
# Question
Title: 3D turret tracking in XNA 4.0
I've beeen going through Reimer's flightsim tutorial and wanted to expand it by adding anti air turrets shooting at the ship. Im still new to programming in c# and xna and also a bit horrible in maths :P. How would I go about calculating how the turret would track the ship which is moving in 3 axes? Looking through the tutorial I assume I'll be using a quaternion and using lerp to try and smooth the tracking movement?

My model is just a simple hovering ball with a gun so theres no animation or bones to worry about.

# Answer
> 0 votes
Quaternion is the right keyword! Look at this question which deals with the same problem.

Basicly your objects have a position and an orientation. To point the turret at the ship you need to find the vector pointing from turret to ship. Then you can manipulate the turret to point at the ship and start you shoot logic / animation.

# Answer
> 0 votes
You could use a "LookAt" view matrix for the World transform of the turret.

See Matrix.CreateLookAt

This method requires you to figure out the Up vector though. The cross product of two perpendicular vectors will give you the third perpendicular vector in the direction of the handedness of the system.

```
///  position = my position, lookat = the position of the object I want to look at
public static Matrix LookAt(Vector3 position, Vector3 lookat)
{
    Matrix rotation = new Matrix();

    rotation.Forward = Vector3.Normalize(lookat - position);
    rotation.Right = Vector3.Normalize(Vector3.Cross(rotation.Forward, Vector3.Up));
    rotation.Up = Vector3.Normalize(Vector3.Cross(rotation.Right, rotation.Forward));

    return rotation;
}

```

---
Tags: xna, 3d
---


title: Swapping limbs between meshes

text:
# Question
Title: Swapping limbs between meshes
I'm trying to achieve what was done in the game impossible creatures. I will have a skeleton to which I will apply different meshes to i.e. torso mesh, leg mesh, etc. I would also like these meshes to be skinned together at the joints so that it looks like an animal and not like a robot.

Any ideas as to how I go about achieving this?

# Answer
> 1 votes
One way would be to separate all the pices into diffrent meshbuffers, but with the same skin.

so what you realy do is to pick all the limbs you want, and combine them into one vertex buffer and draw that one when needed. so you dynamicly generates this buffer at command from the user.

So it´s basicly a big merger but with diffrent limb options. and if you store your vertexlayout smart you dont need to bother about how you store your vertexes.

ETC - For every vertex save Position, bones, texture ID.

Then you can just push on whatever to build your vertex buffer. and dynamicly set the textures for specific vertexes. and bones aswell. and it will be pretty fast aswell if you combine all this into one drawcall.

---
Tags: 3d-meshes, skinning
---


# Question
Title: World space and model space the dummies version
I'm by no means a 3d programmer but have recently taken it upon myself to build a Voxel based game and I'm having a little trouble understanding some of the concepts around matrices (what with my limited knowledge of mathematics en all).

So here's my situation ... (assume I've declared other stuff but omitted for simplicity)

I have my camera class in to which I have declared the 3 basic matrices (I think something's wrong here for a start)

```
class Camera
{
    public Matrix World { get; set; }
    public Matrix View  { get; set; }
    public Matrix Proj  { get; set; }
}

```

Now I have a few other bits like a BaseModel class, a chunk class and a block class that gives me all the core bits i need for a voxel based modelling system ...

```
abstract class BaseModel
{
    public Chunk[] { get; }
}

class Chunk
{
    Block[,,] Blocks { get;set; }
}

class Block
{
    public Bool IsActive { get;set; }
    public int Type { get;set; }
}

class TerrainModel : BaseModel
{
   ... terrain specific stuff ...
}

class PlayerModel : BaseModel
{
    ... Player specific stuff ...
}

```

This is all good and works well.

So i can do something like (obviously i'm not doing this in my draw method):

```
TerrainModel terrain = new TerrainModel(heightMap);
terrain.Draw();

```

In my draw Method I have something like ...

```
if (updated)
            {
                // Load the vertex data in to the buffer
                buffer.SetData(Vertices);
                updated = false;
            }

            // Send the vertex buffer to the device
            GameEngine.GraphicsDevice.SetVertexBuffer(buffer);

            cubeEffect.World = GameEngine.Camera.World;
            cubeEffect.View = GameEngine.Camera.View;
            cubeEffect.Projection = GameEngine.Camera.Projection;

            cubeEffect.TextureEnabled = true;
            cubeEffect.Texture = cubeTexture;

            foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                GameEngine.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, Vertices.Length / 3);
            }

```

Now here's where I get lost: Assuming when I setup my camera I have done this ...

camera.World = Matrix.CreateTranslation(0,0,0);

... from the cameras point of view the world is based on points starting at that location which should be correct I think.

Now assuming I want to render my terrain model at a different location do I create a new world matrix that represents the translation between the terrain model and the world that my game lives in?

This seems like the logically thing to do and everything I read suggests that maybe the "world matrix" is not a single object but represents the translation from model to world rather than that of all world space like I had previously thought.

When I do this ... (assume i'm only rendering this model for now, I know this has other issues)

```
camera.World = Matrix.CreateTranslation(10,0,10);

```

... all is good and everything renders the extra 10 pixels on the x and z axis. The bit I can't seem to figure out is how to move only (for example) my player model taking this approach because when I do this ...

Matrix playerWorld = Matrix.CreateTranslation(PlayerModel.Position);

... I would expect a translation from player model space to world space for each of the verts in question however instead the player object seems to disappear going to who knows where (trust me I looked).

The odd thing being that my camera class is a Third Person Camera and follows the PlayerModel around, pushing the keys I can move the camera but the playerModel stays still.

Have I missed something fundamental about Matrix calculations?

EDIT:

Ok something very odd ... If I tell all models (via the base class) to generate a World matrix and use that in their rendering it all starts working !! ... how peculiar?

That raises the question ... Is world space something that is considered "relative" to each model in the scene and their location in relation to the camera?

I've solved my problem but matrices still remain a scary mystery to me :)

# Answer
It looks like your attempting a voxel based terrain game built using cubes. Forgive me if I'm wrong, but if so, you are welcome to look at TechCraft, which I coded a few years ago:

http://techcraft.codeplex.com

The simplest form of single threaded xna/c# based code in that project, that demonstrates procedural terrain is found here:

http://techcraft.codeplex.com/SourceControl/changeset/2acaf7e56694 (set the NewTake project as startup)

Incidentally, the project also includes a voxel terrain that is pregenerated, in the TechCraft project.

I hope it helps in you learning about cube based voxel terrain in XNA. It uses matrices, so the code has examples of how to use them also in what you are attempting. Good luck!
> 1 votes

# Answer
In any 3D application there are four main coordinate spaces:

1. **Model Space**: Also known as "Object Space". This is the coordinate system local to any object in your game. If I had a character, then his model space would not change regardless of where the character was or what direction they're facing. The best way to think about model space is "The character always knows what is three units in front of him"
2. **World Space**: The world space is the relative location of all objects in the world. When a character moves, his position in world space changes (unlike his position in model space). Usually when you need to deal with physics or other game logic, world space coordinates will be the best way to determine relationships between your objects.
3. **View Space**: Also known as "Camera Space" or "Eye Space". This is the coordinate system *relative to the camera*. In this space, the camera is at the position (0, 0, 0), and the direction of the camera is the z-axis of the coordinate system. This is the space in which culling takes place. (For example, we don't need to render anything with a negative Z value, since it would be behind the camera).
4. **Screen Space**: This is the (X, Y) coordinate system of whatever screen you're displaying your graphics on. Your mouse coordinates, for example, are given in this space.

Now, in computer graphics, the transformation from one space to another is encoded using a matrix. So when rendering your full scene, what developers generally do is store:

* A single matrix for each different object in the scene. This corresponds to that object's transformation from **Model** space into **World** space.
* One overall matrix for your view. This corresponds to the transformation from **World** space to **View** space. Note that you only need one of these, since it's assumed that everything will be in world space before being transformed into view space.
* Finally, another overall matrix known as the *Projection Matrix* is saved in order to transform objects from **View** Space into a space that's ready for mapping into **Screen** Space. This matrix is usually combined with the *View Matrix* mentioned above.

Now that we have a good understanding of how matrices work, for your problem, you will need to compute a separate **Model** Space matrix for each block that you want to render. This is usually done "on-the-fly" from the block's position and orientation. Alternatively, you could specify a single **Model** Space matrix for the entire terrain, but then each block's vertices would have to be specified relative to each other (in "terrain" space).
> 4 votes

---
Tags: xna, xna-4.0, matrix, spaces
---


# Question
Title: 2D games on Unity and collision detection performance
I'm developing a 2D game for the iOS platform. I have seen a lot of packages on asset store that makes 2D asset creation for unity easier.

I have narrowed my selection to just 2, 2d toolkit and ex2d. I have to test them and see with fits my workflow better (if anyone has an useful opinion I'm all ears). But my main concern is how to do the collision detection in unity for this kind of games.

My game is a side scroller and I want it to have slopes. I have done this in my own engines using tile height maps, etc... but unity doesn't support all this, but it has a physic engine. Do you think unity own physics engine will be ok for a game like this? I really need a good control on player collision to achieve a nice playability, so, I'm a bit sceptic if I will be able to do it using the physic engine, perhaps, because of my poor knowledge on this subject.

I have thought about rolling my own 2D cuad collider and do my own collision detection on the fixed update call but not sure either if it will be faster that the built-in physics engine because unity3d could be just optimised to use its own collision system.

What do you think?

# Answer
You should be able have you character go up slopes without a 3rd party tool.

You can attach the character controller(download it off the asset store, its free) and then you can change the angle that the character is allowed to move over (I have my player able to climb up to a 50' angle, be sure the re-angle the character though).

The 2D Toolkit is great as you can create your own collision meshes over sprites, and batch all the images together, increasing performance.
> 5 votes

# Answer
You might want to check Orthello. It's a pretty simple and straightforward 2D framework for Unity.

Orthello has 3 events for handling collisions.

1. OnCollision (Start)
2. OnStay (If after the first collision it keeps colliding)
3. OnExit (It's not colliding anymore)

I'm pretty sure you have to bypass Unity's physics engine to handle 2D collisions.

You can find more info about Orthello at: http://www.wyrmtale.com/orthello
> 1 votes

# Answer
You might want to check out "2D ColliderGen" for Unity too, you can then automatically generate MeshColliders for your game objects from a sprite image’s alpha-channel at a button-click. Automatically integrates with Orthello, 2D Toolkit and SmoothMoves. Easy to use and still tweakable.
> 0 votes

---
Tags: collision-detection, unity, physics, physics-engine
---


# Question
Title: GLES2 rendering performance for different iPad generations
I'm using C++/GLES2 for iPad only (no iPhone). The only device I own is an iPad2 and I do not plan to support iPad 1.

Can anyone help me understand realistic goals/limits on iPad 2/3/4 in terms of polygon count, etc?

# Answer
> 1 votes
There are a billion different things that can impact performance in your app. It's silly to ask "what can I expect from the performance" of an architecture, since generally people aren't going to be able to say anything more than a repeat of the spec sheet. What you're going to need to do is write whatever game you plan on writing, profile, and then fix bottlenecks.

That being said, from the small amount of iPad programming that I've done, the most expensive things to look out for are translucent (not transparent) alpha blending and fill-rate. In other words... try to avoid writing any single pixel more than once.

---
Tags: 3d, ios, rendering, performance, opengl-es2
---


# Question
Title: Why do most games save the players team as a short int in the player class and not as a pointer to a team object?
Why do most games save the players team as a `short int` in the player class and not as a pointer to a team object. As far as I know both methods have their advantages.

**Short method:**

* Saving it as a short is smaller;
* Syncing players will be faster because of the first point.
* Syncing players will be easier because the memory location can be different on another PC.

**Pointer method:**

* You could for example save a team name. That way you don’t need to look it up every time you need it;
* It’s more OOP.

I saw a lot of engines saving the team as a `short int`. What are the reasons that they save the players team as a short and not as a pointer?

# Answer
The most common reason is, there simply is no Team object, a int or enum will suffice.

But your assertions are slightly flawed. So let my iterate on them and finally tell you why an int is also a good idea even with a Team object.

First, yes a short *may* be smaller than a pointer. True on a PC, but it is nowhere guaranteed. (Yes, this is sort of academic.) I doubt that saving or sending 16 bits or 64 bits makes such a difference really and you do not want to send the pointer's address anyway. If you have an IP network to sync over, the network's structure will certainly determine how fast you can sync the player state.

As noted above, you never want to send the address of a pointer over a network or save into a file. You need a way to represent this information in a stable way, thus you give each team and id (int) and store/send this. The receiving/reading end then looks up the team from that id.

At this point you can put a pointer to the Team into the Player object. It has no or little effect to storing or syncing objects.

There **may** be a reason why you still don't want to refer to other game objects by pointer, *but this depends on your engine design*. For example you may have some delayed message mechanic. So you send a message to the object (maybe even to itself) to be delivered later, but in the meantime the object is deleted. By using a unique int it is possible to safely handle the message, the lookup fails and the message can be silently ignored. If it was a hardcoded pointer it would have crashed. You see this type of safety or weak references can often be found in code. (Google "Handle" for more info.)

And on a closing note, *"It's more OOP"*. We are software engineers and not software zealots, thus we don't adhere to dogma. Any design discussion must based on real principles that have a well defined gain. Any person that says this is the right way to do it should get their brains unwashed. It don't want to say that OOP is bad, no it is great, but "this is the right way to do OOP" is a non starter.
> 5 votes

# Answer
Are we talking about short int? If so, the main advantage is data serialization. Int is a POD (plain old data). It's way easier to save and load an ID (short int in this case) rather than recreating the OOP pointer to class.

Btw : Speed is negligible in this case
> 2 votes

---
Tags: software-engineering
---


title: XNA 2D Particle in 3D world

text:
# Question
Title: XNA 2D Particle in 3D world
Is it possible to make 2D-sprite particles in a 3D world that always face towards the camera?

# Answer
> 0 votes
This is possible using sprite billboards, as demonstrated in this tutorial.

---
Tags: xna, 2d, 3d
---


# Question
Title: independent lighting per mesh in blender
In Blender, is it possible to assign lighting objects/effects exclusively to a single mesh? For instance, if I place two meshes next to each other, and two lights (one shining on each mesh), I would want each mesh to **not** cast a cast any shadow on the other.

For example, in the following rendered image from a "test" star system view:

The rings are casting shadows on the right-most planets. I want the rings to **only** cast shadows on their own planet.

Is this possible?

# Answer
It has been a long time since I tried this. but basically in blender lighting is only applied on one given layer. So to get lighting for individual objects, you need to put each on it's own layer with one light.

P.S I first thought about "not casting shadows", but that probably won't work, since you may want self shadowing. (-\> rings)
> 1 votes

---
Tags: blender, lighting
---


title: Smoothing a shot power curve

text:
# Question
Title: Smoothing a shot power curve
I'm making a game with shot powers (user presses and holds and launches an object)

Distance from the cursor was working for testing but obviously a distance of 1 and 2 pixels is **double**. I scaled this by 4 to make the difference itself less drastic but they're double of each other.

Is there a common way to smooth the strength of a shot so it's not so great per jump?

# Answer
I would suggest trying a logarithmic scale. This is probably best as a power factor. As they drag further away, the power will increase at a slower rate.

For example:

```
var maxPower = 300;
var scale = 4;
var distance = (the number of pixels they dragged...);

var power = maxPower * log( distance / scale );

```
> 2 votes

# Answer
Easy answer: start from say 10, so your power function goes like 10, 11, 12 ...

Advanced answer: linear functions aren't so great for things like powers, where you're interested in the relative difference between powers. For example, power 100 should be noticeably different to power 99, even though the linear difference is just 1%, barely noticeable. Instead you should start with something like a geometric series, which means a function where every step is a constant factor up or down. You see this crop up in a lot of places, such as exp required for next level up, the amplitude from volume knobs, chance-to-hit formulas etc.
> 0 votes

---
Tags: javascript
---


# Question
Title: Mario like jumping and landing in box2d, help
I've been trying to get Mario type jumping/landing in a Box2d game and it's been giving me some trouble.

Results: Player loses velocity on landing

Desired Results: When player lands it will continue at the same velocity it was in the air.

\[edit\] Player loses velocity on impact, but quickly regains its set max speed.

I know this is an issue with friction and I've tried setting the friction to 0 when the user is pressing Left and Right movement keys and back to normal friction when the player is not pressing those keys. This however, does not work as the state does not get changed until the collision is over and the player will be stuck sliding until the collision state has changed.

My next best guess is to set friction to zero all together for the player and simulating an opposing force on the player.

Solution? Tips? Heck... maybe there's a tutorial out there I missed.

Thanks in advance.

Example http://www.guioui.com/saxattack/box2d\_landing.png

```
        Vector2 a = entityBody.getLinearVelocity();
        float force = 0;

        if(Gdx.input.isKeyPressed(Keys.D)){
            if(a.x < 5) force = 25;
            //entityBody.getFixtureList().get(0).setFriction(0);
            //floor.entityBody.getFixtureList().get(0).setFriction(0);
            //entityBody.resetMassData();

            //entityBody.applyLinearImpulse(new Vector2(0f,1f), entityBody.getWorldCenter());
            //entityBody.applyForce(new Vector2(0f,50f), entityBody.getWorldCenter());
        }
        else if(Gdx.input.isKeyPressed(Keys.A)){
            if(a.x > -5) force = -25;
            //entityBody.getFixtureList().get(0).setFriction(0);
            //floor.entityBody.getFixtureList().get(0).setFriction(0);
            //entityBody.resetMassData();

            //entityBody.applyForce(new Vector2(0f,50f), entityBody.getWorldCenter());
        }
        else{
            entityBody.getFixtureList().get(0).setFriction(.4f);
            floor.entityBody.getFixtureList().get(0).setFriction(.4f);
        }

        if(Gdx.input.isKeyPressed(Keys.W)){
            a.y = 5;
            entityBody.setLinearVelocity(a);
        }

        entityBody.applyForce(new Vector2(force, 0), entityBody.getWorldCenter());

```

# Answer
> 1 votes
I would only use the physics input for what should react to the physics. As long as you can keep track of solid surfaces and your character or take advantage of events, I would write your own code to handle player actions, instead of trying to use Box2D to make it happen.

It will probably be more worth your time creating your own code than to tinker with Box2D to get working.

---
Tags: 2d, box2d, libgdx, side-scroller, jumping
---


# Question
Title: Why (SDL) animated filled-circle leaves trail of movement?
I'm trying to achieve proper animation using SDL. Used flags are SDL\_HWSURFACE and SDL\_DOUBLEBUF.

That what I'm getting is technically smooth (I think), but I can figure out what should I do to remove that trail? My animation is time-based (I'm calculating displacement with delta time).

Link to to video: https://vimeo.com/62065078

my (every-frame) drawing function is like:

```
for(int x = 0; x < screen->w; ++x)
    for(int y = 0; y < screen->h; ++y)
        draw_pixel(screen, x, y, 136, 136, 136);

```

and ball:

```
filledCircleColor(screen, ball.x, ball.y, 17, 0x000000ff);

```

and finally:

```
SDL_Flip(screen);

```

main loop is:

```
for(;;) {
    curr_ts = stopwatch_seconds_elapsed(sw);
    d_time = curr_ts - prev_ts;
    prev_ts = curr_ts;
    cpSpaceStep(space, d_time);
    draw_scene(screen);
}

```

# Answer
> 2 votes
It looks like what you're seeing is a persistence of vision effect. Your circle isn't really leaving a trail, but it looks like it is because it has a very hard edge. If you use a less contrasting image, or just squint, you will probably see that your image doesn't have the trail.

If you want to fix the app so it doesn't look like it has a trail, your best bet is to ensure you are getting a high framerate, or add a bit of fake motion blur so it counters the jagging effect created by your eyes trying to track the object.

---
Tags: animation, sdl
---


title: Will this Entity Code work?

text:
# Question
Title: Will this Entity Code work?
How do you create 2D entities?

Here is something i tried to write up as a base for entities but is this usable and is entites like this?:

```
 public abstract class Entity {
        int attackRange; // out of 100
        int speed; // 1-slow(walk), 2 jog, 3 sprint
        int defense; // out of 100
        int attack; // out of 100
        int health; // out of 100
        int mana; // out of 100

        public abstract void render();

            public void entityBoundaries(){
               Rectangle head = new Rectangle(0,0,25,25);
               Rectangle chest = new Rectangle(0,0,25,25);
               Rectangle arms = new Rectangle(0,0,25,25);
               Rectangle legs= new Rectangle(0,0,25,25);
            }
    }

```

This is my sample class (an archer) that I have made:

```
public class Archer extends Entity {
    public Archer() {
        attackRange = setAttackRange();
        speed = 2;
        attack = 75;
        defense = 35;
        health = 100;
        mana = 50;
    }

    public int setAttackRange() {
        return 5;
    }

    @Override
    public void render() {

    }

    public void trackHealth() {
        System.out.println(health);//for now just out put in console, later
    }

    public void entityBoundaries() {
          Rectangle bow = new Rectangle(0,0,25,25);
          Rectangle arrow = new Rectangle(0,0,25,25);
    }
}

```

Can the class contain boundaries and how would you check them in the main game class?

```
Rectangle sampleObject = new Rectangle(0,0,100,100);

```

As an additional issue, I am not clear with how lists work with Java but i was thinking that adding the boundaries to it would be good and then i just cycle through them.

# Answer
> 0 votes
First of all, I'd ask on Stack Overflow (or get a book) about how to use lists in Java. It really is a fundamental skill, and if you can't use lists, you might want to take a crash course in Java first. Then again, learning by experience is good - it just helps to know what you're doing.

About whether there is a more efficient way to write a player class, the answer is *probably* \- but I can't think of a way off the top of my head, and to be honest your method is the method that I would use. Using abstract classes / inheritance really ends up paying off (providing that you avoid multiple inheritance, which is a PITA - see the diamond problem), so you've made a good decision there.

Next, you need to create a list with the boundaries of the object in, ***unless*** you want to detect between a head-shot and an arrow in the knee (see what I did there, with the archer... OK, it wasn't that funny) - if you use multiple, different hit-boxes, I would either iterate through them manually, or create a new class with an array, a `hit(Object obj)` method and a name so you could then make a list of these and find out which part had been hit by name. The only issue with the latter method is that it would probably add unnecessary overhead - I'd go with a seperate class, but that's my OCD.

Once you have the objects in a list to be hit, you iterate through that list, and with everyone do a collision test. These get slightly more interesting with other shapes (read - irregular polygons and circles), but collision tests with rectangles are surprisingly easy. In pseudocode:

```
Rectangle rectA;
Rectangle rectB;

if ((rectA.leftHandSideXValue <= rectB.rightHandSideXValue) && (rectA.leftHandSideXValue >= rectB.leftHandSideXValue))
{
    // Handle intersection
}

// Repeat for the other sides - that is, rectB.left <= rectA.right
// ^ && rectB.left <= rectA.left, and do the same but with top and bottom boundaries.

```

That probably answers your questions - I've probably failed to address something, but just comment on the OP and I'll see it, and try to edit this post accordingly.

---
Tags: 2d, java, entities
---


# Question
Title: deferred rendering and point light radius
I use a common attenuation equation for point lights: **attenuation = 1 / kc + kl * d + kq * d^2**.

I use deferred rendering so I need to know a light radius. An example light has following intensity: vec3(10, 1, 8). RGB components can be greater than 1.0 beacuase of HDR/Tone Mapping. How to calculate a light radius ?

**Edit1** An attenuation equation can be defined this way (link) and we get following equations:

* **attenuation = 1 / ( (d / r) + 1) ^ 2**
* **attenuation = (attenuation - cutoff) / ( 1 - cutoff)**
* **attenuation = max(attenuation, 0)**
* **lightRadius = r * (sqrt(Li / cutoff) - 1)**
* **cutoff = minLuminance / lightLuminance**
* **Li = lightLuminance**

Let's assume that d = 40, r = 1, lightLuminance = 10 and minLuminance = 0.01. Then: lightRadius = 99 but attenuation = 0. What is wrong ?

# Answer
The attenuation equation you posted, strictly speaking, does not allow for any finite light radius, since the attenuation will not go to zero at any finite distance.

However, in practical terms there will be some distance at which the light becomes too dim to see. If you define a luminance threshold, you can plug this into the attenuation formula and solve to see where the light crosses this threshold. In pseudocode:

```
// Get light's luminance using Rec 709 luminance formula
lightLuminance = dot(lightColor, vec3(0.2126, 0.7152, 0.0722))

// Minimum luminance threshold - tweak to taste
minLuminance = 0.01

// Solve attenuation equation to get radius where it falls to minLuminance
lightRadius = solveQuadratic(kc - lightLuminance / minLuminance, kl, kq)

```

In an HDR context, you might have variable exposure - in that case, `minLuminance` should probably be scaled inversely by exposure so that it represents a consistent display-referred luminance. This means lights will have different radius at different exposures though, which might be undesirable (e.g. you're putting them into a spatial subdivision structure).

On the other hand, you might want to tweak the attenuation so that it actually falls off to zero at a finite distance. A common way to do this is define an inner radius and outer radius, and multiply the attenuation function by a linear ramp that fades the light down to zero between the inner and outer radius, such as

```
attenuation *= saturate((radiusOuter - d) / (radiusOuter - radiusInner));

```

(In the shader, of course you should transform this into just `saturate(d * a + b)` and precalculate `a` and `b` to match the previous formula, rather than doing the subtractions and divide per pixel.)
> 8 votes

---
Tags: opengl, mathematics, deferred-rendering
---


# Question
Title: Changing textures on a Model messes up antialiasing? (XNA)
Here is a code sample:

```
        blockModel = game.Content.Load<Model>("Models/Cubes/Cube"); //this is a .fbx file, made in blender

        absoluteBlockTransforms = new Matrix[blockModel.Bones.Count];
        blockModel.CopyAbsoluteBoneTransformsTo(absoluteBlockTransforms);

        /*
        foreach (ModelMesh mesh in blockModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.Texture = game.Content.Load<Texture2D>("Textures/Cubes/CubeLayout"); //this is the texture it's already using, but copy-pasted into a different directory
            }
        }*/

```

This looks fine

Now if I uncomment the lines above, somehow everything gets screwed up?

Somehow just setting the Texture property messes something up, but I'm not sure what exactly (aside from the symptoms). Note that framerate doesn't actually change; the small difference is just a coincidence. Also, the multisampling property is set *after* this is called, so it's not an issue of it somehow changing the graphics property.

# Answer
> 1 votes
As was eluded to in the comments, the problem is that in the second half your textures are missing mipmaps.

---
Tags: xna, 3d, models
---


# Question
Title: Game Editor - When screen is clicked, how do you identify what coordinate you clicked?
This is a follow-up to my earlier question:

Game Editor - When screen is clicked, how do you identify which object that is clicked?

Something I've noticed is that picking only calculates a ray and checks for the closest objects that intersects it, but since this method isn't working for placing object in a 3D World what are the best way of doing that? A ray is just a line that goes from one point in a certain direction, it checks the first object that intersects it that is closest. But not if you don't have any objects.

I've used one method for calculating a position with an Isometric Camera, but currently I have an arc ball camera and it doesn't produce the same results. Is there a general way that actually produces a good coordinate?

This is currently the method I'm trying to understand, but I've found no tutorials/information on how to actually translate numbers between 0 and 1 to real coordinates on the screen.

3D Arc Ball Camera with this method:

```
public static Vector3 GetScreenCoordinates(MouseState Mouse, Viewport viewport, Matrix Projection, Matrix View, Matrix World)
{
    Vector3 pos1 = viewport.Unproject(new Vector3(Mouse.X, Mouse.Y, 0), Projection, View, World);
    Vector3 pos2 = viewport.Unproject(new Vector3(Mouse.X, Mouse.Y, 1), Projection, View, World);
    Vector3 dir = Vector3.Normalize(pos2 - pos1);
    dir.Normalize();

    return dir;
}

```

# Answer
Use a plane or three planes to check collision against them.

If the world is empty you need to collide with something... one easy solution is setting a reference plane... usually the ground... and check ray collision against the plane to get coordinates in world space...

when you work with objects in an editor, the easier is working in world coordinates... and being independent of screen coordinates...

Here is a video of the editor i'm doing now... where you can see how it is done...
> 2 votes

---
Tags: xna, coordinates, map-editor, picking
---


# Question
Title: How can SpriteBatch use a single texture/asset as multiple independent objects/instances
I'm using LibGDX to create a game, but I'm encountering a problem with SpriteBatch. Whenever two objects that use the same image for their sprite come onto the screen, the new object replaces the old object. So, for example, one ship will come onto the screen, and when a ship with the same sprite comes onto the screen, the old ship will disappear and the new ship will have all the damage and other characteristics of the old ship.

I could always make multiple copies of the same image and put them in the assets folder, but that seems unnecessary. Does anyone have any ideas? Am I using SpriteBatch incorrectly?

Edit: Here's a couple of examples of rendering methods in the game loop.

The method for rendering ships:

```
private void renderDoodad(Doodad doodad) {
    if (!doodad.isDisabled()) {

        batch.begin();
        if (doodad instanceof Enemy) {
            batch.draw(doodad.getSprite(), doodad.getX(), doodad.getY());

```

Followed by some code about what to do if the ship is the player's ship. But the player's ship is rendering fine, so I left that out.

Then there's the method for rendering shots:

```
    private void renderShot(Shot shot) {
    if (!shot.isDisabled()) {
        batch.begin();

        batch.draw(
                shot.getSprite(),
                shot.getX(),
                moveDoodadY(shot, shot.getDirection().getVal()
                        * getApp().getGraphics().getDeltaTime()));
        batch.end();
    }
}

```

# Answer
I'm a couple of days late in answering this, but I thought I'd let you know. The problem was with Sprites being referenced through a static helper class and therefore not instantiating properly. This has been fixed by switching the helper class to textures.
> 0 votes

# Answer
I can't see how rendering (another ship is being rendered) can cause changes in game logic - damage and other ship characteristics, as you said. If this was truly a sprite rendering issue, the game objects would be fine and only the graphics would be messed up.

It seems to me more like some reference mistake. Is it possible that you accidentally use "x = y" instead of "x.set(y)"? That will *bond* objects together instead of copying one object's properties to another. You can check that in debugger. If you inspect your game objects, they should generally have different pointer (the number in parenthesis after the variable name). Only used SpriteBatch or Texture/Region should point to the same object.

---

If I am wrong, you should probably edit your question and add some example of your code. There should be no issues in drawing multiple Sprites which share the same Texture. It is being used in numerous games. Also check SpriteBatch wiki page for code snippets.
> 0 votes

# Answer
It's hard to tell without seeing your code (show some!), but I'm guessing that your draw order may be messed up. Maybe you are clearing your buffer each time you draw a new sprite or maybe you are drawing your background again over top of the old one. Post code that is relevant to your game loop's draw step and shows how you are using SpriteBatch.
> 0 votes

---
Tags: graphics, libgdx, spritebatch
---


title: Should my platformer have collectibles?

text:
# Question
Title: Should my platformer have collectibles?
By collectibles, I mean objects that you collect mainly for the sake of collecting them, not to power up. Think coins in *Super Mario* or bandages in *Super Meat Boy*.

I've seen a few platformers that do not have any collectibles and it's the platforming itself which is challenging (my platformer itself is challenging), but I think adding collectibles will add extra challenge and re-playability, especially if some of the collectibles are really well hidden. Tradition would dictate that you should have collectibles, as it's a way for players to gain extra lives or even gain points, but that would not be the only reason to have collectibles.

I'm not interested in making features for feature sake. I'm purely wanting an opinion on whether collectibles should be included in a game and what should the collectibles do when you collect enough? Is a simple +1 life fine? Should there be some cool object you get? Possibly should collecting really change something hectic, like collect 100 coins and your character is invincible?

How do I decide if my platformer should have collectibles?

**Closed**. While I disagree with the closing as according to the FAQ What should be asked `game design (level design, gameplay, mechanics, etc)`. I got some nice pros and cons from everyone. I have updated the question slightly to be more specific.

# Answer
> 7 votes
You don't say anything about what your game is, so it's hard to know whether you should or shouldn't have such collectibles.

Some platformers do have additional tokens to collect, and some don't. There's no tradition that requires they be included in a game. What matters is if they fit in how your game should be played. I imagine you're more likely to be able to think of games where there's some sort of reward for collecting them. Some games offer extra lives for collecting enough *things*, others allow unlocking additional features (areas, characters, all sorts of stuff). If there's a purpose to them, they can add additional replay value or extra goals for skilled players.

The Super Mario Bros. games award extra lives (among other things depending on the title) for collecting enough coins, giving them a specific purpose and a reward. The reward for players skilled enough to collect more coins, is that they earn additional chances in-game. Mario games are more arcade-style gameplay, and the player benefits directly from being able to earn additional lives.

Metroid, on the other hand, does not feature similar non-upgrade collectibles. Your tokens are either direct upgrades (new armor, weapons, etc.) or health and ammo. There are no extra *things* that exist solely to be collected. This doesn't hurt the game because the game isn't designed around the need for such collectibles.

Both of these series are considered classic platformers, one has them, the other doesn't. The list could go on, of course...

Look at the design of your game and determine what the purpose for collectibles would be. If you think your game would benefit from them, try it.

# Answer
> 4 votes
Definitely maybe.

Good platformers that **have** collectibles (and how they're used):

* Nintendo's Super Mario (coins, Shine Sprites, mushrooms...) Very frequent coin pick-ups, with some games featuring collectibles that are harder to find.
* Team Meat's Super Meat Boy (bandages). Always very difficult to get, but optional to winning. They're still visibly dangled somewhere nearby to tempt you.
* jmtb02's Achievement Unlocked (coins). Taking it to ridiculousness, as usual. Important but fairly infrequent collectibles.
* Mossmouth's Spelunky (gold, gems, lost ladies). The whole point is to collect treasure. Frequent game-critical pick-ups.
* DICE's Mirror's Edge (runner bags). 3D example! Much like Super Meat Boy, in that collectibles are hard to get and optional. However, they are never pointed out and must be discovered through exploration.

Good platformers that **don't** (and why not):

* Nifflas' Knytt and Night Sky. Their gameplay relies heavily on skillful platforming. Both games also have a quiet atmosphere, with lots of emphasis on the environment. Collectibles would be distracting.
* Adam Atomic's CANABALT, where the focus of both the gameplay and art is on escape to somewhere as far as possible. Collectibles would be distracting from the overarching theme. Interestingly, Temple Run has taken a very similar idea, but managed to add collectibles!

There is much to be learnt from history.

It's a matter of game design. Collectibles *are* common in platformers, but they are not necessary or traditional. Even *when* they are used, they are used in very different ways as to gameplay.

Use them wisely, if at all.

# Answer
> 4 votes
Placing collectibles in hard to reach places adds an additional challenge to the game, but it's an optional challenge the player doesn't necessarily have to complete in order to progress. That allows you to challenge the player without frustrating them by blocking their progress should they be unable to complete it.

Collectibles can also be used to communicate hints to players. They can "suggest" players to perform certain actions. Look at this screenshot from Giana Sisters: Twisted Dreams. The goodies here mark the ideal jump trajectory over a pit. They tell the player "That's how you have to jump":

Goodies can also tell the player if they already were in a certain location before or not (when there are still goodies around, the location must be new). So they are also a valuable navigation help, especially when your level design is complex and you lack the graphic design resources to make each location sufficiently unique.

# Answer
> 2 votes
Would you like to have collectibles in your game? If so, have them. If not, don't.

# Answer
> 1 votes
If you are looking into designing the platformer, consider other parts of platformer design too, as mentioned in this blog post:

http://phoffstein.wordpress.com/essays/platformer-level-design/

Collectibles arent necessary in platformers. They are a choice decision by the game designer, in the overall design of the platformer gameplay.

---
Tags: game-design, platformer
---


# Question
Title: How do you accommodate newbies while still creating depth in the design of light/dark systems for MUDs (or other text-based games)?
I've been pondering a redesign of our MUD's light/dark system. Our current system accommodates new players by simply not saddling them with being unable to see should they happen to wander outside of a populated area at night. I would like, in redesigning the light system, to stop making accommodations. I take the accommodations as a sign the system is less than ideal for everyone.

I appreciate the way visual games are afforded to handle this; we can generally see the area around our character, and in some cases can obtain bonuses to the radius within which we can see. I haven't been able to come up with a good way to port this concept to a MUD, at least without a concept of relative position that our current code-base just doesn't support. If we didn't have multiple player sub-classes based on the darkness they can create, I would be inclined to make it so all players can see the room they're in, get rid of torches, and be done with it.

I've spent a few hours searching and have failed to dig up compelling discussions on the topic. I'm sure they exist--I find it hard to believe the topic hasn't been aired somewhere. I'm curious how others would approach a light/dark system needing no exceptions for newbies, while still being able to accommodate classes, such as the undead, which need darkness (indeed, part of their power comes from their ability to keep others from seeing.)

# Answer
You could have alternative, very short, vague descriptions of locations for use at night. Also available interactions with elements of the room could be different. This way the player could be able to for example notice that there is some road sign pointing to some important location (which might be the city) and during day the player could be able to read that sign.
> 2 votes

# Answer
You could provide players with some easy to obtain equipment to see in the dark (a torch, for example), but discourage its use for advanced players by making other equipment options available which result in superior character performance, but do not have the light perk.

An easy to acquire torch, for example, could be useful as a weapon itself in the beginning, so it's dual-use light source and weapon. Or it could fill the offhand equipment slot which a newbie has no use for, because two-handed weapons, shields or dual-wielding weapons aren't available to them yet.

But a player who has progressed further might opt to use a harder to acquire two-handed sword instead which is a much superior weapon, but doesn't create light, so the player has to learn how to navigate the world without the aid of light in exchange for more combat ability.
> 2 votes

# Answer
I'm going to make a presumption here, in that experienced players can cope with the dark. What I'd do is follow the route of several other games, and give a one week grace period, for example. During this time, new players can get used to playing the game - note that there would only be a limited amount of light, and this could possibly even be shrunk down over time to acclimatise players to the game. In this way, new players aren't faced with a seemingly impossible game to start with, but after a while they can then play evenly with other people.
> 1 votes

---
Tags: text-based, lighting, mud
---


title: Regarding physics engines and the GPU

text:
# Question
Title: Regarding physics engines and the GPU
The rigid body physics engines that use a "bounding box" for collision detection, I am aware of how they are created.

What I want to know is, is there a physics engine that does not use "bounding box" but actually uses something like vertex data to do the physics calculations? What type of physics engine is this called, and does it use the GPU?

# Answer
There are two general cases for using a physics system in a game:

1. For gameplay. That is, using forces and collisions to move objects around. The physics system manages the location and movement of game objects.
2. For visualization, things like particle systems. These are pure-rendering things that don't affect gameplay.

Handling #1 on the GPU is a bad idea performance-wise. The problem is that you need to do a CPU-\>GPU-\>CPU round-trip. The CPU needs to manage where objects are, so that AI and other systems can manipulate it. Therefore, the CPU may need to update the position of objects. The CPU also needs to read the positions of objects, as well as be notified of any collisions. So you can't just fire off some GPU "rendering" commands and then do something else; you need that information right now for AI and the like.

This forces a GPU/CPU synchronization. A GPU/CPU sync is one of the worst things you can do for performance. You want the GPU to operate as asynchronously as possible. Doing physics of type #1 on the GPU works against that.

Now, for #2 physics, things are different. In this case, the physics is completely subservient to the rendering of the object. It basically does physics solely to do rendering. Therefore, everything can effectively live on the GPU. For this, doing the physics on the GPU makes sense, because the AI and game engine *don't care* about any collisions or whathaveyou.

I don't know of anything complex enough for people to call it a "physics engine" that *doesn't* handle at least convex hulls. You can generally build concave meshes by taking many convex hulls and using constraints to effectively fuse them together, though how well this works depends on the physics system.

Many physics engines do have some way to run on GPUs. PhysX and Bullet have some mechanisms for it, though it may be limited to certain hardware that provides appropriate support.
> 5 votes

# Answer
In general bounding boxes are used as quick checks to avoid performing the more expensive collision checks involving the complete geometry. If the bounding boxes of two objects do not intersect then it is guaranteed that the objects themselves do not intersect, and therefore the real collision detection between these objects can be skipped.

No serious physics engine use bounding boxes for actual collision checks, if they are used it is purely a performance optimization that has no influence on the outcome of the simulation.
> 1 votes

---
Tags: game-design, physics
---


# Question
Title: Can SpriteBatch be used to fill a polygon with a texture?
I basically need to fill a texture into a polygon using the SpriteBatch. I've done some research but couldn't find anything useful except polygon triangulation method, which works well only with convex polygons (without diving into super math which is definitely *not* something I'm pretty good at). Are there any solutions for filling in a polygon in a basic way? I of course need something dynamic (I'll have a map editor that you can define polygons, and the game will render them (and collision detection will also use them but that's off topic), basically I can't accept solutions like "pre-calculated" bitmaps or anything like that. I need to draw a polygon with the segments provided, to the screen, using the SpriteBatch.

# Answer
if you have to use the spritebatch, only accepts to draw rectangles, and you define the polygon in a map editor, why don't precalc the texture?

You can still use your polygon for physics, only have to create its skin.

1. Create a new texture. The polygon have to fit inside.
2. Fill the texture with Color.TransparentBlack
3. Draw the polygon's edges with lines. You can use the bresenham algoritm
4. Do a flood fill with your texture.
5. Then you save this new texture.
6. Later inside the game you can draw with this new texture as a rectangle

Other approach is to compose the polygon with triangles, but that it's not worth.

And the third option is not using spritebatch and triangulize as you know
> 1 votes

# Answer
```
    private Bitmap ClippedBitmap(Bitmap texture, Point[] pointsArray, out Point position)
    {
        int minX = pointsArray.Min(x => x.X);
        int maxX = pointsArray.Max(x => x.X);
        int minY = pointsArray.Min(x => x.Y);
        int maxY = pointsArray.Max(x => x.Y);
        position = new Point(minX, minY);
        Bitmap bit = new Bitmap(maxX - minX, maxY - minY);
        Point[] offset = new Point[pointsArray.Length];
        pointsArray.CopyTo(offset, 0);
        offset = Array.ConvertAll(offset, x=> x = new Point(x.X - minX,x.Y - minY));
        Graphics g = Graphics.FromImage(bit);
        TextureBrush tb = new TextureBrush(texture);
        g.FillPolygon(tb, offset);
        return bit;
    }

```

Load the texture U need as a bitmap, then use this. pointsArray is a polygon points. Point position is a position point, where you ought to draw the texture to be fitted in polygon. Also, you can add code

tb.WrapMode = System.Drawing.Drawing2D.WrapMode.Clamp;

float scaleFactor = Math.Max((float)bit.Width / texture.Width, (float)bit.Height / texture.Height);

tb.ScaleTransform(scaleFactor, scaleFactor);

if you want to wrap your texture inside the polygon (otherwise if will be tilted).
> 0 votes

---
Tags: xna, spritebatch
---


# Question
Title: What concepts are there for interactive water?
I want water to be a gameplay object in my game. The player should be able to take in in a bucket and tip it out somewhere in the world. Water should flow in some way so that it can be used to build rivers and transport game objects or to create particular apparatuses. It's comparable to the game Minecraft where you can build cool things involving water or just create just some small waterfalls. However, there my game isn't made out of blocks so there is smooth terrain.

In most games water is simply placed at a given height. That works well for lakes and Oceans, but for flowing rivers and usage in apparatuses this concept is to limited. In Minecraft water is implemented as a block which spreads inside the blocky grid, too. That approach is a bit more what I need to realize my idea but I don't use these blocks and therefore such water simulation would look very misplaced.

What concepts of representing water which the player can interact with in the mentioned manners are there? How can I realize oceans, rivers, buckets and so on with one general approach? There shouldn't be an infinite amount of water. If you fill your bucket, the volume of the lake the water was taken from should decrease unnoticeable. Moreover if the player would place water somewhere that volume of water should never go missing.

# Answer
If you're looking to have not a lot of water move over a terrain, then your best bet will likely be some form of Smoothed Particle Hydrodynamics (or SPH). In this formulation, you simulate a set of particles as they adhere to the laws of hydrodynamics (namely, the Navier-Stokes equations). There is a great series of articles written about this from Intel:

http://software.intel.com/en-us/articles/fluid-simulation-for-video-games-part-1

Rendering your particles as fluid will likely be done using some sort of metaball formulation. You can get a good intuition from this article. The basic technique is described here, and what you can expect it to look like is something like this although it will depend how you write your shaders.

For larger bodies of water, I suggest looking at this tutorial which outlines some of the techniques used to generate a large body of water. You can combine this with the previous method to have fluid that flows into large bodies of water too.
> 6 votes

---
Tags: water
---


title: Android Game an

text:
# Question
Title: Android Game an
I want to develop an android game (3D/2D).. and I don't have any knowledge about android app development. So can you suggest some helpful and understandable resources like video tutorials or head first book that i could consult?

Also can I use C++ for the task?

# Answer
> -1 votes
Try the video tutorials of Android Application Development Tutorials of **theNewBostonAndroid** series. Its very briefly explained in detail & step by step way for android aplication development environment.

You can also check the **android** portal of stack exchange for any query or problems of android. Go to url ***android.stackexchange.com***

---
Tags: c++, 2d, android, 3d, game-design
---


# Question
Title: Starting out - should I make complete games or just play around?
While starting out, I made clones of some arcade games (Tic tac toe, Pong, Snake, Tankwars, Breakout, Tetris, etc). Most of these games had just had the gameplay, I didn't code any of the starting screens, there were no features like high scores, etc. My question is, should I focus on polishing these games up or just start with more comlicated games?

# Answer
It depends what exactly you want to learn and what your goals are. I would tend to say it'll be more valuable for you to finish the games completely, rather than leave a trail of half finished demos, but there is something to be said for moving on to more complex topics (eg. 3D graphics) and leaving the simple stuff behind.

On the one hand, finishing your games fully will build up a crucial skill/attribute I refer to as "finishing ability." In other words, the grit and doggedness to actually see the project through to the end. It is one thing to just hack together the interesting part of a project, but it is pretty rare to find someone who can stick through to the end and not peter out when the project gets less interesting. For example, I knew a guy who was a graphics programmer on a AAA game engine (ie. this guy was a top notch programmer) who couldn't build an entire game when I first met him and found the process of building up his finishing ability a revelation.

That said, my little anecdote does point out that you don't necessarily need finishing ability in order to be, say, a graphics programmer on a AAA engine. Managing other people and/or a large project does require the doggedness to keep going through to the bitter end, but you don't necessarily need finishing ability when you're first starting out and being managed by a superior. A bigger company might care more about specific advanced technical skills the team needs, whereas a smaller team needs people who self-manage development.

(aside: I've never really pinpointed this before, but now that I'm thinking about it, I think finishing ability is the main thing I see separating experienced developers from novices)
> 12 votes

# Answer
Biased answer, based on my personal preference and experience since the question is of the same nature.

Finishing is beneficial in terms of learning to architect a clean code structure and program flow, initial prototyping i tend to leave in quite a few hacks, they are "correct" in terms of language use but when writing them i have a better method in mind that would require more time, and its more satisfactory to just get things to "work" as soon as possible, example would be brute force collision checks versus spatial partitioning, it works on the demo level but will be insufficient in later levels.

When actually finishing a game, i tend to run into these boundaries and have to solve them, which can be interesting and a nice learning experience.

And when it comes to "classic" games, you can always reiterate on the game play, how to make it more interesting rather than just cloning the game mechanics.

So to summarize, my advice would be yes completion is better.
> 2 votes

# Answer
I used to play around the whole time. Implement just some features, optimise etc. While this is all fun and inspiring you can't really put that in your portfolio which I quite regret. That's just one thing, next one is you won't experience certain problems when doing the small stuff.

If I may suggest - try to accomplish 1 big project a year, but don't forget to experiment. I'd do that if I was smarter in the past :)
> 0 votes

---
Tags: 2d, game-design
---


# Question
Title: Will polishing my current project be a better learning experience than starting a new one?
I started programming many years ago. Now I'm trying to make games. I have read many recommendations to start cloning some well known games like galaga, tetris, arkanoid, etc. I have also read that I should go for the whole game (including menus, sound, score, etc.).

Yesterday I finished the first complete version of my arkanoid clone. But it is far from over. I can still work on it for months (I program as a hobby in my free time) implementing a screen resolution switcher, remap of the control keys, power-ups falling from broken bricks, and a huge etc.

But I do not want to be forever learning how to clone ONE game. I have the urge to get to the next clone in order to apply some design ideas I have come upon while developing this arkanoid clone (at the same time I am reading the GoF book and much source code from Ludum Dare 21 game contest).

So the question is: **Should I keep improving the arkanoid clone until it has all the features the original game had? or should I move to the next clone (there are almost infinite games to clone) and start mending the things I did wrong with the previous clone?**

This can be a very subjective question, so please restrain the answers to the most effective way to learn how to make my own games (not cloning someone ideas). Thank you!

---

**CLARIFICATION**

In order to clarify what I have implemented I make this list:

Features implemented:

* Bouncing capabilities (the ball bounces on walls, on bricks, and on the bar).
* Sounds when bouncing on bricks and the bar, and when the player wins or loses.
* Basic title menu (new game and exit only). Also in-game menu and win/lose menus.
* Only three levels, but the map system is so easy I do not think it will teach me much (am I wrong?).

Features not-implemented:

* Power-ups when breaking the bricks.
* Complex bricks (with more than one "hit point" and invincible).
* Better graphics (I am not really good at it).
* Programming polishing (use more intensively the design patterns).

Here's a link to its (minimal) webpage: http://blog.acamara.es/piperine/ I kind of feel ashamed to show it, so please do not hit me too hard :-)

My question was related to the not-implemented features. I wondered what was the fastest (optimal) path to learn. 1) implement the not-implemented features in this project which is getting big, or 2) make a new game which probably will teach me those lessons and new ones.

---

**ANSWER**

I choose @ashes999 answer because, *in my case*, I think I should polish more and try to "ship" the game. I think all the other answers are also important to bear in mind, so if you came here having the same question, before taking a rush decision read all the discussion.

Thank you all!

# Answer
I disagree with Patrick's answer completely. If you want to succeed as a game developer, the number one skill you need to learn is **how to take an idea and ship a complete, polished game.**

What you will realize over time (which is what I realized after several years) is that programming *is only a small part of your game.* It's easy, because it's fun. But to stick to only programming will leave you with a trail of incomplete proof-of-concepts and demos.

Instead, I would suggest very strongly you put up a website and blog (Wordpress is great for this kind of stuff), finish your games (starting with Arkanoid), and release them into the wild.

Also, it's key to realize that if you do this, **you control when the game is done.** If you want 1000 levels with 10 major features, fine. If you want 10 levels with 3 major features, fine. (In fact, I recommend smaller projects more frequently, because you learn more and focus a lot on polishing that way).

**Edit:** In response to the people who disagree, I feel I need to clarify. If you created a game just for one purpose/experiment (which I do *all* the time), by all means, **cut scope and ship it.** Nobody said Arkanoid needs 1000 levels to be a polished game; just make enough levels for it to be, in your opinion, fun, and move on.

It IS possible to spend years on a game and never ship. But I feel it's far easier to fall into the other hole of only making technical demos and prototypes forever. It took me 10+ years to stop doing this myself.
> 32 votes

# Answer
I would suggest a synthesis of the previous two answers. Basically, I agree that it is enormously important to learn how to take an idea and ship a complete, polished game. The internet is littered with half-completed projects that someone started and then got bored of. The ability to stick with a project from beginning to end, what I call "finishing ability", is rare and precious, and gained by forcing yourself to practice it.

However you are not at that stage in your learning yet; I would not recommend doing this with your very first game, but rather make a few smaller games to learn with before working up to your first complete project.

(aside: I've never really pinpointed this before, but now that I'm thinking about it, I think finishing ability is the main thing I see separating experienced developers from novices)

---

ADDITION: I think a lot of the disagreements between answers just comes down to different assumptions about where he is in his process. For example, when he said "I finished the first complete version of my arkanoid clone" that could mean many different things. In my case, since he earlier said "I have also read that I should go for the whole game (including menus, sound, score" then I assume he actually implemented that stuff and is asking if he should keep going even further. In that case I would say no; call this project done and move on to the next project.

However that's just an assumption on my part; he didn't actually say he had *done* that stuff, just that he'd read it. If he hasn't done that stuff, then I would say don't move on until you've done that stuff.
> 8 votes

# Answer
I think that you have the right idea that you should move onto the next project now. I think this because you've already learned from your first and want to apply what you've learned! Once you slow down learning the basics then that would be the time to clone deeper features that you can keep learning from.

Remember that you're working on programming skills, not game design, so you want to end up being able to program any game design when you're done learning.
> 5 votes

# Answer
Why not make the clone "yours"? Add some new interesting twists that will keep you interested.

There is an upside to started "your own" project, you feel like it has never been done before. Reality is someone probably has something similar already. Unless you plan on inventing a new genre of gaming, I would suggest making these "clones" your own.

Example, my buddy in college created a pong "clone". He made it his own, added a whole new type of gameplay where a power-up allowed one to drive a sweet tank around for like 15 seconds and destroy as many bricks as possible!

The best way to learn game development (art, code, design) is to just do it. You may not do it well at first but the key is to just keep at it and write more code, draw more animations, and design more levels!! In my opinion, it doesn't matter if you are "cloning" something as long as you make it your own, keep doing it, make it interesting, and have fun!
> 2 votes

# Answer
To answer your question, **yes**, polishing your current project will be a better learning experience than starting a new one.

1) You need to get in the habit of finishing things. That *in itself* is a learning experience.

2) The tasks you are "too lazy to add" (for lack of a better term) may have a ton of game dev lessons embedded in them, that you're just totally skipping out on.

3) If you're *bored* of Arkanoid, you can always set it aside and work on something else for the time being. There is nothing wrong with that.

### 1) Too many unfinished things is bad. You can't really use your unfinished product to show off your skills effectively.

This is because having an array of unfinished things is like having a closet full of junk. Some of it looks useful, but in reality it is all very useless, and the reality of the game industry is, few will appreciate your "junk" (unfinished games).

Unfinished games are too common. People put them out there and are like, "duh, this game was sapposa be StreetFighter.. now you can move back and forth.." **Unimpressive**. Nobody can see in your head what the game was "sapposa" be. They only see it for what it is, unfinished.

An unfinished game is like a half-baked tart. Some people might be able to appreciate that, but it actually tastes disgusting, and 20 minutes more in the oven could make what you've already half done delicious to everybody.

### 2) The features you're avoiding working on may have some very valuable lessons in them.

The stuff you're balking at finishing:

Features not-implemented:

* Power-ups when breaking the bricks.
* Complex bricks (with more than one "hit point" and invincible).
* Better graphics (I am not really good at it).
* Programming polishing (use more intensively the design patterns).

Some of these things you can leave out. For example, "Use more intensively the design patterns". Refactoring like this is a waste of time for a pet project, to apply this you should just start a new project.

Some of these are easy. E.g. complex bricks. Some of these are actually *a lot of work*. Powerups aren't easy, they require you to feature build things like guns, bullets, would require addition of ray-intersection code.

I think what you're seeing is "putting the scaffolding in place was so easy.. and look it's almost done. Finishing would be so much work, may as well stop now." Yeah, erecting the wooden frame for a house is "easy" too, and it may be half the work. Drywalling, electricity, plumbing, are all "details". But by not finishing the house, nobody's gonna "buy" how great the house *would-a* been if only you would have finished it.

### 3) If you're bored of what you're working on, there's nothing wrong with starting something else.

This doesn't mean junk what you're working on, but there's no harm in spending a month or two thinking about other things or starting a new game. You may come back to Arkanoid with a fresh perspective.

Also a final point. Besides building out all expected features of Arkanoid, it's even *more* interesting to put your own twist on it. So instead of *stopping short* on your clone, you should take it **a step further** and innovate on the original game.
> 2 votes

# Answer
The right answer really depends on what you want to do next. If you move on to something new you may risk finding yourself solving the same old problems all over again and not really extending your skills, but you do get to move on to something new. If you continue to polish there are useful things to learn from the brief list you gave, and they will stand you good in the future, but you're still working on the same old codebase.

What I'd recommend, and this is a purely personal opinion, is to move on to something new and save the polish for that. At the same time try to stretch yourself with that something new. So if you're currently not using a 3D API, learn one and use it. If you are using one, learn the other and use it. Or move up to a more advanced level at the one you are using. Include a better sound, physics or input engine from the get-go. Whatever, what I see as the important thing is to move a little outside of your current comfort zone and build up more skills and knowledge, while having fun doing so.
> 1 votes

---
Tags: project-management
---


# Question
Title: Why doesn't a line draw after instantiating it on a thread other than the renderer thread?
I'm making a 2D game with OpenGL ES 2.0 on Android, as an excuse to learn a bunch of things. I'm drawing many lines to make a grid, but setting everything up takes time and I'd like to render a loading screen while I set everything up in the background.

While trying to tackle this issue, I'm facing a problem that I can't understand so my question is why am I seeing this behavior.

**The code:**

This is the class whose instances will represent each line:

This is just a slightly modified example I found on the web. There's a call to Thread.sleep that's only meant to increase the time it takes to create it, so that I can show the problem I'm facing.

```
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import android.opengl.GLES20;

public class LineExample {

    private final String vertexShaderCode =
                "attribute vec4 vPosition;" +
                "void main() {" +
                "   gl_Position = vPosition;" +
                "}";

    private final String fragmentShaderCode =
                "precision mediump float;" +
                "void main() {" +
                "  gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0);" +
                "}";

    private int mProgram;
    private FloatBuffer vertexBuffer;
    private ByteBuffer bb;

    // number of coordinates per vertex in this array
    static final int COORDS_PER_VERTEX = 2;
    private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex
    private float lineCoords[] = new float[2*COORDS_PER_VERTEX];
    private int vertexCount = lineCoords.length / COORDS_PER_VERTEX;

    public LineExample(float[] lineCoords) {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        this.lineCoords = lineCoords;

        // initialize vertex byte buffer for shape coordinates
        bb = ByteBuffer.allocateDirect(
        // (# of coordinate values * 4 bytes per float)
                lineCoords.length * 4);
        bb.order(ByteOrder.nativeOrder());
        vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(lineCoords);
        vertexBuffer.position(0);

        // prepare shaders and OpenGL program
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER,
                                                   vertexShaderCode);
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER,
                                                     fragmentShaderCode);

        mProgram = GLES20.glCreateProgram();             // create empty OpenGL Program
        GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
        GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
        GLES20.glLinkProgram(mProgram);                  // create OpenGL program executables

    }

    public void draw() {

        // Add program to OpenGL environment
        GLES20.glUseProgram(mProgram);

        // get handle to vertex shader's vPosition member
        int mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");

        // Enable a handle to the triangle vertices
        GLES20.glEnableVertexAttribArray(mPositionHandle);

        // Prepare the triangle coordinate data
        GLES20.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX,
                                     GLES20.GL_FLOAT, false,
                                     vertexStride, vertexBuffer);

        // Draw
        GLES20.glDrawArrays(GLES20.GL_LINES, 0, vertexCount);

        // Disable vertex array
        GLES20.glDisableVertexAttribArray(mPositionHandle);
    }

    private static int loadShader(int type, String shaderCode){

        // create a vertex shader type (GLES20.GL_VERTEX_SHADER)
        // or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
        int shader = GLES20.glCreateShader(type);

        // add the source code to the shader and compile it
        GLES20.glShaderSource(shader, shaderCode);
        GLES20.glCompileShader(shader);

        return shader;
    }

}

```

Here's the renderer:

```
public class MyRenderer2 implements Renderer {

    LineExample currentLineToRender = null;

    @Override
    public void onDrawFrame(GL10 unused) {
        GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
        if (currentLineToRender!=null){
            currentLineToRender.draw();
        }
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        //initializeLines();
        initializeLinesSameThread();
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {
        GLES20.glViewport(0, 0, width, height);
        GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    }

    private void initializeLines(){
        float[] waitingLineVerts = {-0.5f,0.0f , 0.5f,0.0f};
        currentLineToRender = new LineExample(waitingLineVerts);
        new Thread(){
            public void run() {
                float[] doneLineVerts = {0.0f,-0.5f , 0.0f,0.5f};
                currentLineToRender = new LineExample(doneLineVerts);
            }
        }.start();
    }

    private void initializeLinesSameThread(){
        float[] waitingLineVerts = {-0.5f,0.0f , 0.5f,0.0f};
        currentLineToRender = new LineExample(waitingLineVerts);
        float[] doneLineVerts = {0.0f,-0.5f , 0.0f,0.5f};
        currentLineToRender = new LineExample(doneLineVerts);
    }

}

```

The goal is to see the an horizontal line for 5 seconds (analogous to a loading screen) then see a vertical line (analogous to the actual game grid). However, with this code I get a dark screen for ~10 seconds and then the second line is drawn.

I figured that the thread is busy with the initialization code so it's not drawing the first line, so to allow it to get to the **onDrawFrame** method and draw the first line, I decided to call the initialization of the second line on another thread (by calling **initializeLines()** instead of **initializeLinesSameThread()** on **onSurfaceCreated**), but by doing that, I only see the first line and I never get to see the second.

My guess is that some things that are done in the other thread aren't accessible by the renderer thread when the line's draw method is called.

My question is why is this happening?

(and I'd be grateful if you could give me a suggestion on how to achieve what I want to do)

# Answer
It turns out you can't use GLES20 static methods outside of the renderer's thread. Even though the lines are being "drawn" in the renderer thread, I was using OpenGL calls to prepare their programs in their initialization, which was taking place in another thread. Those calls seem to always return 0, that's why the line wouldn't be drawn later, even if drawn in the renderer thread.

I've had success using the renderer's onDrawFrame method to initialize some assets if needed and show the loading screen at the same time but Shivan Dragon's suggestion is probably much more reasonable for most cases.
> 1 votes

# Answer
If you don't care that the loading screen is not drawn in OpenGL, you can just make a plain View which displays the image corresponding to your loading screen, display that view and then start the view that holds your OpenGL surface. Once that view is loaded, hide the loading screen view.
> 1 votes

---
Tags: android, opengl-es2
---


title: Does this UV mapping method look ok?

text:
# Question
Title: Does this UV mapping method look ok?
i'm having a spot of trouble trying to get my voxels textures in the right place.

I am using a very simple mechanism that assumes all sides of any given block are always individually specified (i'll improve it later). The idea being that the method below gets me the UV coordinates for the block faces.

Given a block type (the Y index) and a face (the X index) i am trying to pull the (textureSize X textureSize) portion of the atlas on to the block face. But it isn't doing what I expect.

So I figured I'd start by confirming that this code is logically correct then look at my vertices to confirm that i'm putting the mappings on the right ones.

```
        /// <summary>
        /// Gets the UV mappings for the given face on the given block type
        /// where the textures in the atlas have the given size and the atlas contains
        /// textures for the given number of block types.
        /// </summary>
        /// <param name="blockType">Type of the block.</param>
        /// <param name="face">The face.</param>
        /// <param name="textureSize">Size of the textures within the atlas.</param>
        /// <param name="atlasSize">Size of the atlas.</param>
        /// <returns></returns>
        public static Vector2[] GetUVMappingsFor(int blockType, int face, int textureSize, int atlasSizeInBlocks)
        {
            Vector2[] result;
            // knowing a little about the engine design means I can make an assumption (or 4) here ...
            //    1. all textures in the mapped atlas are to be the same size
            //    2. all atlas's are laid out in the same way (vertically for each block, horizontally for each face on the block)
            //    3. the blocktype is a number, we don't care what the block is just that it's texture will be in the calculated position
            //    4. all blocks are a perfect cube so no odd shaped textures in the atlas

                // used when dealing with an atlas
                float atlasWidth = textureSize * 6;                    // total width of the atlas
                float atlasHeight = textureSize * atlasSizeInBlocks;   // total height of the atlas
                float tWidth = (1 / atlasWidth) * textureSize;         // width of 1 texture face in the atlas
                float tHeight = (1 / atlasHeight) * textureSize;       // height of 1 texture face in the atlas
                float y = blockType * tHeight;                         // Y to top left of block texture info
                float x = (float)face * tWidth;                        // X to top left of block texture info

                result = new Vector2[]
                {
                    new Vector2(x, y),                   // top left
                    new Vector2(x + tWidth, y),          // top right
                    new Vector2(x, y + tHeight),         // bottom left
                    new Vector2(x + tWidth, y + tHeight) // bottom right
                };
         }

```

Building the vertex array im doing this ...

```
 /// <summary>
        /// Gets the vertices that make up this block.
        /// </summary>
        /// <param name="position">The block position.</param>
        /// <param name="block">The block.</param>
        /// <param name="visibleFaces">The visible faces.</param>
        /// <returns></returns>
        public static VertexPositionNormalTexture[] GetTexturedVertices(Vector3 position, Block block, bool[] visibleFaces, float blockSize, int textureSize, int blocksInAtlas)
        {
            if (block.IsActive)
            {
                List<VertexPositionNormalTexture> _vertices = new List<VertexPositionNormalTexture>(36);

                // Calculate the position of the vertices on the top face.
                Vector3 topLeftFront = position + new Vector3(-blockSize, blockSize, -blockSize);
                Vector3 topLeftBack = position + new Vector3(-blockSize, blockSize, blockSize);
                Vector3 topRightFront = position + new Vector3(blockSize, blockSize, -blockSize);
                Vector3 topRightBack = position + new Vector3(blockSize, blockSize, blockSize);

                // Calculate the position of the vertices on the bottom face.
                Vector3 btmLeftFront = position + new Vector3(-blockSize, -blockSize, -blockSize);
                Vector3 btmLeftBack = position + new Vector3(-blockSize, -blockSize, blockSize);
                Vector3 btmRightFront = position + new Vector3(blockSize, -blockSize, -blockSize);
                Vector3 btmRightBack = position + new Vector3(blockSize, -blockSize, blockSize);

                // Normal vectors for each face (needed for lighting / display)
                Vector3 normalFront = new Vector3(0.0f, 0.0f, 1f);
                Vector3 normalBack = new Vector3(0.0f, 0.0f, -1f);
                Vector3 normalTop = new Vector3(0.0f, 1f, 0.0f);
                Vector3 normalBottom = new Vector3(0.0f, -1f, 0.0f);
                Vector3 normalLeft = new Vector3(-1f, 0.0f, 0.0f);
                Vector3 normalRight = new Vector3(1f, 0.0f, 0.0f);

                if (visibleFaces[0])
                {
                    // Add the vertices for the FRONT face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 0, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalFront, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftFront, normalFront, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalFront, uvMappings[1]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftFront, normalFront, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightFront, normalFront, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalFront, uvMappings[1]));
                }

                if (visibleFaces[1])
                {
                    // Add the vertices for the BACK face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 1, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(topLeftBack, normalBack, uvMappings[1]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalBack, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftBack, normalBack, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftBack, normalBack, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalBack, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightBack, normalBack, uvMappings[2]));
                }

                if (visibleFaces[2])
                {
                    // Add the vertices for the TOP face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 2, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalTop, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalTop, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topLeftBack, normalTop, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalTop, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalTop, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalTop, uvMappings[1]));
                }

                if (visibleFaces[3])
                {
                    // Add the vertices for the BOTTOM face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 3, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftFront, normalBottom, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftBack, normalBottom, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightBack, normalBottom, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftFront, normalBottom, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightBack, normalBottom, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightFront, normalBottom, uvMappings[1]));
                }

                if (visibleFaces[4])
                {
                    // Add the vertices for the LEFT face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 4, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalLeft, uvMappings[1]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftBack, normalLeft, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftFront, normalLeft, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topLeftBack, normalLeft, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmLeftBack, normalLeft, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalLeft, uvMappings[1]));
                }

                if (visibleFaces[5])
                {
                    // Add the vertices for the RIGHT face.
                    Vector2[] uvMappings = GetUVMappingsFor(block.Type, 5, textureSize, blocksInAtlas);
                    _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalRight, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightFront, normalRight, uvMappings[2]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightBack, normalRight, uvMappings[3]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalRight, uvMappings[1]));
                    _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalRight, uvMappings[0]));
                    _vertices.Add(new VertexPositionNormalTexture(btmRightBack, normalRight, uvMappings[3]));
                }

                return _vertices.ToArray();
            }

            return new VertexPositionNormalTexture[0];
        }

```

Screenshot of the problem: http://www.ccoder.co.uk/textures.png

# Answer
Ok i cracked it the problem was in the vertex generation method in several places ...

Firstly ...

```
// Calculate the position of the vertices on the top face.
                Vector3 topLeftFront = position + new Vector3(-blockSize, blockSize, -blockSize);
                Vector3 topLeftBack = position + new Vector3(-blockSize, blockSize, blockSize);
                Vector3 topRightFront = position + new Vector3(blockSize, blockSize, -blockSize);
                Vector3 topRightBack = position + new Vector3(blockSize, blockSize, blockSize);

                // Calculate the position of the vertices on the bottom face.
                Vector3 btmLeftFront = position + new Vector3(-blockSize, -blockSize, -blockSize);
                Vector3 btmLeftBack = position + new Vector3(-blockSize, -blockSize, blockSize);
                Vector3 btmRightFront = position + new Vector3(blockSize, -blockSize, -blockSize);
                Vector3 btmRightBack = position + new Vector3(blockSize, -blockSize, blockSize);

```

lets assume a block size of 1 ... this code generated an actual set of verts that resulted in a block being 2 in size in all dimensions so my odd looking scene was the result of overlapping blocks which in turn caused a sort of "tearing" to occur between blocks with different textures result in each block having a line of screen real estate (ugly to say the least).

I then noticed something was still not right so I Took Jason Coombes advice (given on skype - thanks Jason) and added another set of textures to my atlas which had numbers on them.

Most of the sides looked ok but the top face seemed messed up ... the uv coordinates were setup wrong in here ...

```
       if (visibleFaces[2])
        {
            // Add the vertices for the TOP face.
            Vector2[] uvMappings = GetUVMappingsFor(block.Type, 2, textureSize, blocksInAtlas);
            _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalTop, uvMappings[2]));
            _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalTop, uvMappings[3]));
            _vertices.Add(new VertexPositionNormalTexture(topLeftBack, normalTop, uvMappings[0]));
            _vertices.Add(new VertexPositionNormalTexture(topLeftFront, normalTop, uvMappings[2]));
            _vertices.Add(new VertexPositionNormalTexture(topRightFront, normalTop, uvMappings[3]));
            _vertices.Add(new VertexPositionNormalTexture(topRightBack, normalTop, uvMappings[1]));
        }

```

This resulted in the texture being "twisted" in the middle. It was hard to explain exactly what I was seeing because there were more than 1 problems with it however taking the time to check through all the steps got me there in the end :)

Thanks everyone. Sometimes it's just good to talk about it.
> 0 votes

---
Tags: c#, xna-4.0, voxels, uv-mapping
---