# Question
Title: Looping an object to move between two positions
I've search a bit and tried to find a decent answer to this but have failed majorly. Basically I'm trying to loop an AI object between two points. Heres some of the code I have so far:

```
class Object
{
    Vector3 startPos;
    Vector3 endPos;

    Vector3 curPos;
    Vector3 curVel;
};

struct Vector3
{
    float x;
    float y;
    float z;
}

Start()
{
    startPos = Vector3( 1, 0, 0 );
    endPos = Vector3( -1, 0, 0 );
    curPos = Vector3( 0, 0, 0 )

    Generate();
}

Generate()
{
    // Standard code to generate angular velocity
    // Calculate angle between two points
    // Calculate velocity based on angle
}

Update()
{
    // Add velocity
    curPos += curVel;

    // If the position has reached the end point
    if( curPos == endPos )
    {
        // Reverse movement positions
        Vector3 temp = endPos;
        startPos = endPos;
        endPos = temp;

        // Recalculate velocity
        Generate();
    }
}

```

I'm now stuck, as you can see from the comments, the velocity could take the position of the object to something like (-1.5, 0, 0) which would mean the if statement wouldn't work. For the initial movement, it could be fixed using

```
if( curPos <= endPos )
{
    // Reverse
}

```

However, when I then reverse the positions, problems arise and it won't work. Any ideas?

# Answer
One approach is to use distance as it will always be a positive number so you don't need to account for sign.

When at `startPos`, compute the distance from `startPos` to `endPos` and store this is a float called `distanceToTravel` (or similar). Each tick of `Update()` compute the distance traveled so far (this is `startPos` to `currPos`), call this `distanceTraveledSoFar` (or similar). Then compare `distanceTraveledSoFar` to `distanceToTravel`:

```
if (distanceTraveledSoFar >= distanceToTravel)
{
    // You've arrived!
}

```

A potential optimization is to use distance squared values rather than distance as `sqrt` is relatively costly to call each tick.
> 1 votes

# Answer
Define a function that takes care of not overshooting the target, like this:

```
template<typename T, typename D>
T Approach(T from, T to, D limit)
{
    D diff = Abs(from - to);
    limit = Abs(limit);
    if(diff > limit)
    {
        if(from < to)
            return from + limit;
        else
            return from - limit;
    }
    else
        return to;
};

```

Now replace this

```
curPos += curVel;

```

with

```
curPos = Approach(curPos, endPos, curVel);

```

And you can just check for equality.

**Edit**:
Above works well if the movement is limited and straight forward. But movement is often not that predictable. The alternative is checking for proximity rather than the exact position. This will become necessary if the movement is physics based.

```
// If the position is very near the end point
if((endPos-curPos).length() < 25)
{
    // Reverse movement positions

```
> 0 votes

---
Tags: c++
---


# Question
Title: Shared Object Not saving the level Progress
I am making a flash game in which i have a variable **levelState** that describes the current level in which user has entered I am using **SharedObject** to save the progress but it does not do so first i declred a clas level variable

```
private var levelState:Number = 1;
private var mySaveData:SharedObject = SharedObject.getLocal("levelSave");

```

in the Main function i am checking if it is a first run of the game like below

```
if (mySaveData.data.levelsComplete == null)
    {
        mySaveData.data.levelsComplete = 1;
    }

```

and in a function where the winning condition is checked so that levelState could be increased i am usin this sharedobject to hold the value of levelState

```
if (/*winniing condition*/)
    levelState++;
    mySaveData.data.levelsComplete = levelState;
    mySaveData.flush();
    setNewLevel(levelState);
}

```

but when i play the game clear a level and again run the game it does not start from that level it starts from beginning.

# Answer
> 1 votes
**Solution** Actually in the main function i have to assign the **levelState** the value from the ShredObject . In the first part of the above code i added some lines like this

```
if (mySaveData.data.levelsComplete == null)
{
    mySaveData.data.levelsComplete = 1;
} else {
   levelState = mySaveData.data.levelsComplete
}

```

That **else part** i was missing

---
Tags: flash, actionscript-3, savegame
---


# Question
Title: How do I disassemble a 3x3 transformation matrix into rotation and scaling matrices?
I have a transformation matrix that rotates and scales. Is there any easy way to disassemble it into the original rotation and scaling matrices?

For instance:

```
M = R * S;
// I need f and h such that
R = f(M); S = h(M);

```

# Answer
As long as you're doing only *uniform* scaling, this is easy; you can simply extract each row (or column; it doesn't matter), of the 3x3 matrix. The scale factor will be the length of the row vector. If you normalize each row vector and construct a new matrix from the normalized rows, that will be the rotation part. (If you have a 4x4 matrix, you just do this to the upper-left 3x3 part.)

This can be done because uniform scaling commutes with rotation, and therefore the two can be cleanly separated. In fact, a matrix constructed from any sequence of rotations and uniform scales can be broken down into a single rotation and a single scale.

If you have nonuniform scaling, but it's done along the axes *before* any rotations are applied in the transformation chain, you can also extract that with the same technique as above; you just get the three axial scale factors from the lengths of each of the three rows or columns (depending which convention you use; here, it does matter).

The general case of an arbitrary combination of nonuniform scales and rotations *can't* be decomposed into a single rotation and a single scale, since nonuniform scaling doesn't commute with rotation in general. However, using singular value decomposition, a general linear transformation can be decomposed as a rotation, a nonuniform scale, and another rotation.
> 11 votes

# Answer
You can apply the transformation matrix to a point and calculate the orientation and the scale from it. This of course only works if there are no other transformations than that.

```
Vec2 scale;
Angle rotation;

Vec2 point(0, 1);
point = matrix.apply(point);
scale.Y = point.length();
rotation = AngleBetween(point,   Vec2(0, 1));

Vec2 pointX(1, 0);
pointX = matrix.apply(pointX);
scale.X = pointX.length();

```

Though, it would be better if you just store the parameters alongside with the transformation and just read out that information when needed.
> 2 votes

# Answer
This is what I did. Please comment and vote if it's correct?

I had a 3d transform matrix that both scales and rotates a vector:

I took the vectors : \\$(1, 0, 0); (0, 1, 0); (0, 0, 1)\\$ (let's call them x1, y1, z1) and I multiplied the matrix by those vectors. I then intuitively checked their lengths much like API-Beast suggested.

So I figured the scaling Matrix is:

$$ \begin{pmatrix} Tx1.length & 0 & 0 \\ 0 & Ty1.length & 0 \\ 0 & 0 & Tz1.length \\ \end{pmatrix} $$

I then inverted this matrix (easily)

$$ \begin{pmatrix} \dfrac 1 {Tx1.length} & 0 & 0 \\ 0 & \dfrac 1 {Ty1.length} & 0 \\ 0 & 0 & \dfrac 1 {Tz1.length} \\ \end{pmatrix} $$

And if \\$T = RS\\$ then \\$T(S^-1) = RS(S^-1) = R\\$.
> 0 votes

---
Tags: mathematics, rotation, matrix, scale
---


# Question
Title: When should I clear an auxilliary render target?
I'm using a few different render targets in my game in addition to the back buffer. These other render targets are only used in a few places, for specific tasks.

I'm wondering when I should be clearing them. Right now I clear all of my render targets at the beginning of the frame, and it seems like I'm waiting for all the textures to clear before the rest of the drawing gets underway.

Would it be more efficient to clear these textures later in the frame, when they aren't being used? Is there any hope of the GPU sort of clearing them "on the side" while unrelated rendering is happening? Or are these tasks always sequential and will I always need to wait for clearing?

# Answer
Clear them when you need them cleared.

As discussed in the comments, the performance degradation you are seeing is likely related to the placement of the calls in the relative call stream for the frame, and not specifically the fact that clearing the buffer is "slow" (it should be one of the faster operations available, since implementers know how often it will be called).

But it will take non-zero time, and there's really no point to clearing the buffers until you need to. So, if you are rendering to them every frame, clear them every frame. But if you only render to them once every few frames, you should consider moving to clear to just before the render into that buffer. It's possible this will, itself, have performance implications based on how you are using all the other related graphics objects, including the buffer itself, so you'll need to experiment and verify; perhaps you should clear immediately before, perhaps immediately after you're done using the buffer, and so on.

If there's no measurable performance difference, favor the option that is most logical.
> 1 votes

---
Tags: directx, directx10
---


# Question
Title: How to circle a target at a constant distance
I have an AI ship that stops approaching when it gets within firing range, and starts strafing around its target. The problem is that it doesn't circle its target very well. The following code attempts to do this, and for short periods of time, it's convincing, but as soon as you let it run for ~5-10 seconds, the AI ship drifts out of range of the target and is forced into the approach state again.

```
Vector2 tangent = Vector2.Normalize(new Vector2(TargetVector.Y, -TargetVector.X));
velocity += 0.8f * tangent * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;
velocity += 0.2f * TargetVector * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;

```

The above doesn't work for obvious reasons, so I attempted to bring the target into my frame of reference using the following:

```
Vector2 tangent = new Vector2(TargetVector.Y, -TargetVector.X);
Vector2 asdf = tangent + (velocity * (float)gameTime.ElapsedGameTime.TotalSeconds);
velocity += Vector2.Normalize(asdf) * accelerationMagnitude * (float)gameTime.ElapsedGameTime.TotalSeconds;

```

Here is a quick video on how it behaves using the second method while trying to maintain a firing distance of 350: https://www.youtube.com/watch?v=16Bc46ekJI0 The white line and number indicate the Ship-\>Station vector and distance, and red circles are the weapon ranges.

How do I make my AI ship circle its prey convincingly?

# Answer
> 4 votes
Rather than attempting to calculate acceleration so that the physics system will generate the desired motion, it's probably better to calculate the desired motion directly, like

```
angle += rotationRate * (float)gameTime.ElapsedGameTime.TotalSeconds;
Vector2 desiredPos = new Vector2(radius * cos(angle), radius * sin(angle));

```

You can then apply some type of steering behavior so that the AI ship will attempt to stay on top of `desiredPos`. Or, simply *set* the AI ship's position to `desiredPos` if it's close enough. You can calculate velocity and acceleration by taking derivatives of `desiredPos` if you need them for other reasons (for instance, showing thruster sprites based on acceleration).

If your ship gets too far from the target, you can switch off this behavior; and in the approach phase, you can set `angle` based on the angle your ship is coming in from, so the `desiredPos` will be in the right place when the circling behavior switches on.

# Answer
> 1 votes
Nathan Reed's answer is probably the right solution for you. That said, you could also model the distance constraint you're imposing on the ships and solve for an acceleration that keeps your ship rigidly tethered to its prey, while still allowing you to apply acceleration as you are. This paper shows how to do this at the acceleration level; it's not terribly complicated.

---
Tags: xna, physics
---


# Question
Title: How to rotate an object around a fixed point?
I have a walking stick:

Some information:

* The handle is fixed, it cannot move
* The bottom part can move

Using the mouse click position and mouse movement, how can I rotate this stick with OpenGL?

# Answer
> 2 votes
Generally, to rotate an object you'll want to use a rotation matrix. However, this will rotate your object around its origin - you want to rotate it around the handle.

So, if the handle isn't at the origin, you will want to apply a transformation matrix that moves the stick so that the handle is at the origin, then apply your rotation around the handle, and then possibly apply another transformation to position the stick in the world again.

Now, how you want to rotate your stick is entirely up to you, you could just map x/y movement to the theta/phi angles of a spherical coordinate system.

# Answer
> 0 votes
glPushMatrix();

glTranslatef(250,250,0.0); // 3. Translate to the object's position.

glRotatef(angle,0.0,0.0,1.0); // 2. Rotate the object.

glTranslatef(-250,-250,0.0); // 1. Translate to the origin.

// Draw the object

glPopMatrix();

---
Tags: opengl
---


# Question
Title: Bullets won't shoot out of barrel in top-down shooter
So I am working on a top down shoot and have been stumped on why my bullets refuse to come out of the barrel of the gun. I know about the rotation equation which is

```
x2 = x * cos(theta) - y * sin(theta)
y2 = x * sin(theta) + y * cos(theta)

```

Here is part of my shoot method for my shotgun

```
    float dx = (float) (5 * Math.cos(direction) + 40 * Math.sin(direction));
    float dy = (float) (5 * -Math.sin(direction) + 40 * Math.cos(direction));

    //PlayState.effects.add(new MuzzleFlashEffect(x + dx, y + dy, (float) Math.toDegrees(-direction)));

    for(int i = 0; i < randNum; i++){
        float var = MathUtils.random(-accuracy, accuracy);
        float dir = direction + (float) Math.toRadians(var);
        PlayState.projectiles.add(new Bullet(this, x + dx, y + dy, dir));
    }

    bulletsInClip--;
    lastShot = System.currentTimeMillis();

```

The bullets always tend to shoot out of the left side and I don't have a clue why. The player sprite origin is the center and not the top left but I can't get it shooting out of the barrel.

Can someone explain why this is happening and how I can fix this. I have spent too many hours and losing my sanity.

Thanks in advance!

**EDIT**

Here are some pictures of the character shooting in different directions

**RIGHT**

**LEFT**

**DOWNWARD**

# Answer
Let's see what is happening.

```
float dx = (float) (5 * Math.cos(direction) + 40 * Math.sin(direction));
float dy = (float) (5 * -Math.sin(direction) + 40 * Math.cos(direction));

```

So facing right, dx = 40, so cos(direction) = 0 sin(direction) = 1.

dy = -5 for the same reasons. 0,0 is top left.

This means that direction = pi/2. This is unusual, normally pi/2 means up in java.

Facing down the shots are offset downward and a little left. So cos(direction) = 1, sin(direction) = 0, dx = -5, dy = 40. This means the angle is 0.

So far so good, though the angle is still funny, 0 meaning down.

Facing left it's down and below.

dx = -40, dy = 5. cos(direction) = 0, sin(direction) = -1, so this is -pi/2

Then up, it's greatly to the left and up.

What I would expect given the rest is that direction = pi. sin(direction) = 0, cos(direction) = -1

If that is the case, then you should have dx = -5, dy = -40.

But you have something that looks more like dy = -80, dx = -40.

So what's up?

My first test would be to check what exactly the direction is when you're pointing up.

Then I would watch the values of dx and dy to confirm that they were in fact the things that were screwing up and it wasn't something like your x and y values that were getting offset when you pointed up.

I know there's no way for both cos(x) and sin(x) to return positive numbers, and no way for cos(x) to return something less than -1.

So either something is screwing up the value of dy (like code that isn't shown) or the value of y when you create the bullets is incorrect, or possibly that there's some logic in your bullet constructor that is screwing up the position in that case.

I would look at the bullet constructor to make sure that it's not the one at fault. Finally I would worry about the casts to float. All the trig functions take and return doubles, and conversions to floats can do weird things which might be present elsewhere.
> 2 votes

---
Tags: java, rotation, shooter
---


# Question
Title: Deferred Rendering With Diffuse,Specular, and Normal maps
I have been reading up on deferred rendering and I am trying to implement a renderer using the Sponza atrium model, which can be found here, as my sandbox.Note I am also using OpenGL 3.3 and GLSL. I am loading the model from a Wavefront OBJ file using Assimp. I extract all geometry information including tangents and bitangents. For all the aiMaterials,I extract the following information which essentially comes from the sponza.mtl file.

* Ambient/Diffuse/Specular/Emissive Reflectivity Coefficients(Ka,Kd,Ks,Ke)
* Shininess
* Diffuse Map
* Specular Map
* Normal Map

I understand that I must render vertex attributes such as position ,normals,texture coordinates to textures as well as depth for the second render pass. A lot of resources mention putting colour information into a g-buffer in the initial render pass but do you not require the diffuse,specular and normal maps and therefore lights to determine the fragment colour? I know that doesnt make since sense because lighting should be done in the second render pass.

In terms of normal mapping, do you essentially just pass the tangent,bitangents, and normals into g-buffers and then construct the tangent matrix and apply it to the sampled normal from the normal map.

Ultimately, I would like to know how to incorporate this material information into my deferred renderer.

# Answer
> 2 votes
Each parameter necessary to the final color of a fragment must be saved in the so called "G-Buffer". So you would have one Render Target for each of those parameters: Diffuse, Specular, Normals, Position (or depth), UVs and so on. This is the reason why deferred rendering is so memory intensive. And, in my opinion, it is only viable if the hardware has support for MRT (Multiple Render Targets). Otherwise you would have to do one pass to each of those parameters anyway.

Take a look at the tutorials on OGLDev. These are probably the most popular ones out there. I think you can get a solid understanding of the technique from there.

---
Tags: opengl, glsl, deferred-rendering, deferred-shading
---


title: Parse and iterate over SVG path

text:
# Question
Title: Parse and iterate over SVG path
I need to parse a SVG path expression like

```
m8,295c-4,-292 441,-291 446,-26c5,265 440,263 442,-9

```

and have a way of iterating over it in \[0 ... 1\]. I looked into Apache Batik but it doesn't seem to have this specified function. I also looked at Salamander SVG but in the end the path is a wrapper around java.awt.geometry, which is not ported to android so I can't really use it.

# Answer
> 2 votes
I hammered together the class that I needed using the AnimateMotion classes from Batik to interpolate through the path, it has no dependency with AWT or android. If anyone wants to use it it's in the following repository. The only dependency is libgdx Vector2 that can be easily replaced by any other 2 point class

http://github.com/ibrabeicker/bezier

---
Tags: java, android, libgdx, svg
---


# Question
Title: OpenGL glDisable(GL_TEXTURE_2D) vs glBindTexture(GL_TEXTURE_2D,0)
I would like to ask which one of these is better to use after I finished my texture rendering.

```
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,0)

```

Is there any difference performance-wise?

# Answer
> 11 votes
## These are two fundamentally different things.

### glDisable (GL\_TEXTURE\_2D)

* Disables 2D textures for the active Texture Unit in the ***fixed-function*** OpenGL pipeline.
* In programmable OpenGL (GLSL or the older ARB VP/FP assembly languages), enabling or disabling `GL_TEXTURE_2D` is meaningless.

### glBindTexture (GL\_TEXTURE\_2D,0)

* Binds the ***"default"*** texture to the active Texture Image Unit.
* For all intents and purposes, there is *always* a texture bound to a Texture Image Unit; **0** is just a special-case with an *initially* incomplete set of states, thus complicating ***validation*** (*see below*).

There is a little bit of validation overhead associated with binding any OpenGL resource (GLSL programs and FBOs tend to have the most complicated validation). In general, changing an object binding tends to be more expensive than changing one or two states associated with a bound object.

Therefore, unnecessarily changing the bound texture is inadvisable.

If your intention by binding **0** was simply to *"disable"* a texture, you would be better off setting a ***uniform*** value to communicate this intent to a shader. Uniforms are extremely cheap to set (assuming you do not do something stupid like query their location everytime you set them). Changing a uniform is orders of magnitude quicker than binding a different texture or even worse a different GLSL program.

---

### If you are using fixed-function OpenGL:

* Disabling `GL_TEXTURE_2D` is a better way of approaching this problem.
* Changing bound objects should be done as little as possible.

### If you are using programmable OpenGL:

* Neither of these things make much sense.
* Work your desired behavior into your shaders.

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


# Question
Title: DirectX9 texture flashing or disappearing
I am learning DirectX 9 and I have these test models in my scene and this weird texture flashing happens.

If you look at the bottom of the picture you will see a blue area, that is supposed to be filled with the ground texture I have. So every time I move my camera the ground texture flashes very quickly and parts of it disappear lots of times a second. I know it's not a problem with my video card. What could cause this?

# Answer
> 1 votes
Your problem has nothing to do with texturing. Your are experiencing the ancient problem of Z-Fighting.

This should be caused either by some interpenetrations between your meshes or, less likely, due to very low accuracy of the Z-buffer in your graphics card.

---
Tags: textures, directx9
---


title: Moving a rig by his bones correctly

text:
# Question
Title: Moving a rig by his bones correctly
I created a model and then tried to add armature. But when I'm moving the rig, some of it stays in the place (the mouth), and I don't know why. Anyone know why it could happen and how to fix it?

This is what I did : http://www.mediafire.com/download/fg86hdb82wjit6q/Alien2.blend

These pictures illustrate the problem:
idle pose:
when rotating a bone:

Thank you!!

# Answer
> 1 votes
Your model is not rigged correctly, you need to further weight paint the model. For that you should set the object interaction mode. You can do this in the 3D view's taskbar where you can also switch between object mode/edit mode, etc.
There is also a blender stackexchange now, you should go there if you have further questions, you will have better chances there I imagine.

---
Tags: blender, rigging
---


title: Offline texture mipmap generation

text:
# Question
Title: Offline texture mipmap generation
I want to generate mipmaps for 2D textures as an offline step. My priority is for image quality, execution time is not a concern. The images will, naturally, always be halved and will always be powers-of-2.

I've found this fine article on the subject, which was helpful, but I don't have much knowledge on filtering, so I'm not very sure where to start.

I'm looking for algorithms and hopefully some sample implementations that I can base myself on. Also, using a third party library is an option, as long as it is open source and portable C or C++.

Any help is appreciated.

# Answer
I have settled with the NVidia Texture Tools library. It has a lot of good texture filters plus other things that might be useful in the future, such as GPU accelerated DXT texture compression. The library is Open Source and released under the MIT licence, which is very unrestrictive.

Thanks for all the replies and comments.
> 3 votes

# Answer
You might look into ImageMagick. It's open-source and contains code for resampling images using a variety of filters including Lanczos, Kaiser, Gaussian, etc. It can be used as a library linked into your code, and/or as a set of command-line tools you can call from shell scripts and suchlike.
> 7 votes

---
Tags: c++, textures, rendering, mipmaps
---


title: What makes a game look "good"?

text:
# Question
Title: What makes a game look "good"?
I am working on a 3D space game using OpenGL and C++ and I am planning to focus on giving the game modern, eye-catching graphics, but the more I think of it the more I realise I don't really know what makes graphics "good". Sure, I can go and play some well known AAA games and bask in the amazingly put together graphics, but I don't really know *how* the graphics looks good. (this is why I consider games to be an art!)

This is what I can think of now:

* High quality textures
* High quality models
* A good lighting model
* Bumpmapping + specularity mapping
* High quality UI, if applicable
* A wealth of not-overdone posteffects

I'm asking here in the hope of an experienced game developer who has produced games and know how they work inside and out can explain some techniques that warrant a game's graphics to look "good", and some not-well-known quirky tips. That'd be awesome.

Thanks!

# Answer
> 59 votes
This may sound surprising on the face of it, but actually isn't: The higher you make the graphical resolution, polygon count, colour depth and whatnot, the easier it is for your game to look terrible. The crucial component in enjoying an audio-visual artwork is *the mind*: Your mind *knows* that you are looking at a flat computer screen. You are willing to accept that and not be bothered by it, and instead *construct* the mental image of the world that is being portrayed in your mind.

Now, if the visuals are highly stylized, sketchy or pixelated, the mind is attuned to that, and factors that out as "background" -- it doesn't get in the way of the mental construction of the scene. That's why a game like the original Monkey Island, with its 320x200 resolution, can get away with a door animation that consists of only two frames: We already accept that the scene is a pirate tavern, and we have no problem accepting that the door just opened.

But if you have a high resolution and want to go for photo-realism, then the mental *expectations* go up dramatically. It's no longer obvious that we're faced with visual fiction, and the mind does a lot less of the internal reconstruction work. The more realistic the input, the less the imagination is at work filling in the details. The (possibly unintended) side effect is that you as the designer must now go and *produce* all the details in actual graphics and 3D modelling. You've successfully un-outsourced the imaginative work from your consumer and signed your graphics design team on to the task.

An ill-fitting visual style and appeal can be a *huge* problem. If you ever felt that a game looks more like an Excel spreadsheet than a computer game, you know that the visual design has gone wrong.

As a consequence, you shouldn't try to aim for *realism* as much as for a coherent visual style. Realism doesn't give you immersion. On the contrary, it makes it vastly more difficult to achieve immersion. By contrast, having a unique, memorable visual style may be *far* simpler to produce and may well make your game recognizable, memorable and fun.

# Answer
> 36 votes
You are focusing a lot on the technical aspects, but you seem to totally forget about something which is much more important than any graphic engine features:

The design!

* Models and textures which have an unique look, but still follow consistent themes
* Scenarios which look diverse, but still fit together
* Well-chosen color palettes which support the mood of the game
* Lighting that is used to set and enhance the mood of each scenario

The player won't care about hyperlinear-ultra-multipass-highdef-anisotropic-super-occlusion-dynamic-parallel-megashader-rendering, when you use it for ugly, uncreative models in a boring environment.

On the other hand, look at all the independent game studios which create truly beautiful games with minimalistic graphic engines.

# Answer
> 12 votes
Cohesion? I think that's most crucial. A certain technology certainly isn't going to make a game look good, there are countless examples of games with, in its time, state of the art tech, but they didn't look good.

When you say "high quality", what defines a quality model is subjective.

If you had written "high resolution textures" or "high polygon-count models" I would say no, that's not necessary, and not a sign of quality.

Most of this will come down to artistic ability, working within your constraints and still making something look good is truly art.

# Answer
> 7 votes
Some of the most gorgeous games do not adhere to any singular principle of what's 'good' and 'not good'. From what I've seen in both AAA and indie game space is an extreme amount of focus placed on style, consistency and theme. To elaborate:

This covers anything from the color palette chosen, level of detail, the choice between richly rendered 3-d assets to painstaking pixel-art. When you see an out-of-context screenshot from games you find visually striking, you can often recognize the game immediately. This is because the artists responsible took the time not only to define a visual style in which to create everything, but have refined it to a point where it can be nothing else besides what it is. On the flip side, games that have a muddy or nonspecific visual style do not strike the same chords with us visually.

Examples of striking visual style:

* Braid (2-d pixel/painted art and backdrops. Visible brushwork on both canvas and characters. Fluid yet simple animation. Saturated colors that tend to bleed into one another, contributing to the 'dreamy' feeling of the levels.)
* Borderlands (3-d with painted textures, hard silhouettes/outlines, exaggerated proportions, grimy and dusty metallic surfaces, and lots of harsh lighting)
* Fez (2-d pixel art. A very mild color palette that balances vibrant color with pastels and muted primaries. Geometric blocks/tiles, and lots of symmetry)
* World of Warcraft (Simplistic but extremely refined 3-d models with richly painted textures. A clear distinction between color palettes in reference to different zones, cities, racial consistencies and themes of building construction and apparel/accessories. Large feet/shoulders, distinctive posture and excessive attention paid to communicating through body language)

In order to achieve these kind of results, an artist needs to be able to envision not only the end-vision of the style in question, but how it can be used to complement gameplay and add to the user experience. The less artists at your disposal, the more diverse a skillset they will require. A single artist creating the visual assets for a 3d title will need to have a firm grasp of the following and more:

* Construction and animation of 3-d models
* 2d image projection/texture mapping creation
* An understanding of architectural style and settings
* The ability to build a 'scene' from foreground to background and everything in-between
* An understanding of setting, mood and how to extract the desired emotional impact of both the world and the characters that live in it.

I am only scratching the surface here, but that's because to attempt to apply something so varied as art into silos of 'good' and 'bad' is complicated.

# Answer
> 3 votes
You need skilled artists.

All the technical stuff can help a bit to make the work of the artists better appreciable, but the truth is that you can get a perfectly capable rendering engine for free or very cheap, and a better engine will only increase the quality marginally.

# Answer
> 2 votes
To begin, I think it's important to point out the obvious. A good looking game does not necessarily mean it has *good* graphics. And one doesn't have to look any further than Nintendo to see how it is done.

Take **Wii Sports** for example. One of the most successful games of our generation and it has horrible graphics on a purely technical level. However, the look of the game is by all accounts a tremendous success. So what did it do right?

In my personal opinion, it's because the **target demographic** interested in the game bought into its presentation. They expected a certain product when they picked up the title, and the title delivered on their expectations if not surpassing them. To me, that's the fundamental point. *It has to touch the player somehow and how to go about achieving this will depend on who you are targeting.*

That's the reason when I picked up **Playstation Allstars** for my PS3 recently, I was disappointed by the "graphics". I was expecting it to look more like **Smash Bros**, but instead everything looked quite cold and bland in comparison. Not only did it not meet my graphical expectations, it did not excite any new emotions, so I just ended up being disappointed. (To be fair, the gameplay is fun).

I would also use this argument with **Diablo 3**. Technically a fabulous looking game in nearly every aspect. However, it still disappointed many core fans because it changed the dark tones that were so prevalent in the first and second iteration.

Good graphics is just like any other art form. It's more than the sum of its parts and has to touch on the player's emotions at that specific point in time. Thus, I'd argue that there is no secret sauce to it because our tastes are constantly changing over time. What looks good today may not look so good tomorrow, yet looks good again the day after that.

# Answer
> 1 votes
A game with lambert-shaded polygons or wireframe models can look good! All kinds of games have looked good, historically, and still do.

An old arcade machine running Battlezone looks good.

The main thing is for everything to be robust, highly playable and not exhibit any flicker or tearing (use double buffering or blitting of whole frames from an off-screen buffer, ideally synchronized to the vertical retrace of the display device).

# Answer
> 0 votes
Basically you have 2 things:

1) Art

2) Effects

**Art** is all about just putting the world exactly as the artist envisioned it. This means having a killer artist who can design a cohesive world with fantastic looking textures. As long as you have enough texture memory, you can make a scene exactly as the artist envisions it / authors it in a 3d modelling package.

**Effects**. These are the real-time effects you lay on top of the already awesome art, like your standard particle engines and bloom effects and better looking execution of the artists vision using things like order-independent transparency.

# Answer
> 0 votes
Consistency.

It's not the only thing that matters, of course, but it's very jarring if there's not a consistent point-of-view throughout a game. People have made great games with all level of graphic quality. Look at Kingdom of Loathing; a great web-based game that is consistent in its graphic quality (low) and humor (even lower). World of Warcraft has a graphic style that has been consistent since the old RTS games (at least from Warcraft II, the original had a very different style). Braid had that beautiful hand-drawn painting style.

In other words, people may buy into your vision or they may not, but there should be a consistent vision.

# Answer
> -3 votes
1) The models

2) Clearly and decidedly SHADING. Programing crazy shaders will give you exeptionnal graphics.

---
Tags: opengl, 3d, graphics
---


# Question
Title: In Slick2D, how can I generate a 2D platformer map from an image?
I'm fairly new to game development. I've been messing around with Slick2D. My map consists of rectangular objects. I want to use an image to represent my map, similar to this:

How could I generate a level from that image? As I said, I'm new to game development and am not familiar with terminology or procedures.

Bonus question: How could I also generate non-rectangular game objects from it?

# Answer
Though the idea of what to *do* with your data is vague, reading image data and operating on it is straightforward. See the `ImageBuffer.getRGBA` docs.

> `public byte[] getRGBA()`
> Retrieve the raw data stored within the image buffer
> **Returns:** The raw data in RGBA packed format from within the image buffer

You have other options as well, such as `ImageIOImageData.loadImage`

The important part is, load the image, get the data. Once you have that byte array (as well as some other handy info from `getHeight()` and `getWidth`) iterate over it and generate your level geography. The options for exactly what you generate are infinite.
> 2 votes

---
Tags: java, tilemap, slick, file-format
---


# Question
Title: How can I support different screen resolutions without scaling the sprites?
I already tried to support different screen resolutions with scaling the sprites. But if I scale my sprites from 800x480 to 1920x1080 pixel, then the sprites look blurry. I want to use different sprites for each resolution to avoid the blurry effect.

How can my game choose the right sprite for each resolution? How can I do that?

How can I calculate the right measures for every sprite? For example, I use a 64x25 pixel sprite with a 800x480 pixel resolution. If I change the resolution to 1280x720, what should then be the measures of the sprite?

Can I calculate the measures like this?

sprite measures(1280x720): Width = 1.5f\*64= 96, Height = 1.5fx25= 37,5

Should I round up or round down the height(37,5 pixel) of the sprite?

I create a Windows Phone game with Monogame, and I want to support every resolution from 800x480 to 1920x1080 pixel without scaling.

# Answer
> 4 votes
What you're attempting to do is not a common strategy (in fact, I don't think it's even a *rare* strategy), for several reasons:

* There are at least ten common phone resolutions between those you mentioned (http://www.sven.de/dpi/)
* Phone/tablet aspect ratios vary from 3:2 to 4:3 to 5:3 to 16:9. Will you also make wider and narrower sprites to accomodate for these variations? Will you make the screen wider or narrower?
* The very problem you mentioned - if you downscale and the numbers are not even, what do you do?

I will ask you to reconsider your position. Drawing the same art ten times just so it's not 'blurry' will force you to either spend a lot (and I mean a lot) of time on the art or rush it and have the same issue with quality. What if you have to redraw an asset?

More common strategies to deal with this issue are:

* Draw the sprites in a sufficiently high scale that they can be downscaled for all other resolutions
* reduce blurring by employing a harsher filter like bilinear or point, or shaders
* Upscale art by exactly 2x or 3x, padding the screen sides as appropriate

Now, the equations. Keep in mind I advised you repeatedly to not use them.

```
SpriteWidth = OldSpriteWidth * NewScreenWidth / OldScreenWidth
SpriteHeight = OldSpriteHeight * NewScreenHeight / OldScreenHeight

```

If you must, round up rather than down, as overlapping sprites is better than sprites with a gap between them.

# Answer
> 0 votes
Stop thinking pixels and start thinking abstract units.

Imagine that a screen is 100 units wide, and the art style and approach of your game dictates that the sprite should be 1/20th the screen width. Only then do you actually start thinking pixels.

Only then do you start thinking about artwork pixel dimensions. And specifically, think in terms of scaling DOWN your artwork, not up. Don't take little pictures, blow them up, and make them blurry. DO take big pictures and scale them down, so you never lose detail on scaling.

That said, it's not always just about scaling down. I'm going to point to a previous answer I gave at How do I scale down pixel art? that covers basically what I'd say about that.

Can you make a perfect set of images for every resolution you'll encounter? Yes, in fact this is the best approach IMO as you can optimize them for each resolution. But it's not the most realistic approach. Maybe this makes your game too big, you don't have the resources to create all the artwork, etc. But what you probably can do is create a set of 2-4 versions of your art at different resolutions. Create them to be optimal for what you think are the most common dimensions you'll see. And then for the ones they aren't perfect for, pick the appropriate one and scale it to what it should be.

---
Tags: xna, c#, windows-phone-8
---


# Question
Title: Unity 2D camera drifts from player as speed increases
I have a dilemma that I did not have in XNA before porting my game to Unity.

First-- my goal is to mimic Super Mario World 2's camera tracking in x. The camera tracks to 1 block ahead of the player, to the left or right, depending on the direction, even if the player stops moving during the camera tracking process, otherwise I would simply make the camera a child of the character and then be done.

As the speed of my character increases, the camera drags behind. The distance (lag) between the camera and the player increases with speed, but catches up instantly when the player stops moving. I figure this is because the FixedUpdate call is somehow getting the last player position from my controller script.

This did not occur in my XNA project, and the algorithms are essentially the same.

```
cameraTargetX = position.transform.x - margin;

```

in this case the margin would be +2 blocks or -2 blocks depending on direction. Even if I get input for movement into fixed update in my player script, I still get the same delay amount. Is there a way to essentially lock the camera to a position directly in front of or behind the player without gradual delay?

If one could point me to an example of a detailed or elaborate 2D platformer with similar camera controls, that would be much appreciated since the Unity 2D example platformer's camera script is really nothing like what I'm trying to do here.

# Answer
> 2 votes
Update the camera position in the `LateUpdate` method. This will account for the position of the character after it has moved.

When updating in fixed update or in update, the position of the camera is being set to the position of the character before it's moved. This means that the more it moves per frame (its speed), the farther behind it lags.

---
Tags: 2d, unity, camera, platformer
---


title: Using this.GameObject

text:
# Question
Title: Using this.GameObject
I once read (I actually don't remember where, I'm looking for it) that using `this.GameObject` to call the script owner is a **very bad** practice.

I believe it has to do with some sort of *information hiding*, but I couldn't figure out why. What are the disadvantages with this? Is there a best-practice to achieve the result?

# Answer
> 4 votes
It is not a bad practice.

From a point of view of a component, `this.gameObject` will always lead to a valid gameObject:

> A component is always attached to a game object. - reference

That is, component cannot live without one. With `GetComponent<Type>()` there could be no component at all, so you should always check it or you could get crash caused by `NullPointerReference`.

The only bad practises about `gameObject`/`transform`/`components` getters are connected with using them heavily, multiple times on every update. Then you could consider some caching mechanism, for better performance results. See this question.

EDIT: It seems like caching `gameObject` shouldn't make any improvements, but there is a speed gain by caching `components` (and yes, `transform` is a `component`). However, this stuff was also slower in previous Unity releases.

There is some useful time measured data comparison: link.

# Answer
> 2 votes
Bad practice, no. However, as with any reference, you have to be careful with it. Even though using it in general isn't bad practice, people can still find a way to use it in a bad practice way. Typically, `this.gameObject` is going to be a valid reference for as long as the script accessing it exists. Since the script is attached to the GameObject, it is also removed when the GameObject is.

Things to look out for:

* Expecting the same composition of every gameobject. For example, using `this.gameObject.GetComponent` to access a component, without testing if the component exists on the gameobject this script is currently attached to. The component based design of Unity means the script you're writing can be attached to any game object.
* Ensuring that the `gameObject` isn't missing, this can happen when destroying the game object, and still trying to access it, producing a MissingReferenceException exception. Typically this happens in other scripts keeping references to the `gameObject` of a different script.

---
Tags: unity
---


# Question
Title: How frequently do my game server need to message the client?
I am writing a game-server and a game-client. In the client there is a game loop that has a delay of ~16ms (because that would be nearly 60fps). All the logic is at the time handled at server side so I need to send the latest frame to the client every 16 ms. Is this a good solution? I know that I probably have to do some game logic at client side just to smooth things out but this is an early version.

Is it possible to make the server send frames to the client each 16ms? Each client is handled in different threads (or actors, as the server is written in Erlang).

# Answer
> 1 votes
It's a question you must answer yourself, depending of what do you send.

In **TCP/IP**, you can send any kind of information, your client will get it (until it is wired), but the protocol check takes some time, resulting in a lag when you have a low band-width.

In **UDP**, you just get rid of all the checks, so you have the max speed of transfert (less lag). But some data could be lost and never be fetched.

You must first know what kind of information you need to send, their priority, and if they are critic or not.

You may be able to sent at ~16ms and have a kind of smooth moves, without interpolating or applying a velocity, but you'll certainly not reach 60 packets by second and you will have your entities acting like jumping between positions.

---
Tags: networking
---


title: Can't create "hero walking" animation

text:
# Question
Title: Can't create "hero walking" animation
I'm creating a Fez-based HTML5 Canvas game and animating my hero image using sprite sheets. The problem is that I can't create the animation of the hero walking, don't matter how much I try, the output is a weird animation that looks like the hero is just shaking its legs. Can someone help me? You don't need to create the sprite sheet for me if you don't want, just show me what's the correct leg position. I'll post the game link in a comment because I can't post more than two links.

Note that the "hero's legs" are compound by 3 pixels each, that are 2x up scaled.

**Here is the sprite sheet:**

the walking animation is compound by the 6 first frames.

**EDIT: If you fall in the demonstration, open the console, type `localStorage.x = localStorage.y = 0;` and then reload the page immediately to return to the starting point.**

# Answer
Regardless of the level of details and the number of pixels you have, you must start with a thorough understanding on how walking works. If your character looks like shaking its legs, it probably because, that's all you drew : shaking its legs.

Just search "Walk cycle" with google image and you'll find plenty of examples. Here is a little example of what I would do with yours, where the knee is green, the upper leg is yellow and the lower leg is orange.

It is of course improvable.
> 9 votes

---
Tags: html5, spritesheet, pixel-art
---


# Question
Title: How to set LinearVelocity exactly in onSceneTouchEvent?
I'm beginner in Android programming. And i use AndEngine GLS2 with Body and AnimatedSprite.

I have a object ball and i want to move it to follow my hand. This is description for my idea:

And my code:

```
@Override
public boolean onSceneTouchEvent(final Scene pScene,
            final TouchEvent pSceneTouchEvent) {
     ballObject.getBodyball().setLinearVelocity(
                    new Vector2(pX, pY));
}

```

How to get exactly variables:`pX`, `pY` ?

# Answer
> 1 votes
This is a simple math. First you find the vector between those two points. Then create a vector (use vector pool) from it. Let's say your touch coordinates are \[p1x, p1y\] and the up coordinates are \[p2x, p2y\]:

```
dx = p2x - p1x;
dy = p2y - p1y;

Vector2 v = Vector2Pool.obtain(dx, dy);

```

You can normalize it to get the same speed everytime. Simply call:

```
v.nor();

```

Then you can set desired speed by:

```
v.mul(scalar);

```

Where scalar is a constant to make it go faster or slower. See the Vector2 class for more.

---
Tags: box2d, vector, andengine, scene
---


# Question
Title: How does GL_INT_2_10_10_10_REV work for color data?
Can anybody tell me how exactly to use `GL_INT_2_10_10_10_REV` as type parameter in `glVertexAttribPointer()`?

I am trying to pass color values using this type. What is the significance of "REV" suffix in this type? Does it require any special treatment in the shaders?

# Answer
`GL_INT_2_10_10_10_REV` is a packed integer data type. Elements of this type in a buffer need 32 bits of space, with the Z, Y, and X (or B, G and R) components packed respectively into ten bit chunks starting at the low bits (that is, Z is bits 0 through 9, Y is bits 10 through 19, et cetera). The W (or A) component is stored in the high two bits (30 and 31).

The "REV" suffix refers to the fact that the data is "reversed," because the Z component is stored in the least significant bits.

This format allows higher precision in the XYZ/RGB channels at the cost of precision in the W/A channel. The pipeline will unpack the channel data and apply normalization back to `[-1, 1]` (`[0, 1]` for the unsigned variant) if you ask for it (using the `normalized` parameter of `glVertexAttribPointer`). Other than that, and deciding in your shaders to accept them as normalized floating point values or their original fixed-point integer values, they should not require special handling.
> 4 votes

---
Tags: opengl, glsl
---


# Question
Title: How can I ensure my Collada model fits on an iPhone screen?
Hi I am new to game development. I see many examples and tried myself like displaying triangle, cube etc. Now I am looking to render a Collada object. So I created a Collada object using Google Sketch up and trying to render that now. But the thing I am not understanding is, in all examples the vertices are between -1.0 and +1.0 values. But when I looked into that Collada file, the vertices were ranging from -30.0 to 90.0. I know any vertices greater than 1.0 will not display on iPhone. So can you pleas tell my the secret behind converting Object coordinate to normalized vector coordinate?

My previous triangle defined as

```
struct Vertex{

    float Position[3];
    float Color[4];
};
const Vertex Vertices[] = {
    {{-0.5, -0.866}, {1, 1, 0.5f, 1}},
    {{0.5, -0.866}, {1, 1, 0.5, 1}},
    {{0, 1}, {1, 1, 0.5, 1}},
    {{-0.5, -0.866}, {0.5f, 0.5f, 0.5f}},
    {{0.5, -0.866}, {0.5f, 0.5f, 0.5f}},
    {{0, -0.4f}, {0.5f, 0.5f, 0.5f}},
};

```

And now triangle from collada is

```
const Vertex Vertices[] = {
    {{39.4202092, 90.1263924, 0.0000000}, {1, 1, 0.5f, 1}},
    {{-20.2205588, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 176.3763924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 176.3763924, 0.0000000}, {1, 1, 0.5, 1}},
    {{-20.2205588, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
    {{39.4202092, 90.1263924, 0.0000000}, {1, 1, 0.5, 1}},
};

```

# Answer
> 3 votes
By default, if you simply pass untransformed vertex data directly to the GPU via OpenGL, the visible extents of the screen are from -1 to 1 along both axes. This is true of any OpenGL device, not just the iPhone. Also true of any OpenGL device (including the iPhone) is that you can then adjust OpenGL state (the viewport, the transformation matrices, et cetera) to allow you to see any range of vertex coordinates just fine.

Your statement that "any vertices greater than 1.0 will not display on iPhone" is *quite false*.

You should familiarize yourself with the OpenGL transformation pipeline and configure your viewport and projection matrices accordingly to allow you to see what you need to see in your scene. You probably want to configure your view matrix such that your camera is pulled back at least 90 units from the origin, though, since that appears to be the largest extent of your model.

---
Tags: opengl, ios, collada
---


# Question
Title: Are SharpDX's ContextDirect2D methods different from XNA's SpriteBatch?
I'm migrating from XNA to SharpDX in Win8. I noticed this `DrawBitmap` call in one of the samples.

Is this different in some shape, way or form from XNA's `SpriteBatch`?

# Answer
> 1 votes
Yes, they are absolutely different.

The SharpDX method you linked to is a wrapper around the native Direct2D `DrawBitmap` methods; SharpDX is primarily just an interoperability API that provides a wrapper around native functions (excluding it's "toolkit" APIs).

XNA's `SpriteBatch` is a high-level wrapper around Direct3D drawing primitives (vertex buffers, textures, shaders) that provides an easy way to draw sprites.

You can use both interfaces to draw 2D sprites on a screen. Used properly you can probably achieve performance parity. However, they are not interchangeable interfaces.

---
Tags: xna, spritebatch, sharpdx
---


# Question
Title: What should I do when a VBO becomes too large in OpenGL?
Currently I have one buffer for my vertex data and one buffer for normals data. I fill them and then pass them to OpenGL for rendering.

The problem is when I load too large mesh file like "Lucy" from Stanford

The program stops responding or the computer freezes. I allocate my buffers like that:

```
Vector* vertData = new Vector[numVertices];
// then fill the array with data

```

where `numVertices = 14 027 872` in this case. That allocation doesn't throw bad\_alloc exception so I guess there is nothing wrong with the allocation of memory.

I am testing the program on a x64 windows 7 platform with 4GB RAM and GTX 470 which has 1280MB of memory. Windows task managers shows that the program uses about 2GB ram when I run it.

Note that when I choose to render not all the voxels of the mesh - every 2nd for example, then I have no problems. Maybe the GPU runs out of memory and that's why the program hangs ?

Shoud I split my mesh data into more vertex/normal buffers and then pass them to OpenGL one at a time or there is a better way to do this ?

# Answer
Generally, to render extremely large meshes you want to subdivide the data into smaller, separate meshes and render each of those individually.

This can be useful to alleviate memory pressure (although it won't always do so, in practice), but it also allows you to perform some culling on the large geometry to avoid bothering rendering huge chunks of geometry that are not, for example, visible.

Note that you probably don't want to just split the buffer by taking the "first N" vertices followed by the "next N" vertices and so on, as in general this will produce a subset of vertices that isn't logically grouped well for culling. You'll have to load the entire set and intelligently subdivide it, perhaps into a 3D spatial partitioning structure like an octree.

(The reason this doesn't always alleviate memory concerns is you still need to keep the data somewhere on the GPU if you want to be able to quickly render it, and that might actually introduce more memory pressure due to the small per-buffer overhead. You can evict things onto the CPU but then you start trading on the performance cost of resubmitting the geometry when you need to render it, and potentially fragmenting the GPU's memory space, and so on.)
> 6 votes

---
Tags: opengl, c++, rendering, vbo, mesh
---


# Question
Title: Best Way to Render Multiple Lights with Deferred Rendering and GLSL
So I've implemented deferred rendering in GLSL and OpenGL for my game engine. I want to blend together multiple lights, but the performance is a bit sub-par. How I'm doing it now is the following:

1. Render all the objects in the scene to a G-buffer storing the position, color and normals
2. Take that data and render a fullscreen quad for the sun.
3. Enable additive blending with glEnable(GL\_BLEND) and glBlendFunc(GL\_SRC\_ALPHA, GL\_ONE)
4. For ever additional light in the scene render a fullscreen quad and send the shader all the data for each light.

The lighting looks great, but the performance is bad. I have been under the impression that deferred rendering allows for very little performance loss when rendering additional lights, and it is possible to render a few thousand lights with relatively little performance hit. Im sure the way Im doing this isn't efficient at all, so I need a bit of input. The first thing that comes to mind is making it so I don't have to blend so many quads and just make a loop in the shader and only render 1 extra quad. I store all my light data in structs, and the only way I've seen to pass structs to GLSL is by setting each individual variable using `glUniform`.

Here is my current code:

```
void World::renderWorldAndLight()
    {
        //first thing we need to do is render the sun's shadow.
        if (Lighting.Sun.needsShadowUpdate == true)
        {
            Lighting.setupDepthImage();
            //render all the objects.
            for (int i = 0; i < objects.size(); i++)
                {
                    Lighting.renderLightPos(&Lighting.Sun);
                    objects[i].renderObjectForDepth();
                }
            Lighting.Sun.needsShadowUpdate = false;
        }

        //render the rest of the light shadows

        //reder the Gbuffer

        glBindFramebuffer(GL_FRAMEBUFFER, Lighting.gbuffer.frameBuffer);
        GLenum buffers[] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3};
        glDrawBuffers(4, buffers);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glClearColor(0, 0, 0, 0);
        for (int i = 0; i < objects.size(); i++)
            objects[i].renderObjectWithProgram(Lighting.gbufferShader);

        //now we have the gbuffer, lets render the sun
        glBindFramebuffer(GL_FRAMEBUFFER, 0);

        glLoadIdentity();
        //render the buffers for debugging
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0, ENGINE_WIDTH, ENGINE_HEIGHT, 0, -1, 1);
        glMatrixMode(GL_MODELVIEW);

        glDisable(GL_CULL_FACE);
        //glDisable(GL_BLEND);

        //render the full screen quad for the sun

        glUseProgram(Lighting.sunShader);

        glUniform1i(glGetUniformLocation(Lighting.sunShader,"normalMap"),0);
        glUniform1i(glGetUniformLocation(Lighting.sunShader,"albedoMap"),1);
        glUniform1i(glGetUniformLocation(Lighting.sunShader,"positionMap"),2);
        glUniform1i(glGetUniformLocation(Lighting.sunShader,"shadowMap"),3);
        glUniform3fv(glGetUniformLocation(Lighting.sunShader,"sunPos"), 1, &glm::vec3(-Lighting.Sun.position.x,-Lighting.Sun.position.y,-Lighting.Sun.position.z)[0]);
        glUniformMatrix4fv(glGetUniformLocation(Lighting.sunShader, "shadowMatrix"), 1, GL_FALSE, &Lighting.Sun.lightMatrix[0][0]);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, Lighting.gbuffer.textures[1]);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, Lighting.gbuffer.textures[2]);
        glActiveTexture(GL_TEXTURE2);
        glBindTexture(GL_TEXTURE_2D, Lighting.gbuffer.textures[0]);
        glActiveTexture(GL_TEXTURE3);
        glBindTexture(GL_TEXTURE_2D, Lighting.sunlight.depth);

        glBindFramebuffer(GL_FRAMEBUFFER, 0);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBegin(GL_QUADS);
        glTexCoord2f(0, 1);
        glVertex2f(0, 0);
        glTexCoord2f(1, 1);
        glVertex2f(ENGINE_WIDTH, 0);
        glTexCoord2f(1, 0);
        glVertex2f(ENGINE_WIDTH, ENGINE_HEIGHT);
        glTexCoord2f(0, 0);
        glVertex2f(0, ENGINE_HEIGHT);
        glEnd();

        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE);
        glUseProgram(Lighting.lightShader);

        glUniform1i(glGetUniformLocation(Lighting.lightShader,"normalMap"),0);
        glUniform1i(glGetUniformLocation(Lighting.lightShader,"albedoMap"),1);
        glUniform1i(glGetUniformLocation(Lighting.lightShader,"positionMap"),2);

        glDisable(GL_DEPTH_TEST);

        for (int i = 0; i < Lighting.Lights.size(); i++)
        {

            glUniform3fv(glGetUniformLocation(Lighting.lightShader,"light"), 1, &Lighting.Lights[i].position[0]);
            glUniform3fv(glGetUniformLocation(Lighting.lightShader,"lightcolor"), 1, &Lighting.Lights[i].color[0]);

            glBegin(GL_QUADS);
            glTexCoord2f(0, 1);
            glVertex2f(0, 0);
            glTexCoord2f(1, 1);
            glVertex2f(ENGINE_WIDTH, 0);
            glTexCoord2f(1, 0);
            glVertex2f(ENGINE_WIDTH, ENGINE_HEIGHT);
            glTexCoord2f(0, 0);
            glVertex2f(0, ENGINE_HEIGHT);
            glEnd();

        }
        glEnable(GL_DEPTH_TEST);
    }

```

If there is any information, tips, tricks advice, it would be greatly appreciated. Thanks.

# Answer
> 2 votes
One thing you should avoid for sure is to query the uniform locations every frame with `glGetUniformLocation`. This might be hurting the performance a little bit. Cache the locations in any data structure of your choice or plain variables once the shader program is created.

Also you've mentioned that for each light a fullscreen quad is drawn. This is likely to be the main frame-rate killer, because you are probably wasting a lot of fragment processing. Imagine that you have a point light that is affecting half of the screen. 50% of the fragments being processed are not going to impact the visual appearence of the scene, but they are still being processed all the way.

One approach to tackle this is to apply a scissor testing to the lights bounds and 'cull' the area affected to minimize wasted fragments. Eric Lengyel discusses an algorithm for a similar use with stencil-shadows in here. The same algo can be applied in your case. This article is also presented in his book. I recommend you take a look.

---
Tags: deferred-rendering, blending
---


title: Jagged text + additive blend in openGL

text:
# Question
Title: Jagged text + additive blend in openGL
I am having some trouble understanding how openGL blend modes work. At first I was using glBlendFunc(GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA) and it all looked fine except that I couldn't use any additive glowing effects simultaneously without changing blend modes all the time. So I was advised to use
glBlendFunc(GL\_ONE, GL\_ONE\_MINUS\_SRC\_ALPHA) and textures with premultiplied alpha and now both additive and "normal" textures appear fine except that for some reason some textures have slightly jagged/thick outlines. I found that this only happens to images that have *semi-transparent pixels* but I'm not sure why.

This is an example of anti-aliased text with this kind of outline. The first is how it used to look and how I want it to look and the second is how it looks with the mode I'm trying to use. I don't want its color blended with the background. Is what I'm asking possible?

# Answer
> 1 votes
You are now using blending factors which assume pre-multiplied alpha (usually a good idea), but some of the textures don't have pre-multiplied alpha. You can either:

1. Persuade your image editor to multiply your colour channels by the alpha channel (it may then not display properly in the editor), or otherwise pre-process your image files to the same effect.
2. Multiply the colour channels by the alpha channel when you load the image.
3. Multiply the colour channels by the alpha channel in the fragment shader.
4. Switch to your old blending factors when using those textures

---
Tags: opengl, lwjgl, alpha-blending
---


title: What library for octrees or kd-trees?

text:
# Question
Title: What library for octrees or kd-trees?
Are there any robust performant libraries for indexing objects?

Objects would have bounds themselves, rather than being represented by points; and an object could therefore be in more than one compartment if the index divides things in fixed sized partitions.

It would need frustum culling and visiting objects hit by a ray as well as neighbourhood searches.

I can find lots of articles showing the math for the component parts, often as algebra rather than simple C, but nothing that puts it all together (apart from perhaps Ogre, although apparently PyOrge doesn't expose the octree). Surely hobby game makers don't all have to make their own spartial indices?

(I am sitting down writing my own sphere-sphere, sphere-ray, ray-aabb, cone-aabb, cone-fustrum, aabb-fustrum and octree implementation; surely there is a better way i.e. someone has already done this and make a nice package?!?!)

(Python or C/C++ w/bindings preferred)

# Answer
> 10 votes
> Surely hobby game makers don't all have to make their own octrees?

Unless they are using something larger (like Ogre, or another physics/rendering engine), many do. An octree is a fairly simple structure to implement, and there's a lot of tradeoffs:

* Is the octree intrusive or not? If it's intrusive you get better cache performance, but larger structures.
* If it's not intrusive, does it store pointers or some kind of safe handle?
* Is it stored flat or with child pointers?
* How type-safe is it? If it uses templates, it'll be a lot safer with minimal runtime overhead, but much harder to bind to Python.
* Any octree with spatial querying is going to have to include some kind of vector/point/ray type, and anything with frustum culling is going to include a frustum and matrix math routines. Is writing the code to interface that to the dozen matrix/vector classes you've already dragged in from all the other libraries you're using actually less work than just writing the base octree you want?
* Is it thread-safe?

That being said, there are plenty of octree implementations online. Just don't assume grabbing one of them is going to save you much work, and don't assume there's One True Way to make any data structure other than an array.

# Answer
> 2 votes
To be fair, the linked Python Octree was posted in 2006, so Python-Ogre may very well have exposed the Octree class by now.

However, looking through the Ogre sources, I can see two Octree implementations: one in `Plugins/OctreeSceneManager/OgreOctree.h` and one in `Plugins/OctreeZone/OgreOctreeZoneOctree.h`.

If you point me at the one you're needing exposed, I'll put it on my todo list for my own, hand-written Python wrapper (it's available on bitbucket, linked in my profile.)

Anyway, good luck. :D

# Answer
> 1 votes
I found some code for a Python octree implementation here, by simply googling 'octree python'. ;D

It is not library dependent (though originally written for PyOgre) and is well commented.

# Answer
> 1 votes
After unsuccessfully trying a couple of the packages mentioned above I found RTree, which is a wrapper around libspatialindex.

---
Tags: python, octree, frustum
---


# Question
Title: Is there an all inclusive C++ game engine that is free
I would like to know if there is a C++ game engine that I can use for free to prototype some ideas I have.

I have experience in C++ and have spent some time now playing around with different rendering engines such as Ogre3d and irrlicht. I don't want to re-invent the wheel and spend the time building my own engine.

I have some ideas for a game that I would like to prototype and would be looking for a free engine to experiment with. I would be open to paying for the engine if I can make my idea work but as I don't have a great deal of time or resources I would need the engine to not have a time limit on free use.

By all inclusive I mean: I would rather not have to get a whole bunch of separate dependencies for physics, sound etc. I would prefer the one engine to have those things in it.

It might be a big ask as well but some of my ideas are of a more advanced nature so ideally not free because it limits the features for free use. I want something I can use to prototype some ideas and would be happy to pay for if the project went past the prototype stage.

# Answer
> 3 votes
Comparison of free AAA game engines.

Those are going to be your best options. You haven't really given enough information for me to suggest past that, but the breakdown should be detailed enough for you to choose.

# Answer
> 0 votes
if you are going to just create a prototype for your games you can use Esenthel Engine. it's basically designed for an mmorpg games, but it has reach framework for any kind of game you need to create. ofcourse you can expand your prototypes to full game using this engine but i'm not sure how the results will be.

# Answer
> -1 votes
Prototyping only ? I personally think using C++ to prototype in 2014 is just for someone who's not serious about his ideas and is just working for a school project or something.

If you have a game idea and you're thinking of making your first steps (prototype) then going with Unity3D is a good start it allows you to code your game details in JavaScript which is WAY simpler and it takes care of the C++ (hardware) part which includes memory management, rendering and texturing and executing your actual JavaScript game level instructions.

---
Tags: c++
---


# Question
Title: Calculate diameter of sphere large enough to encompasss a frustum
I'm attempting to speed up box-to-box collision checks by first testing if two spheres large enough to encompass each (respectively) would collide (because I'm using separating axis theorem and it's slower than I'd like it to be).

This is fine for equilateral boxes (ie, cubes) since I can just take two opposing corners and the line between them is the exact diameter of a sphere big enough to encompass the whole thing properly; and also the point in it's middle is the origin of the sphere. I add an epsilon just to avoid any glitches with colliding with the corners of the cube, but theoretically it shouldn't be necessary.

But for non-equilateral boxes, such as frusta, this method does not work. I've pondered it over and nothing I can come up with is a quick enough calculation for my taste. The best I've come up with is to take two opposing edges (diagonally through the box) from the near face to the far face, get their individual lengths and sum them; then do the same thing for the left-to-right faces and top-to-bottom faces. with these three sums, take the largest and just use that.

Anyway, that method works but it's too much calculation, involving 6 square roots. I need something faster and preferably more accurate. I've googled and haven't found much on this subject at all. I'd like the solution to work for boxes of *any* shape (as long as faces are valid) and frustums of unknown orientation (meaning the large face could be any side, not a known one).

It's also important to know the origin of the sphere (which is the dead center of the frustum). Which if there is no faster calculation, this is just the sum of all 8 verts divided by 8.

Any ideas?

# Answer
> 3 votes
*I do not think this answers your question in the general case, this is more specific to a frustum, and assumes that you know the 8 vertices formed by the intersecting planes ahead of time.*

Effectively, you need to know the distance from the center of your frustum to the 8 points where 3 planes intersect. What you ***do not*** need is to know the *Euclidean* distance for all 8; squared distance will work just fine.

### On the range \[0,oo):

```
(n+1)^2 > n^2

```

### On the range: (-oo,0\]:

```
(n-1)^2 > n^2

```

Since the only thing you are interested in is the magnitude of the distance from the center of your frustum to the extremes, this works quite well. The square of any non-zero displacement will always be greater than a shorter displacement (regardless of direction).

Now, given the squared distance to each of the 8 points, all you need to know is which one of them has greater magnitude.

The squared distance with greatest magnitude is the only distance you actually have to perform a `sqrt` on. This will be the minimum radius necessary to create a circumsphere for your frustum. Thus, what takes you 6 `sqrt` operations right now can be done with only 1.

---
Tags: collision-detection, geometry, bounding-boxes, bounding-spheres
---


# Question
Title: Handling packet impersonating in client-server model online game
I am designing a server-client model game library/engine.

How do I, and should I even bother to handle frequent update packet possible impersonating?

In my current design anyone could copy a packet from someone else and modify it to execute any non-critical action for another client.

I am currently compressing all datagrams so that adds just a tad of security.

**Edit:** One way I thought about was to send a unique "key" to the verified client every x\_time and then the client has to add that to all of it's update packets until a new key is sent.

**Edit2:** I should have mentioned that I am not concerned about whether the actions described in the packet are available to the client at the time, this is all checked by the server which I thought was obvious. I am only concerned about someone sending packets for another client.

# Answer
> 1 votes
Yes, you should definitely prevent this, because it makes cheating very easy.

There are countless ways for a cheater to manipulate the network traffic sent from their machine. For example:

* Hooking of network APIs of the operating system
* Play man-in-the-middle on their network router
* Hacking your game client
* Cloning your game client
* ...

You might consider to just tell the users of your library/engine to slap an anti-cheat tool on their game when they don't want cheaters, but 3rd party ACTs are just an excuse for people who don't know how to develop inherently secure client/server applications. Also, when you search on this website for information about anti-cheat tools you will realize how flawed they are.

Never trust the client. The client is in the hands of the enemy! Each incoming network message should be examined carefully to check if that very client is allowed to perform that very action at this very moment, and reject it when it doesn't.

When you use the TCP protocol, each client has their own connection, so determining who sent the message is trivial. UDP is connectionless, but each UDP datagram has a source-IP and source-port you can use to determine its origin. When your client library doesn't create any new UDP sockets, these shouldn't change during a session.

When you want to be really paranoid, you might consider encrypting the network traffic with a stock encryption algorithm (never invent your crypto unless you have at least a Ph.D. in math *and* computer science) and a different key for each session exchanged using the diffie-hellman key exchange. But that level of security is usually overkill for a game and not worth the added complexity and performance overhead.

# Answer
> 0 votes
> One way I thought about was to send a unique "key" to the verified client every x\_time and then the client has to add that to all of it's update packets until a new key is sent.

What if the client doesn't get it, or gets it very late? Probably better to establish a key per-session and call it a day. For example I encrypt all data using a per-session AES key due to the low overhead, but I don't claim to be a security expert.

Also don't broadcast network information about the clients to each other, only the server needs to know. The last thing a multiplayer game needs is multiple players DoS'ing each other.

# Answer
> 0 votes
If you are using TCP then you should be able to determine which connection the packet came over (from what address it originated). So you assign each player a unique id and associate that with the connection id. Now for each packet, you can do a lookup on the server, and make sure the id/connection pair is valid. That is an easy fix for the problem you describe.

---
Tags: networking, multiplayer, client-server, udp
---


# Question
Title: Render error in xna DrawPrimitive for Assimp Mesh
I am trying to render the vertices of a scene with a cube I exported as an OBJ from Blender. The 8 vertices become 24 when imported into XNA but when I render it I dont see all faces. This is not an issue of missing meshes because I'm pretty sure this is being stored as the first and only mesh. I suspect this is because of the vectors defined in the Assimp Mesh object but I can't seem to find any help for this.

THIS IS SOLVED! The code shows how to render a 3D model using only Assimp and XNA with vertex and index buffers. oScene is the Scene object imported using Assimp. This code only draws faces in a single color without textures.

Here is the relevant code:

```
   private void SetUpVertices()
    {
        mMesh = oScene.Meshes[0];
        vertices = new VertexPositionColor[mMesh.VertexCount];
        indices = new  short[mMesh.FaceCount*3];

        int i=0;
        foreach (Vector3D mVec in mMesh.Vertices)
        {
            vertices[i] = new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red);
            i++;
        }

        int f = 0;
        Face mFace;
        for (i = 0 ; i < mMesh.FaceCount*3 ; i=i+3)
        {
            mFace = mMesh.Faces[f];
            f++;
            indices[i] = (short)mFace.Indices[0];
            indices[i + 1] = (short)mFace.Indices[1];
            indices[i + 2] = (short)mFace.Indices[2];

        }

        vertexBuffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
        vertexBuffer.SetData(vertices);

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None);
        indexBuffer.SetData(indices);

    }

    private void SetUpCamera()
    {
        cameraPos = new Vector3(0, 5, 9);
        viewMatrix = Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0));
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f);
    }

    protected override void Draw(GameTime gameTime)
    {
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
        effect = new BasicEffect(GraphicsDevice);
        effect.VertexColorEnabled = true;

        effect.View = viewMatrix;
        effect.Projection = projectionMatrix;
        effect.World = Matrix.Identity;

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            device.SetVertexBuffer(vertexBuffer);
            device.Indices = indexBuffer;
            device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes[0].VertexCount, 0, mMesh.FaceCount);
        }

        base.Draw(gameTime);
    }

```

# Answer
> 0 votes
```
device.DrawPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleStrip, 0, oScene.Mesh[0].VertexCount);

```

I believe the problem may be that you are using TriangleStrip instead of TriangleList. It also primarily seems to be the draw call as well (based on my own quick test using your draw call). Try this:

```
device.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, oScene.Mesh[0].VertexCount, 0, triangleCount);

```

You'll have to set triangleCountfrom the oScene.Mesh\[0\] object (don't know what it is in Assimp, sorry). I'm currently using a draw call like this, and .OBJ files loaded from my own .OBJ importer work fine.

---
Tags: xna, rendering, vertex, assimp
---


# Question
Title: How do I use tiles and sprites together in an isometric scene?
I'm trying to write a 2D isometric scene. Rendering order is complex, since both tilemaps and sprites are different concepts. Rendering one of the 2 before the other will draw the scene incorrectly.

Tiles and Sprites both have some common data that can be used as render information. I thought of creating an extra object which simply holds the coordinates and texture data. However, this also meant having to couple a tile or sprite to a render info object. (something I haven't figured out). This adds complexity. However, I thought this way I could abstract over any renderable object.

This tutorial defines tiles as any other sprite and then uses a topology algorithm to sort the scene every frame.

I was actually thinking of using the pigeon hole algorithm by sorting the render info objects on their depth property.

How is this usually done? I can't wrap my head around it.

Bear in mind that I have no actual `z`-depth to work with. Everything relies on the artificial depth from the `x` and `y` coordinates.

# Answer
> 3 votes
The artificial depth from x and y is worth exactly as much as a the one from perspective projection, meaning all normal depth operations apply to it. There are essentially two possibilities for solving your problem: Keeping the static tiles in an already sorted structure and using the depth buffer.

## Sorting and Redrawing

pros:

* lower graphics memory consumption
* works with transparent tiles and sprites

cons:

* more CPU pressure
* likely more GPU pressure

Since the tiles' draw order won't change over the course of the scene, you can sort just the sprites and then keep track of the next tile and sprite each, picking between the two using your comparison function. Since the order of the sprites is somewhat consistent over time, you can base the order on the previous one and pick an algorithm that performs well with almost sorted lists.

If you have access to the stencil buffer it might be better to draw front to back, if no pixels are transparent. This depends on the complexity of your shader though, as far as I know.

If you have a lot of overdraw through tiles this algorithm is not very efficient, but you can make sure your tile map is composited with not much of it by culling e.g. invisible front faces when building the game.

## Depth Buffering

pros:

* lowest CPU pressure
* likely lowest GPU pressure

cons:

* higher graphics memory consumption
* doesn't work as well with transparent tiles or sprites

Since the artificial depth computed from x and y is "real", you can write it to the z-buffer as normal. Then, after drawing the map (or parts of it, if it's too large) keep that clean image in a texture and each frame copy it to the back buffer and draw unordered sprites on top.

The depth check function in the GPU will automatically (and relatively efficiently) sort everything correctly, just like when rendering 3D graphics. This doesn't work on transparent pixels though, so it may not be an option in every case.

## Hybrid Solution

pros:

* relatively low CPU and GPU pressure
* works with transparent sprites

cons:

* higher graphics memory consumption
* doesn't work with transparent tiles

You can combine an opaque tile map that is drawn once with transparent tiles if you sort the latter and then draw back to front over the clean map. This still takes advantage of the fastest solution for static maps but allows some more flexibility on the art side.

It's also possible to separate opaque and transparent sprites and draw the former first, without sorting.

## Other Thoughts

* If you have large (possibly static) obstructions that hide part of the map, consider using occlusion culling to avoid rendering sprites in that area. This works just like in 3D, with the exception that the bounding checks are easier because the view doesn't rotate.
* If you use a cache of twice the screen size in each direction, you can always just replace half of it when scrolling beyond the cached area and draw it in one go to the back buffer using texture wrapping.

If you don't render with "nearest pixel" mode you have to make the image slightly larger to consistently avoid texture bleeding around the edges, but I don't know what the impact of a non-power-of-two texture is in practice. This should be a non-issue if the viewport already has a non-power-of-two size though.

---
Tags: rendering, isometric, draw-order
---


# Question
Title: Collision detection using distance field for a dynamic object
I am using a signed distance field for collision detection. The object I calculated the distance field for rotates between 0 and -30 degrees. The other object I want to check collision against is in a bounding volume hierarchy (BVH) of axis aligned boxes. The problem is that as the first object is rotating, I cannot use the initial calculated distance field for collision detection. One solution that I thought of is that I can rotate the Bounding volumes by an angle opposite to what the original object rotates and then check the collision but this can be computationally extensive. Is there any other better solution that I can use to check the collision with the rotating object?

# Answer
> 0 votes
The solution you described is the correct one. You would convert the other objects to the local coordinate system of the object with the SDF and then use the SDF to check for collisions.

---
Tags: collision-detection, signed-distance-field
---


# Question
Title: How to interpolate movement between two points?
I have a map that's stored in a 2D Array with 1s being walls, 0s being roads, and 2s being houses. There is a character that is not stored in the map but its position is always checked against the map for "collision detection". Here is the map as a reference:

```
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1],
[1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1],
[1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,1,1,1,1,1,1,0,1,1,1,0,0,1],
[1,0,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1,0,0,1],
[1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,2,2,2,0,0,0,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,2,2,2,0,0,0,1,1,1,1,0,1],
[1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1,0,0,1],
[1,0,0,1,1,1,0,1,1,1,1,1,1,0,0,1,1,0,0,1],
[1,0,0,1,1,1,0,0,1,1,1,1,1,0,0,1,1,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,0,1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

```

The problem is I don't know how to make the character go smooth on that surface without overlapping any walls when drawing. The drawing viewport is 500x500, the map array is 20x20, so I divided the viewport size to the size of the array to get a block size to fit in my viewport, which was 25x25.

The blocks are drawn fine and fit in the screen perfectly but when I put the character size to 12.5 by radius, it keeps being drawn incorrectly into the screen. Like the area at the next would be "Road" but in the graphics it will just keep overlapping a wall. Changing the radius of the character didn't change anything. It just keeps jumping farther to be at position (x,y).

How is this generally done in a 2D game where the map is stored in an array? How can I "interpolate" between the two points and also detect collision cleanly?

If it matters, I am writing this game in JavaScript/HTML5 and drawing everything using `fillRect` and `arc`.

# Answer
Every time you detect a keypress, you add the velocity and move it.

```
if (up_key_pressed)
{
    // Move it up by a velocity (not a cell)
    temp_y -= velocity_y * deltaTime;
}
....

```

Then after every move, you check the map if the point `(temp_x, temp_y)` collides with the walls. If it doesn't collide, assign that point to the position of your character.

Hope this helps.
> 1 votes

---
Tags: 2d, collision-detection, javascript, tiles, movement
---


# Question
Title: How can I use a filter to scale down my sprites?
I want the best visual result on my Windows Phone if I scale down my sprites from 1920x1080 pixel resolution to 800x480 pixel resolution.

How can I use a filter to scale down my sprites? Which filter is the best?

# Answer
> 0 votes
In XNA you can change the texture sampling method in the GraphicsDevice class. For example:

```
GraphicsDevice device;
//... say you created a valid device
device.SamplerStates[0] = SamplerState.LinearClamp; //this sets bilinear filtering
device.SamplerStates[0] = SamplerState.PointClamp; //this sets nearest neighbor (or point) filtering

```

You will also find a LinearWrap and PointWrap feature in the SamplerState class. These do the same filtering but will wrap around your texture coordinates (You don't have to use it if you don't know what it means yet).
An other method would be to set the sampler states in the shader if your can use them:

```
Texture xTexture0;
sampler TextureSampler0 = sampler_state {
                                        texture = <xTexture0>;
                                        magfilter = linear;
                                        minfilter = linear;
                                        mipfilter = linear;
                                        AddressU = wrap;
                                        AddressV = wrap;
                                       };

```

For which is the best filter there is no universal definition it depends on the art style. For example with pixelated retro graphics you would want to use point filtering, while high resoulution sprites like bilinear better. Also bilinear filtering requires a bit more processing because of the interpolation.
There is an other filtering method called anisotropic which makes no difference from linear in 2D graphics.

---
Tags: xna, c#, windows-phone-8
---


title: Importing .blend files into netbeans

text:
# Question
Title: Importing .blend files into netbeans
How can we import blender models into netbeans for use? I have jmonkeyengine 3 installed for netbeans 7.3 but havent found any good tutorials on importing.

# Answer
> 1 votes
We do not use the `.blend` files. They are `Blender` projects and cannot be used directly. You have to export them to a usable format like `.OBJ` files.

And you use the asset manager in JME3 to load an obj model.

```
assetManager.loadModel("path/to/model.obj");

```

Hope this helps.

# Answer
> 0 votes
.blend files are not supposed to be used in games directly. You should first export them to another format (obj, 3ds, own custom format..) and use that in your game instead. .blend files (blender project files) are to 3D models what .psd files (Photoshop project files) are to 2D pictures. You wouldn't put a Photoshop project file on the web, but use jpeg, png, etc. instead. While .blend files are great for editing purposes, they store lots of useless information, e.g. your game doesn't care about layers. Such features make .blend files complex and slow to load in your game.

You should research whether one of the existing formats is good enough for you ("supports enough bone weights" and other requirements), then pick one to export to, as described in http://wiki.blender.org/index.php/Doc:2.6/Manual/Data\_System/Files/Export If none of the existing formats is good enough for you, you might want to install a 3rd party export plugin for blender or write your own exporter. You will then need to teach your game engine to load the chosen file format.

---
Tags: blender
---


# Question
Title: What to send to server in real time FPS game?
What is the right way to tell the position of our local player to the server? Some documents say that it is better to send the inputs whenever they are produced. And some documents say the client sends its position in a fixed interval.

With the sending the inputs approach: What should I do if the player is holding down the direction keys? It means I need to send a package to the server in every frame. Isn't it too much? And there is also the rotation of the player from the mouse input. Here is an example:

> http://www.gabrielgambetta.com/fpm\_live.html

What about sending the position in fixed interval approach. It sends too few messages to the server. But it also reduces responsiveness.

So which way is better?

# Answer
Simple answer: cheat or don't be that accurate!

If you've played some shooter online, you'll most likely have experienced the so called "rubber banding" if your connection to the server is bad.

This is caused by your client correcting your position from time to time.

Basically, what happens on the two sides:

* The server will track your movement and send updates to the clients as expected. These don't always have to be full updates. Every x frames there could be a full update, all other frames you only send new velocity vectors (if there are any changes).
* Your own client will allow you to move freely but will use the updates provided by the server to correct/adjust your position. This will ensure the game to feel responsive, even if you don't update the position frame by frame.

But how is input handled? Your client will send your position to the server "I moved there.". The server will verify this update (e.g. should you be able to move there that fast?) and if it's valid move you (or rejecting your update, resulting in "rubber banding").

So yes, your fixed interval approach will most likely work and be enough.

But even if you want to send input and handle movement on both sides, keep in mind that you don't have to send "button is still pressed". Instead, send one event when the button is pressed and another once the button is released.
> 23 votes

# Answer
If you haven't already, I suggest you to read these two deep but understandable articles : https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking and http://fabiensanglard.net/quake3/network.php.

These explain why it's advised to use 'fixed interval' packet sending. To be short, it's in fact mainly important for packets sent by the server.

Sending a packet has a fixed cost, and a network packet maximum size is about 1.5 KB. So if you have for example 16 players on your server, each frame when you calculate movement for a player, naive code could send a update packet to each player after each movement resolution, so 16\*16 = 256 packets. If you have a framerate of 30, that's 7680 packets.

A better approach, is to create a buffer in each beginning of frame, concatenate in it your 16 calculated positions update, and then send them to your 16 players.

You now send only 480 packets by seconds for same results.

In the player-to-server case, that just means you should send, in the same packet a maximum of data, like; looked position, actions called this frame and so on.

About the second part of your question - the way I choose to reduce the lag sensation was to send this information to the server on each frame:

* actual current position of player (used by server to check if server side and player side positions aren't too much desynchronized).
* Estimated player position in 1 second : calculated by client: if the player doesn't change mouse direction and leaves the keyboard in its current state for 1 sec where will be the player? (we don't care about collisions) If the player isn't moving, then his estimated position in 1 second is its current position.
* The position he look at.

Each time the server receives this information it updates the future position and looked position, and the player entity eventually moves toward its future position.

Players are never exactly synchronized, but input response is instant (most important for me) and I found predicted positions to be accurate enough for me.
> 7 votes

---
Tags: networking, multiplayer, client-server, first-person-shooter
---