title: Spot Light color fade in Unity 3d

text:
# Question
Title: Spot Light color fade in Unity 3d
I have a scene where many spot lights are focused on the screen. All have red color and same intensity. What I want is that the red Color(0,0,0,1) value should increase and decrease in a fading effect over a period of time. I thought of using Color.Lerp() but can not achieve it. What currently I am doing is attaching this script to all the instances of the SpotLight.

```
void Update()
{
 if(Time.time()%120==0)
   transform.light.color=new Color(Random.Range(0,255),0,0,1);
}

```

I know I am missing something big here. Help is appreciated. Thanks in advance.

# Answer
The problem is on the line `if(Time.time()%120==0)`

By doing that, you divide the timestamp by 120 and then compare if the decimals are zero. That will happen really rarely as the timestamp will have quite a lot of different values. What you should do instead is to calculate the colour every frame. Perhaps something like this will do:

```
void Update()
{
    transform.light.color=new Color((Mathf.Sin(Time.time()) + 1) / 2,0,0,1);
}

```

This will smoothly increase and decrease the light over time. The "magic" is in the Mathf.Sin() method.
> 2 votes

---
Tags: unity, color, lighting, lerp
---


title: Is this GLSL equivalent to this HLSL?

text:
# Question
Title: Is this GLSL equivalent to this HLSL?
I was wondering if the both shader codes are equivalent. So the question is, is this GLSL

```
vNormal = mat3(FUSEE_ITMV[0].xyz, FUSEE_ITMV[1].xyz, FUSEE_ITMV[2].xyz) * fuNormal;

```

Equivalent to this HLSL?

```
float3x3 fMatrix = {FUSEE_ITMV[0].xyz,FUSEE_ITMV[1].xyz,FUSEE_ITMV[2].xyz};
output.normal = normalize(mul(input.normal,(float3x3)fMatrix));

```

Theoretical I'd say yes they are but I'm not sure. Can anyone verify that they are equivalent?

# Answer
> 1 votes
Yes, assuming your `FUSEE_ITMV` matrix in HLSL is the transpose of the `FUSEE_ITMV` GLSL matrix, otherwise you need to make sure it's transposed. GLSL `mat3` deals with the passed vectors as columns of the matrix. HLSL `float3x3` on the other hand deals with them as rows.

GLSL:

```
mat3 m( column0, column1, column2);
m[0]; // returs the first column

```

HLSL:

```
float3x3 m = float3x3(row0, row1, row2); // sets rows of matrix n
m[0]; // Returns first row.

```

As far as you are indexing you matrices in a uniform way, columns for columns and rows for rows, this will assign each column to its equivalent column in the glsl `mat3` and each row to its equivalent row in the glsl `float3x3`

---
Tags: shaders, glsl, hlsl
---


# Question
Title: How can I handle rendering on multiple monitors with differing refresh rates?
What's the best way to deal with a situation that may arise, where a user has two or more monitors with different resolutions and vertical sync intervals?

This would apply when a game has a fixed timestep, and is running in windowed mode: if one monitor has a frame rate of 60.056, and the other has a frame rate of 59.94, vertical sync will ultimately fail to do its job, if the game window is moved from the primary screen to another.

Temporal aliasing will also occur, as the timestep is not properly attuned to the other sync rate. How do games typically deal with this issue, if at all?

# Answer
Game logic steps do not *have* to be synchronized with display logic, even if you're using a fixed timestep.

Consider a gameloop like:

```
var time_per_step = 1 / 60 -- for 60 -logic- steps per second
var prev_time = get_time() -- in seconds

while true do
    var curr_time = get_time()
    while prev_time < curr_time do
        do_step()
        prev_time = prev_time + time_per_step
        // optional: curr_time = get_time()
    end
    draw()
end

```

It doesn't really matter how long your `draw()` calls take. As long as your `do_step()` takes less than `time_per_step`, your game logic won't fall behind.
> 5 votes

---
Tags: vsync
---


# Question
Title: How to select a vertex by mouse clicking in OpenGL?
I'm programming a simple graph game and so far I'm still doing a few tests in OpenGL. Right now, let's say I defined a GL\_POINT with the glVertex2f(20.0f, 0.0f). I have this function to calculate the coordinates from the mouse input to world coordinates:

```
void converterCoords(GLfloat winX, GLfloat winY){

GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winZ = 0;

glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
glGetDoublev( GL_PROJECTION_MATRIX, projection );
glGetIntegerv( GL_VIEWPORT, viewport );

winX = (float)winX;
winY = (float)viewport[3] - (float)winY;
winZ = 0;

gluUnProject( winX, winY, winZ, modelview, projection, viewport, &worldX,
        &worldY, &worldZ);

```

}

After this I have a function to check if the mouse click coordinates are the same as one of the GL\_POINTS I defined:

```
int determinaPosicao(double x, double y){

int i;
for(i = 0; i < nPontos; i++){
    if(pontos[i].vX == x || pontos[i].vY == y){
        pontos[i].seleccionado = 1;
    }
}

glutSetWindow(window);
glutPostRedisplay();
return 0;

```

}

I can check just fine if the mouse click is the same as the if condition with the "||" function, however, if I have two points with the same x or y value, then it will declare the mouse has hit both points. However, if I use the "&&" function it never seems to go into the if condition and never declares any point as having been hit.

This certainly isn't the best way to achieve my goal and I would really like to ask for some opinions on how to do this.

Solution I found with help from user concept3d:

```
int determinaPosicao(double x, double y){

const double maxDist = (1e0);
int i;

printf("%f\n", x);

//Escala no rato após conversão: ~5510

x = (x*xMaxRef)/10000;
y = (y*yMaxRef)/10000;

for(i = 0; i < nPontos; i++){
    if(pow((pontos[i].vX - x), 2) <= maxDist  && pow((pontos[i].vY - y), 2) <= maxDist){
        pontos[i].seleccionado = 1;
    }
}

glutSetWindow(window);
glutPostRedisplay();
return 0;

```

}

The operations I used in x = (x\*xMaxRef)/10000 is a simple rule to scale the mouse coordinates (that range from 0 to approx 5510) from the max ortho referencial scale which is x and y = {-100, 100}

# Answer
> 2 votes
Well, I can see few problems in your approach, but I will assume both points are in the same coordinate system (world space).

Comparing doubles and floats using "==" is a bad idea. You need to introduce an error margin like this

```
const double err = 1e-15;
int i;
for(i = 0; i < nPontos; i++){
if( fabs(pontos[i].vX - x) < err  && fabs(pontos[i].vY - y) < err )
{
pontos[i].seleccionado = 1;
}

```

Better yet, you can calculate the distance squared to the point instead, and check if it's within an acceptable distance.

This has the advantage of using distances, which is more intuitive because you can determine which distance doesn't make the user frustrated with selecting the point, if you need him to exactly match the point, he will be frustrated.

```
const double maxAcceptableDistanceSqr = 1e-5; // You need to change this to your liking
int i;
for(i = 0; i < nPontos; i++)
{
    // [Edit] fix the dist calculation
    double distanceSqrd = (pontos[i].vX - x)^2 + (pontos[i].vY - y)^2;
    if( distanceSqrd < maxAcceptableDistanceSqr )
    {
        pontos[i].seleccionado = 1;
    }
}

```

I recommend using the latter approach, this will make your point act as a circle/sphere (point with radius), which is more effective for selection than using the exact vertex position.

---
Tags: opengl, mouse
---


# Question
Title: OpenGL Texture loaded but wont draw on Bind
I wrote my entire Texture loader by hand. I'm not using any Libraries. From what I gather the loading part is done correctly and stored in the texture class:

```
Texture* TGATextureLoader::create(const char *filename) {
        FILE *pFile;            // File pointer
        TGAHEADER tgaHeader;        // TGA file header
        unsigned long lImageSize;       // Size in bytes of image
        short sDepth;           // Pixel depth;
        GLbyte  *pBits = NULL;          // Pointer to bits

        // Default/Failed values
        GLint iWidth = 0;
        GLint iHeight = 0;
        GLenum eFormat = GL_BGR_EXT;
        GLint iComponents = GL_RGB8;

        // Attempt to open the fil
        pFile = fopen(filename, "rb");
        if(pFile == NULL)
            return NULL;

        // Read in header (binary)
        fread(&tgaHeader, 18/* sizeof(TGAHEADER)*/, 1, pFile);

        // Get width, height, and depth of texture
        iWidth = tgaHeader.width;
        iHeight = tgaHeader.height;
        sDepth = tgaHeader.bits / 8;

        // Put some validity checks here. Very simply, I only understand
        // or care about 8, 24, or 32 bit targa's.
        if(tgaHeader.bits != 8 && tgaHeader.bits != 24 && tgaHeader.bits != 32){
            return NULL;
        }

        // Calculate size of image buffer
        lImageSize = tgaHeader.width * tgaHeader.height * sDepth;

        // Allocate memory and check for success
        pBits = (GLbyte*)malloc(lImageSize * sizeof(GLbyte));
        if(pBits == NULL)
            return NULL;

        // Read in the bits
        // Check for read error. This should catch RLE or other
        // weird formats that I don't want to recognize
        if(fread(pBits, lImageSize, 1, pFile) != 1)
        {
            free(pBits);
            return NULL;
        }

        // Set OpenGL format expected
        switch(sDepth)
        {
        case 3:     // Most likely case
            eFormat = GL_BGR_EXT;
            iComponents = GL_RGB8;
            break;
        case 4:
            eFormat = GL_BGRA_EXT;
            iComponents = GL_RGBA8;
            break;
        case 1:
            eFormat = GL_LUMINANCE;
            iComponents = GL_LUMINANCE8;
            break;
        };

        // Done with File
        fclose(pFile);

        Texture* texture = new Texture(pBits);
        texture->setWidth(iWidth);
        texture->setHeight(iHeight);
        texture->setComponents(iComponents);
        texture->setFormat(eFormat);

        // Return pointer to image data
        return texture;
    }

```

Then when Im done, I call textureName-\>generateTexture() Method from the texture class:

```
void Texture::generateTexture(){
        GLuint id;
        glGenTextures(1, &id);
        this->textureID = id;
        std::cout << "Binding Texture\n";
        glBindTexture(GL_TEXTURE_2D, this->textureID);
        glTexImage2D(GL_TEXTURE_2D, 0, 3, this->width, this->height, 0, GL_RGB, GL_UNSIGNED_BYTE, this->data);
        glBindTexture(GL_TEXTURE_2D, 0);
        std::cout << this->textureID;
    }

```

Then in my initialization of the resources, I call;

```
textureName = Engine::TGATextureLoader::create("filePath/fileName.tga");
textureName->generateTexture();

```

lastly in my render method, I bind the texture again before I use it:

```
glBindTexture(GL_TEXTURE_2D, cubeTexture->getTextureID());
glBegin(GL_TRIANGLES);                      // Drawing Using Triangles
    glTexCoord2f(0.0f, 0.0f);
    //glColor3f(0.0f,0.0f,1.0f);
    glVertex3f( 0.0f, 1.0f, 0.0f);              // Top

    glTexCoord2f(1.0f, 0.0f);
    //glColor3f(1.0f,0.0f,0.0f);
    glVertex3f(-1.0f,-1.0f, 0.0f);              // Bottom Left

    glTexCoord2f(1.0f, 1.0f);
    //glColor3f(0.0f,1.0f,0.0f);
    glVertex3f( 1.0f,-1.0f, 0.0f);              // Bottom Right
glEnd();                            // Finished Drawing The Triangle

```

The texture doesn't render though. Is there something wrong with this code?

# Answer
You're not setting any properties in `generateTexture`.

Furthermore, you're setting the texture's internal format to 3, which is not valid and the type to `GL_RGB`, which is not correct. I recommend padding your input data with an alpha byte in order to ensure the texture's validity. Try this version instead:

```
void Texture::generateTexture(){
    GLuint id;
    glGenTextures(1, &id);
    this->textureID = id;
    std::cout << "Binding Texture\n";
    glBindTexture(GL_TEXTURE_2D, this->textureID);
    glTexParameterI(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterI(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterI(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterI(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(
        GL_TEXTURE_2D, 0, GL_RGBA,
        this->width, this->height,
        0,
        GL_BGRA, GL_UNSIGNED_BYTE, this->data
    );
    glBindTexture(GL_TEXTURE_2D, 0);
    std::cout << this->textureID;
}

```

If you're still not getting anything on the screen then at least your texture is valid. If the colors are wrong, try shuffling the bytes in your data.

Lastly, I highly recommend using CodeXL to debug OpenGL problems. You can use it to set a breakpoint for OpenGL errors, but also pause the program and inspect your textures and buffers.
> 1 votes

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


title: How is displacement tessellation done?

text:
# Question
Title: How is displacement tessellation done?
I'm curious because I was thinking that displacement mapping is done in the shader file only inside the domain shader. Am I correct or is it both implemented in the rendering section of the mesh and shader? So, if I make a cube for an example, I would have to read out the displacement map file then tell what vertices get positioned inside the render or only in the shader file? I'm a bit stuck on that concept.

These are the snap shots done inside the game editor of a plane. I believe the issue lies within the texture but you can always correct me.

This texture was created for the box inside 3DS Max and the UV Mapped, then baked the image.

When I load a sphere, not so much crazy gaps but it's still hasty.

# Answer
> 1 votes
I would do this by setting the displacement texture and a sampler to the domain shader, than sample that on every vertex on the appropriate mip level (done by SampleLevel in hlsl). So you have a 0.0-1.0 value on your vertex, which you offset along its normal by it (and additionaly multiplied by a scalar), like for example:

```
pos.xyz += normal.xyz * (sampledValue - 0.5f) * displacementStrength;

```

And in the "rendering section", the c++ code I only decide if the model should be tessellated or not (based on distance, for example, or size...). If yes, bind the hull and domain shaders and set the resources. (Note that you should sort your models if possible to avoid many state-changes, like binding shaders and clearing device. (I would draw the untessellated meshes first, than setting the hull and domain shaders and proceed with the tessellated ones.)

---
Tags: tessellation
---


title: directional lightning

text:
# Question
Title: directional lightning
I have managed to get a point light working, but I am facing problem with directional lightning.

```
    Fragment shader
 uniform vec4 lightColour ;
 uniform vec3 lightPos ;
 uniform float lightRadius ;

in Vertex {
vec3 colour ;
vec2 texCoord ;
vec3 normal ;
vec3 tangent ;
vec3 binormal ;
vec3 worldPos ;
} IN ;

  void main ( void ) {
  vec4 diffuse = texture ( diffuseTex , IN . texCoord );
  mat3 TBN = mat3 ( IN . tangent , IN . binormal , IN . normal );
  vec3 normal = normalize ( TBN * ( texture ( bumpTex , IN . texCoord ). rgb * 2.0 - 1.0));
  vec3 incident = normalize ( lightPos - IN . worldPos );
  float lambert = max (0.0 , dot ( incident , normal ));
  float dist = length ( lightPos - IN . worldPos );
  float atten = 1.0 - clamp ( dist / lightRadius , 0.0 , 1.0);
  vec3 viewDir = normalize ( cameraPos - IN . worldPos )
  vec3 halfDir = normalize ( incident + viewDir );

  vec3 viewDir = normalize ( cameraPos - IN . worldPos );
  vec3 halfDir = normalize ( incident + viewDir );
  float rFactor = max (0.0 , dot ( halfDir , normal ));
  float sFactor = pow ( rFactor , 33.0 );
  vec3 colour = ( diffuse . rgb * lightColour . rgb );
  colour += ( lightColour . rgb * sFactor ) * 0.33;
  gl_FragColor = vec4 ( colour * atten * lambert , diffuse . a );
  gl_FragColor . rgb += ( diffuse . rgb * lightColour . rgb ) * 0.1;

```

As far as I know, directional lightning do not have a radius or a position, just direction. How should I calculate directional lightning?

# Answer
> 4 votes
You don't need to calculate the vector direction, you don't need this line

```
 vec3 incident = normalize ( lightPos - IN . worldPos );

```

Instead just pass the direction(incident) vector as a uniform variable, because direction light doesn't have a position (actually it's supposed to be positioned at infinity), so you pass it as a uniform so it's doesn't change with respect to the object.

```
uniform vec3 lightDir;

```

You also don't need the attenuation, because directional light are supposed to simulate lights at "infinity" like sun.

# Answer
> 0 votes
A directional light is even easier than a point light - the direction of the light is what you use as the `incident` vector, and the rest is the same.

# Answer
> 0 votes
Think directional lighting as like it's a point light but it just has the same direction for all the fragments. Then just leave out the radius and attenuation, and you got directional light.

Some good tutorials of directional lights can be found here, here and here.

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


title: Multiple pixel shader passes

text:
# Question
Title: Multiple pixel shader passes
I currently have a pixel shader that calculates the texture and I have another that calculates the light. I want another shader that does both. What I would ideally like to do is instead of creating a third shader that does that, I would like to have my object run through the first shader, then run through the second and then combine the final colors. Is this possible in DirectX11?

If this is possible, is it also possible that I run through the same shader multiple times? For example, could I load a texture and then run my texture shader then load another texture and then run the same texture shader again. Also same with lights, where I load light information to the cbuffer, run light shader, load another light informationm ,run light shader and rinse and repeat until I have run all lights.

# Answer
Use conditional shader compilation! Well, to explain what I mean:

You can write one shader, that calculate several things, and pass to it a preprocessor token. The shader will compile based on what tokens were passed. This is similar to preprocessor directive we used for a long time in C:

```
#ifdef WIN32
//do this
#else
//do that
#endif

```

The same could be done with any shading language,(unless you are using precompiled binary shaders).

```
vec3 CalculateTexture(){ ... }

vec3 CalcualteLight() { ... }

void main()
{
#ifdef CALC_TEXTURE
vec3 CalculateTexture();
#endif

#ifdef CALC_LIGHT
vec3 CalcualteLight();
#endif
//rest of shader code
}

```

You can pre-pend tokens to your shader source and compile conditionally for example if you pass `#define CALC_TEXTURE` this will only compile the part between the appropriate compiler preprocessor.

This is a common technique called Uber-shader, it will let you re-use your shader code by passing the appropriate tokens each time.

I am familiar with this technique in OpenGL, actually the reason glShaderSource takes array of strings is that you can pre-pend tokens to shader source.

```
void glShaderSource(GLuint shader,
                    GLsizei count,
                    const GLchar **string,
                    const GLint *length);

```

Am not sure how this is done in DirectX (as am not familiar with it's api), but because HLSL supports preprocessor directives I am sure it's straightforward to be done.
> 3 votes

---
Tags: c++, directx, shaders, directx11, fragment-shader
---


# Question
Title: Will I have copyright issues making a mobile game based on an anime?
I have been wanting to create a mobile game based on some of my favorite anime.

I want to know if using character images and names from those anime (even after giving full copyright credits and disclaimer) infringes any copyrights?

Would this come under "fair use" in the DMCA (I mean there are already so many not-so-legal sites using this "fair use" to continue running).

What are the possible things I can do for making this game? I have seen many online browser games based on anime which use images and elements from that anime, while I have also seen many games advertise themselves based on a anime but just use diffrent names for characters of that anime (sometimes modifying the character images, too).

# Answer
> 3 votes
I am not a lawyer; the following is not legal advice. If you really want to proceed with this direction of development *you should consult an actual lawyer* familiar with copyright law.

> Since long I have wanted to create a mobile game based on some of my favorite anime. I wanted to know do using character images and names from those anime (even after giving full copyright credits and disclaimer) infringes any copyrights ?

Copyright and intellectual property law varies from country-to-country. You're talking about anime, which means the source IP *probably* falls under Japanese copyright law.

I am even less familiar with Japanese law than US law, but in the US, it is not sufficient to "give credit" to avoid infringing copyright -- you need to obtain the permission of the copyright holder. Even though you may see others disclaiming that "no infringement was intended," that is not a firm ward against litigation.

It's possible that some things you want to use (such as the names of characters) do not fall under IP protection rights (or would be permissible under fair use), but others (such as character designs or images, or the proper name of the anime itself) may be subject to copyright, trademark or other equivalent IP protection. You'll really want a lawyer to help you untangle that mess.

Either find yourself a lawyer, or choose a different tack for your development plans that do not involve the potential legal ramifications of IP infringement.

# Answer
> 3 votes
If you `don't know` if its a copyright issue, then `always` assume that it will be.

This is the best/safest way to think, at least until you find out for sure :)

# Answer
> 2 votes
With todays civil law it is not about being right, it is about being right and having the cash to prove it in court. When you have a zero-budget fan project and you want it to stay zero-budget, you won't be able to pay a lawyer and defend it in court, even when you assume that you have a good chance to win eventually (maybe you have, maybe you don't - ask a lawyer).

That means the best protection from a lawsuit is not giving anyone a reason to start one in the first place.

What reason would the IP holder have to sue you?

* They might feel that your game affects their brand value negatively.
* They are afraid that your game might compete with a game they make or plan to make in the future. Imagine they spend millions (of yen) to create and promote an own game based on their IP, and people who search for it in the app-store find your game first and play that one instead?
* They do it just because they can and see an opportunity to squeeze some money out of you (copyright-trolling)

Bottom line: Don't make fangames. Better develop your own IP and avoid the legal trouble. When your motivation for the project is that you are a big fan of IntellectualPropertyX and want to capture its look and feel in game form, you should think about *why* you like it, isolate these aspects, and use these aspects as an inspiration for your own intellectual property.

A good example for a fan-game which isn't a fan-game is Freedom Planet. It looks like Sonic the Hedgehog, it plays like Sonic the Hedgehog, but otherwise it has no connection at all to Sega's intellectual property. The result is an all new intellectual property which stands on its own and has the potential to turn into a franchise itself.

---
Tags: android, ios, copyright
---


title: How to manage input state in Unity3D?

text:
# Question
Title: How to manage input state in Unity3D?
In Unity3D how do I manage input among many components, especially in relation to "blocking" input messages to certain components?

To make my question clear, an example:

# Component 1: Input Manager

Manages a list of components that require input. They do this via a `Register` method, which adds the component to a `List`. Each registered component can poll input via this method:

```
public static bool GetKeyUpAndActive(KeyCode keyCode, MonoBehaviour entity) {
    return Input.GetKeyUp(keyCode) && List.Contains(entity);
}

```

This feels clunky, as each entity needs to pass itself to the manager, and the manager has to keep a list of registered input events.

# Component 2: Script Manager

Manages scripts such as "Open Dialogue Box, say "Hello", play SFX, add Item x to inventory. Script manager responds to input, for example, if over component, and `Input.Action` is pressed, run this script.

# Component 3: Dialogue Manager

Manages the dialogue box, pretty stock standard stuff. It also responds to input, pressing `Input.Action` will cycle through the dialogue boxes, until it reaches the end, then returns back to the game.

The **main issue I am facing** is that the `script manager` and the `dialogue manager` are responding to the `Input.Action` during their own updates. So `Script 001` responds to `Input.Action` which triggers an open dialogue box, but because `dialogue manager` also responds, it has already cycled through to the next dialogue box.

I think the Input Manager is breaking encapsulation. I also feel like I'm missing an obvious component here, maybe I need a stronger subscriber pattern to follow, or should there be a separate state manager, and if so, should the input manager only send events/provide methods to components in the correct state, or should components check the state machine themselves?

# Answer
> 3 votes
Hey I will try to give you a starting point. Your problem of handling the input in more than one method could be solved by creating your own small messaging system:

* Create a class `InputMessage`, this class contains the original `Input action` and a `bool handled`.
* Your Input handler is the only class to access the original Unity Input, whenever a input occurs it generates a new InputMessage, encapsuling the original action.
* Components can register to the input manager (just like you already handle it), maybe with the extend to provide a priority, indicating how 'early' it should be processed.
* When a new InputMessage is created the input manager pass it to every component in the list, into a function `InputMessage TakeInput(InputMessage im)`
* This function will handle input logic nd then return the original message, or an altered one, this new message is then passed to the next component, unless it got `handled` set to true

So in your problem you would just set `handled` to true in the script manager and return the message. Your InputManager would see this and break the loop. You could even use this system to change input messages in your components, if you ever need to do so.

Logic in InputManager could look somehow like this:

```
InputMessage im=new InputMessage(originalAction,false);
foreach(InputComponent ic in list){
  im=ic.TakeInput(im);
  if(im.Handled)
    break;
}

```

InputComponent would we an interface or abstract class adding the Takeinput function to your class signature.

Hope this gets you started, feel free to comment, if you got any questions

---
Tags: unity, input, state
---


title: C++ OOP Implementation of a game

text:
# Question
Title: C++ OOP Implementation of a game
I've been recently trying to get into Object Oriented Programming by porting a game I've made in C to C++. The problem is, even though my implementation *works*, I don't know if is the best approach.

The game is a tower defense, which contain 3 main elements: Tiles, Enemies and Towers. Each of the three elements have a "engine" class, which manipulates and allocates the individual objects. For example:

Tiles:

```
Class Tile
{
  private:
  int  posX, posY;
  bool visible;

  public:
  void DrawItself();

};

Class TileEngine
{
  private:
  Tile tileArray[m][n];

  public:
  int GetTileXPosition(int m, int n);
  int GetTileYPosition(int m, int n);
  void DrawArray();
};

```

Enemies:

```
Class Enemy
{
  private:
  int  posX, posY;
  bool health;

  public:
  void DrawItself();
  void MoveItself();

};

Class EnemyEngine
{
  private:
  Enemy enemyArray[m][n]

  public:
  void DrawArray();
  void MoveArray();
};

```

TileEngine and EnemyEngine are then instantiated on a Game class, and their public methods are then called on a loop:

```
Loop()
{
  TileEngine TileEngine;
  EnemyEngine EnemyEngine;
  /*FPS controlling routine omitted*/
  while(1)
  {
    EnemyEngine.Movement();

    TileEngine.DrawArray();
    EnemyEngine.DrawArray()
  }

}

```

The problem is that the EnemyEngine.Movement() method requires information from the TileArray, of which it doesn't have access. My temporary solution has been giving the EnemyEngine class a pointer to the TileEngine class:

```
void Loop()
{
  TileEngine TileEngine;
  EnemyEngine EnemyEngine;

  EnemyEngine.pTileEngine = &TileEngine;

  while(1)
  {
    /*...*/
  }

}

```

But doesn't that defeat the purpose of object oriented programming? **Is there a better approach to get information between the "engine" classes?** Or is the Element -\> ElementEngine -\> Gameloop implementation flawed altogether?

# Answer
> 3 votes
Long text incoming!

What makes OOP powerful is the Inheritance and Polymorphism not knowing exactly how much you know about this I will be very basic. A very common way of structuring a game with OOP is to have a base class that all the other "game objects"(tiles, enemies, players, towers, what have you) inherits from. That is, one class that has alot of children.

So for instance, you create a base class, lets call it GameObject. This class contains all that every object in the game needs, such as posision, rotation and so on.

```
Class GameObject
{
public:
    GameObject();
    ~GameObject();
    virtual void update() {}; //virtual will let you rewrite the function
                              //in a child class.

protected:        //Protected lets the children be able to modify the variables
    int posX, posY;
};

```

Now your Tile and Enemy class can inherit from this class making them subclasses or "childs". That contains all that the "parent does so you don't have to write it again, in this case it's the "int posX, posY"

```
#include "GameObject.h"
Class Tile : public GameObject //Inheritance
{
public:
    void update(); //Add logic

private:
    bool visible;
    //automaticly has int posX, posY; since we inherit.
};

```

What this lets you do is to "trick"(not quite but it's easier to understand) the computer into thinking that a pointer to an Enemy or Tile object is a GameObject pointer. And thereby we can put all the object-pointers to objects that inherites from the GameObject class into one list. This will make the Game Loop look something like this:

```
void Loop()
{
    //creates the list
    std::vector<GameObject*> gameObjects;  //Create a vector or a regular array
                                           //that can hold all your gameobjects
    //Fills the list
    gameOjbects.push_back(new Enemy());
    gameObjects.push_back(new Tile());
    gameOjbects.push_back(new Enemy());
    gameObjects.push_back(new Tile());
    gameOjbects.push_back(new Enemy());
    gameObjects.push_back(new Tile());

    //UpdateLoop
    while(true)
    {
        for(int i = 0; i < gameObjects.size(); i++)
            gameObject[i]->update();
        //This is where the virtual keyword comes in.
        //Here the compiler will regognize this as an Enemy- or Tile-pointer, not GameObject.
        //Having the update function in GameObject as "virtual"
        //will make the compiler take the Enemies or Tiles version of the function
        //if there is one. This is "Polymorphism".
    }
}

```

---

Now your Enemy.update() function still needs an array of tiles, and spontaneously I would do it sort of like you solved it.

```
#include "Tile.h"
#include <vector>
Class Enemy : public GameObject //Inheritance
{
public:
    void update(); //Add movement logic in .cpp file

    //This will set the pointer to the tiles array or vector.
    static void setTilesPointer(std::vector<Tile*>* tiles) { m_tiles = tiles; };

private:
    bool health;
    static std::vector<Tile*>* m_tiles; //The pointer to the tiles array or vector.
};

```

Then in the top of Enemy.cpp we add, so we don't get an unresolved external symbol error:

```
std::vector<Tile*>* Enemy::m_tiles = new std::vector<Tile*>();

```

And now you have to modify your loop function a bit:

```
void Loop()
{
    //Creates the lists
    std::vector<GameObject*> gameObjects;  //Create a vector or a regular array
                                           //that can hold all your gameobjects
    std::vector<Tiles*> tiles;

    //Sets the pointer to the tiles
    Enemy::setTilesPointer(&tiles);

    //Fills the lists
    gameOjbects.push_back(new Enemy());
    gameOjbects.push_back(new Enemy());
    gameOjbects.push_back(new Enemy());
    tiles.push_back(new Tile());
    tiles.push_back(new Tile());
    tiles.push_back(new Tile());

    for(int i = 0; i < tiles.size(); i++)
        gameObject.push_back(tiles[i]);

    //UpdateLoop
    while(true)
    {
        for(int i = 0; i < gameObjects.size(); i++)
            gameObject[i]->update();
    }
}

```

Since the "m\_tiles" variable in Enemy is static we only have to set it once and it will be the same for all Enemy objects.

Hope you got some deeper insight to the world of OOP and that I didn't waste your time :)

# Answer
> 0 votes
I would recommend you to decouple the graphic engine from the game logic. The classes for the game logic should not have any code which is related to drawing their visual representation. The drawing should be done by a separate `GraphicEngine` class which receives a reference to all the game data it needs to visualize and then decides internally how to draw them.

When you decouple the implementation of game logic and the graphic engine, you can easily make changes to either without affecting the other. You could even switch from a 2d engine to a 3d engine later without having to touch any code in your game logic. On the other hand, when the graphic engine is unaware of how the game logic works, you can also easily reuse the graphic engine for an entirely different game without having to change it either.

Being able to easily replace and combine components of an application is one of the most useful applications of object-oriented programming.

Besides: Decoupling game code and drawing code makes it easier to prevent the typical beginner mistake of tying game mechanics to framerate, which leads to the game running faster or slower depending on how fast the users computer is.

---
Tags: c++, tower-defense, oop
---


title: Multiplayer object interpolation

text:
# Question
Title: Multiplayer object interpolation
Currently I'm participating in a multiplayer game project as a network developer. Unfortunately, however, I'm facing an interpolation problem which makes game objects look like they are 'jumping/teleporting' sometimes. Images don't look smooth compared to the server even if the client runs at 60 frames per second.

Things about the architecture:

* Based on client/server model. server sends regular transform updates at every 33 milliseconds (30fps).
* Client receives and stores position updates in a queue. then, plays them from 1 second behind using interpolation between each update.
* Before processing the next packet, client calculates the sent time between current and next packet to find out how many milliseconds this interpolation should take. at every frame, it deducts the delta time from the interpolation time. so, if interpolation time reaches a number equal or less than zero, it iterates to the next packet (if the value is less than zero, it means that there is a time fragment. so the client also considers that time fragment for interpolation of the jumped packet at the same frame.)
* Client doesn't deal with rigidbody; only position and rotation.

I'm using Unity3D's LERP method from the Vector3 class. Using SLERP didn't solve the problem.

Any ideas? Everything looks great on *paper*.

# Answer
> 4 votes
It seems the problem caused by Unity's double typed timestamp which is included in the NetworkInfo packet. Since most of the Unity classes utilize from float instead of double, I was applying typecasting on the timestamp which was leading to loss of data.

After realizing that, I've inserted my own timestamp using Time.time (a float value) to each packet. Now, everything looks fine.

# Answer
> 0 votes
Linear interpolation should be fine. The trick is to figure out which two states to interpolate between, not the interpolation itself. Maybe this will help? http://gabrielgambetta.com/fpm3.html

I disagree with the other reply, you definitely need interpolation even if you don't lose packets (except if you get exactly one packet per frame with zero lag and zero loss, which is unrealistic)

# Answer
> -1 votes
If game objects can get the correct position updatings each frame there's NO need to use interpolation, you just update the position the same in single-player mode.

But packet loss always happens in WLAN, you may need to predict the game object transform in client.

---
Tags: unity, multiplayer, interpolation
---


# Question
Title: Animation of moving circle by square's outer surface
I want to make this animation in OpenGL, here I attached a simple gif how I want it to looks like:

Main problem is that I can not figure out how to move by corner - circle should smoothly move by corner, not to just jump to another side's begin position.

```
import Blender
from Blender import Draw,BGL
from Blender.BGL import *
from math import sin,cos
import time

squareLength, squareX, squareY, circleRadius = 200, 200, 200, 20
movingX, movingY = 0, 0

def event(evt, val):
    if evt == Draw.ESCKEY :
        Draw.Exit()

def gui():
    global movingX, movingY

    glClearColor(0.17, 0.24, 0.31, 1.0)
    glClear(BGL.GL_COLOR_BUFFER_BIT)
    glLineWidth(1)
    glColor3f(0.74, 0.76, 0.78)

    glBegin(GL_QUADS)
    glVertex2i(squareX, squareY)
    glVertex2i(squareX, squareY + squareLength)
    glVertex2i(squareX + squareLength, squareY + squareLength)
    glVertex2i(squareX + squareLength, squareY)
    glEnd()

    glColor3f(0.58, 0.65, 0.65)

    glPushMatrix()

    if movingX == -circleRadius:
      if movingY < squareLength:
        movingY += 1
      else:
        movingX = 0
        movingY = squareLength + circleRadius
    else:
      if movingY == squareLength + circleRadius:
        if movingX < squareLength:
          movingX += 1
        else:
          movingX = squareLength + circleRadius
          movingY = squareLength
      else:
        if movingY < 0:
          if movingX > 0:
            movingX -= 1
          else:
            movingX = -circleRadius
            movingY = 0
        else:
          if movingY > 0:
            movingY -= 1
          else:
            movingX = squareLength
            movingY = -circleRadius

    glTranslatef(movingX, movingY, 0)

    glBegin(GL_LINE_LOOP)
    for i in xrange(0, 360, 1):
        glVertex2f(squareX + sin(i) * circleRadius, squareY + cos(i) * circleRadius)
    glEnd()

    glPopMatrix()

    Draw.Redraw(1)

Draw.Register(gui, event, None)

```

Can you please say me, how can I optimize this code to make circle moving by corners?

Just start learning computer graphics and think up such exercises for training, so I will really appreciate for any help.

# Answer
Just did this using SDL but the theory is the same.

Make your circle orbit your square by the distance from the center of the square to the corner plus the radius of your circle.

Then limit the distance your circle can be from your square. Minimum would be -half square width -circle radius, maximum would be +half square width +circle radius.

Here's the code I used:

```
circle.x = lim(cos(circlePos*(3.1415/180))*(sqrt((float)sqrd(square.w/2)+(float)sqrd(square.h/2))+(circle.w/2)),(-square.w/2)-(circle.w/2),(square.w/2)+(circle.w/2))+square.x;
circle.y = lim(sin(circlePos*(3.1415/180))*(sqrt((float)sqrd(square.w/2)+(float)sqrd(square.h/2))+(circle.h/2)),(-square.h/2)-(circle.h/2),(square.h/2)+(circle.h/2))+square.y;

```

circle and squares are SDL\_Rect structs that just store an x,y,w,h. lim() and sqrd() are functions that I made to simplify stuff.
> 1 votes

---
Tags: opengl, animation, blender
---


title: When should I load my resources?

text:
# Question
Title: When should I load my resources?
I'm making a game, and right now I'm working on the user interface. I'm just wondering when I should be loading my resources.

**Should I do it in small pieces at a time?**

* Load resources for part 1 of menu
* Run part 1 of menu
* Free resources for part 1 of menu
* Load resources for part 2 of menu
* Run part 2 of menu
* Free resources for part 2 of menu
* (So on)

**Or all at once?**

* Load resources for all parts of menu
* Run part 1 of menu
* Run part 2 of menu
* (So on)
* Free resources for all of menu

It would seem to me that the pros of the first method are that my code can be much cleaner, as I can isolate the resources to specific parts of my class:

```
class UI {
    method run() {
         part1();
         part2();
    }
    method part1() {
         // part1's resources can be declared here
    }
    method part2() {
         // part2's resources can be declared here
    }
}

```

Whereas with the second method, it will probably run faster, but then all my resources have to be global:

```
class UI {
    // resources are declared here
    method run() {
        part1();
        part2();
    }
}

```

I'm using OpenGL, so right now what I'm doing is loading all my textures and audio at once, but I'm allocating and freeing my Vertex Buffer Objects as they're needed. For those of you who have more experience writing games, what method do you think I should use?

# Answer
I think it depends on several factors:

### How big your game is

If your game is small and can fit memory, it's much easier to load everything at once and keep it in memory.

If your game is strctured as levels, load everything you need and keep it in memory (e.g. UI, main character) and load each level resources when you need it.

### The nature of the game

Open world game are usually not stored all in memory, the loading/unloading (streaming) of the game can happen while you are traversing the level. But that also depends on the size of the world and the target platform. Keep in mind that loading resources doesn't mean freeing the VBO objects for example, those can re-used and dynamically updated.

### Your target platform

Programming on PC is different from consoles and mobiles. The latter usually have limited memory, so it's more likely you need to load resources on demand.
> 8 votes

# Answer
Use neither, because both approaches involve loading and freeing GPU resources at runtime, which is slow and will lead to constant thrashing of video RAM.

Instead what you should so is have knowledge of all UI resources needed at startup time, and load them all during program startup. Then when you need to use a resource for drawing, you just use the resource that's already been loaded.

If you can't have that knowledge (and you may consider it desirable to not require your startup routines to have knowledge of your UI requirements) you can load on-demand, which is a technique that some games use (the Quake series, for example). In that case, once a resource has been loaded, you keep it loaded: don't unload it. Then the next time you need it, you can once again just use the already loaded resource instead of having to load it again.
> 3 votes

# Answer
You dont want to constantly free things you loaded, once something is loaded keep it in memory, when its needed again, its already loaded in memory. In addition operations like file reading are expensive in themselves. Generally you should only Free something like that when you will never need it again.

For example if I have a Mesh for a Boss monster, I load it in memory during the transition to the room with the boss. It then stays in memory until the player dies and is teleported away, or it's Defeated. During the boss fight however I do not want to Free the mesh because its still in use.

For GUIs its slightly different, since they will almost always be on screen(excluding cutscenes) they should be loaded at the start of the game, and only be freed when exiting or closing the game. Even in cutscenes, leave them in memory and just don't render them that way when the cutscene is over. you dont need to read in all the GUI elements again.
> 2 votes

---
Tags: assets, efficiency, architecture
---


title: Saving & loading Data -String-

text:
# Question
Title: Saving & loading Data -String-
I need help finding a method to save some variables to a string that can be repeated in a text file, which will be stored in my `C:` drive. It will be storing data for multiple players. For example:

```
int one = 0; //(will be set from a different file)
int two = 0; //(will be set from a different file)
int three = 0; //(will be set from a different file)
String PlayerName;(set from a different file)

```

Saves like:

```
(1, 2, 3, player 1);
(1, 2, 3, player 2);
(1, 2, 3, player 3);
etc.

```

Whenever it's called from a player's action it will save that string to a text file.

My save and load methods so far:

```
public class Offers {

    public static List<Offer> offers = new ArrayList<Offer>(2000);

    public Offers() {
    }

    public static void saveOffers() {
        for (Offer offer : offers) {
            if (offer == null) {
                continue;
            }
            int id = offer.id;
            int item = offer.item;
            int amount = offer.amount;
            int price = offer.price;
            int currentAmount = offer.currentAmount;
            int removedAmount = offer.removedAmount;
            int type = offer.type;
            int completed = offer.completed ? 1 : 0;
            int aborted = offer.aborted ? 1 : 0;
            int currentPrice = offer.currentPrice;
            int slot = offer.slot;
            String owner = offer.owner;
            String VALUES(""+ id + "" + item + "" + amount + "" + price + "" + currentAmount + "" + removedAmount + "" + type + "" + completed + "" + aborted + "" + currentPrice + "" + slot + "" + owner + "");
        }
    }

    public static void load() {
        int id = stream.readShort();
        int item = stream.read();
        int amount = stream.read();
        int price = stream.read();
        int currentAmount = stream.read();
        int removedAmount = stream.read();
        int type = stream.readShort();
        boolean completed = stream.readShort() == 1;
        boolean aborted = stream.readShort() == 1;
        int currentPrice = stream.read();
        int slot = stream.readShort();
        String owner = stream.readString();
        if (id != -1)
            offers.add(new Offer(id, item, amount, currentAmount, removedAmount, price, type, owner, completed, slot));
            for (Offer l : offers) {
                if (l == null) {
                    continue;
                }
                if (l.id == id && l.item == item && l.amount == amount && l.currentAmount == currentAmount && l.price == price && l.type == type && l.owner.equals(owner) && l.slot == slot) {
                    l.currentPrice = currentPrice;
                    l.aborted = aborted;
                    break;
                }
            }
        }
    }
}

```

# Answer
I know its not what you asked, but may i suggest using xml instead to save your data. It seems that your current data structure would be better supported in xml not to mention it would be waaaaaay easier to implement.

writing xml files is super easy. as shown here

and reading is just as easy see this.

then you can save your data like so

```
 <saves>
       <players>
             <player1>
                  <data>x,y</data>
                  <data>name</data>
                  <data>level</data>
             </player1>
             <player2>
                  <data>x,y</data>
                  <data>name</data>
                  <data>level</data>
             </player2>
       </players>
</saves>

```
> 0 votes

---
Tags: java
---


title: Bounce off of objects

text:
# Question
Title: Bounce off of objects
How do I make my ball bounce off objects on the screen? I'm having trouble detecting the collision, as well as calculating the response.

The picture below is a good example of how the program should be working once the ball runs into an obstacle

I made the ball bounce off the walls, but what's left is making it also bounce off of objects. Thanks for the help!

Here's the source code:

```
public class 2DGAME extends Application {

    public static Circle circle;
    public static Pane canvas;
    private long counter = 0;
    double X = 0;
    double Y = 0;

    @Override
    public void start(Stage primaryStage) {

        canvas = new Pane();
        Scene scene = new Scene(canvas, 800, 600);

        primaryStage.setTitle("2D Ball Game");
        primaryStage.setScene(scene);
        primaryStage.show();

        circle = new Circle(20, Color.BLUE);
        circle.relocate(100, 100);

        final Rectangle r = new Rectangle(20, 20, Color.DARKMAGENTA);
        r.setLayoutX(400);
        r.setLayoutY(300);

        canvas.getChildren().addAll(circle);
        canvas.getChildren().addAll(r);

        Timeline loop = new Timeline(new KeyFrame(Duration.millis(5), new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                if (counter++ % 5 == 0) {
                    // Moves the ball depending on the values of X and Y
                    circle.setLayoutX(circle.getLayoutX() + X);
                    circle.setLayoutY(circle.getLayoutY() + Y);

//Code to bounce off walls
                    final Bounds bounds = canvas.getBoundsInLocal();
                    boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
                    boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
                    boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
                    boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());

   //Bugged and not sure how to make it work
                    final Bounds rectangleBounds = r.getLayoutBounds();
                    boolean rectangle_left = circle.getLayoutX() <= (rectangleBounds.getMinX() + circle.getRadius());
                    boolean rectangle_right = circle.getLayoutX() >= (rectangleBounds.getMaxX() - circle.getRadius());

   //If the bottom or top wall has been touched, the ball reverses direction.
                    if (bottomWall || topWall) {

                        Y = Y * -1;
                    }
    // If the left or right wall has been touched, the ball reverses direction.
                    if (leftWall || rightWall) {
                        X = X * -1;
                    }

    //Bugged code for boucning off obstacle object
                    if (rectangle_left || rectangle_right) {
                       // X = X * - 1;
                    }

                }
            }

        }));

        loop.setCycleCount(Timeline.INDEFINITE);
        loop.play();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

```

# Answer
Just use the same bounds checking you do with your walls but this time apply it to your object.

For each update :

* Check where the ball is
* Check where the object is
* Check if they collide
* Check from what angle is the collision
* Bounce your ball like with your walls

If there are multiple objects (and I mean like hundreds) you might want to narrow down your collision checking so that you don't check unnecessary objects.
> 4 votes

---
Tags: java, 2d, collision-detection
---


# Question
Title: Random lines away from images in java2d opengl game
Working on a java game that uses some pngs images for icons/textures. A few images ( fewer than 5, out of dozens ) are showing some odd parallel "artifact" lines. They move with the image, are certainly not in the PNG itself.

I can't figure out what's causing it. Using slick2d, lwjgl. I've tried slcik2d and opengl methods of clamping textures but that didn't help.

This black line is showing off the right-hand side of an icon (maybe 50% of the actual image width away). It should not be there.

# Answer
> 1 votes
i think that is because textures are loading using power of 2. and you are probably using the texture width and height to render the image onto a quad. what you should do instead is use the images relative size from withing the texture.

it should be a floating point number such as 0.67080760(or something) since 1f would be the total width and height of your image.

I only say this because i ran into the same problem when i started working with lwjgl(ive never used slick2d but its based on lwjgl) and what i suggested fixed the image irregularity.

---
Tags: opengl, java, slick
---


# Question
Title: Version control for game development - issues and solutions?
There are a lot of version control systems available, including open-source ones such as Subversion, Git, and Mercurial, plus commercial ones such as Perforce.

How well do they support the process of game-development? What are the issues using VCS, with regard to non-text files (binary files), large projects, et cetera? What are solutions to these problems, if any?

For organization of answers, let's try on a per-package basis. Update each package/answer with your results.

Also, please list some brief details in your answer, about whether your VCS is free or commercial, distributed versus centralized, etc.

*Update*: Found a nice article comparing two of the VCS below - apparently, Git is MacGyver and Mercurial is Bond. Well, I'm glad that's settled... And the author has a nice quote at the end:

> It’s OK to proselytize to those who have not switched to a distributed VCS yet, but trying to convert a Git user to Mercurial (or vice-versa) is a waste of everyone’s time and energy.

Especially since Git and Mercurial's real enemy is Subversion. Dang, it's a *code-eat-code* world out there in FOSS-land...

# Answer
# Git

Recently I have been on the **Git** bandwagon (I've used SVN and Mercurial). So far I really like what I get with Git. It is far from a pain to setup and more development tools are starting to adopt using it.

It's a distributed version control system. This allows for us to have our own independent trunk-like area. I can work in my own area and invite you over to view changesets very easily. I can rollback in my own space without mucking up the central repo. I can commit, branch, and do everything you can do with SVN locally. I really like having this control.

With SVN, you need access to your repo in order to commit. What if you're on the road or at a cafe with no internet? Not good.

Sure, SVN is much simpler to learn but I think the advantages of distributed source control largely outweigh the fact that it has a little learning curve.

I also like that it is smarter about merging.

A major downside of GIT is that it stores the entire history locally. (Yes, you can perform surgery to cut that down, but it's the default behavior). It's not a problem at all for source files, but if you have a large project with gigabytes of asset data, it becomes a problem quickly. In my current experience, I'd recommend GIT only for smaller or source-only repos.

If you're still curious about GIT, check out http://thkoch2001.github.io/whygitisbetter/ for some good information/metrics. Also check see https://git.wiki.kernel.org/index.php/GitSvnComparsion
> 74 votes

# Answer
## Mercurial

Key features:

* Distributed VCS
* Free, open source
* Plugin scripts are easy to write---can be written in Python or as shell scripts
* There are many plugin scripts already freely available
* Lots of documentation available, including this book (highly recommended)

With regard to the use of non-text files, last versions of Mercurial (\>=2.0) provide the largefile extension **by default**:

> largefiles solves this problem by adding a centralized client-server layer on top of Mercurial: largefiles live in a central store out on the network somewhere, and you only fetch the ones that you need when you need them.

There are other extensions providing similar solutions like the bigfiles extension which lets you store your assets in the same Mercurial repo, but only fetch the binaries you need when you need them.

I am not aware of any issues with regard to large projects beyond those related to having large binary files. The Python project is a large project and uses Mercurial.

Joel Spolsky has written a mini-tutorial on using Mercurial at Subversion Re-education
> 65 votes

# Answer
# Perforce

Perforce (commercial/closed-source, centralized) is the industry standard for a number of reasons.

1. It's a commercial product, which means it comes with commercial support. Open-source projects may be eligible for a free license (minus the technical support).
2. It supports workspaces *very well*, which allows very flexible source and asset directory layouts.
3. It supports changelists *very well*.
4. You can see who is working on what. Games have an abnormally high number of rapidly changing binary files (assets) compared to other development projects. Most of the time these are non-mergeable, so keeping track of who has what/where/when is critical. Subversion and DSCC clients intentionally avoid this technique, but it's quite beneficial in certain applications.
5. It supports *gigantic* code/asset bases. It does *not* store duplicate data on client machines, which is important when your sub-view of the tree is a couple dozen gigs.

That said, it's painfully obvious on an almost daily basis that Perforce doesn't feel their position in the industry is threatened. Their visual tools, including P4V and P4SCC (integrate with Visual Studio) are slow and buggy, with the latter known to freeze Visual Studio for the sheer enjoyment of it. AnkhSVN is miles ahead of Perforce.

Comment by xan: It is worth noting however that their merge tool, P4Merge (used for diffing and merging) is excellent and far superior to the likes of Tortoise Merge. Surprisingly, this component is available for free as part of the P4 Visual Tools package.

Comment by slicedlime: Another drawback with Perforce is that branching in it tends to be a huge pain, especially if you have large trees. Almost every other vcs is better at branching and merging. This is usually a small price to pay for the above advantages though.

Comment by roe: Perforce is extremely chatty. There's not much going on without the server involved. Most notably, you need the server in order to do open-for-edit, which means you need to jump through a few hoops if you intend to break the connection to the server.

Comment by jrista: As a daily user of Perforce for over two years now, with an extended development and quality engineering team of well over 100 people, I have become intimately familiar with it. While it is a decent source control system, it does have its drawbacks that those evaluating SCC systems should be aware of:

* As mentioned by others, branching/integrating is particularly cumbersome and difficult to do. You have an ungodly amount of control, but it comes at the cost of excessive complexity. On the flip side, the visual merge tool is one of a kind, and presents a beautiful three-file "based" merge view of your work. Perforce does provide some graphical visualizations of branch paths (called the Revision Graph), however the way it is visualized often makes the tool rather useless. If you only need to see a very small segment of time for one or very few files, it can be useful...anything more, and it is near impossible to navigate the Revision Graph.
* Perforce is also not a very efficient tool, as almost any file operation requires duplicating files and data: branching, labeling, change lists, etc. No sparse or lightweight tagging or branching here. If you are not afraid to use a tremendous amount of disk space tracking your changes, perforce will probably serve you well. If not, I would look to another tool.
* Perforce makes use of workspaces, however these can be frustrating at times, as perforce caches all state in your workspace, rather than using the actual files on disk to determine some state. This often results in files not getting synced because your workspace says they are up to date, when, for whatever reason, the physical files on disk are indeed NOT up to date.
* A final annoyance, Perforce is rather brutal on your network. It is an extremely chatty program, and consumes a considerable amount of bandwidth. Any network connectivity loss, and you run the high risk of being unable to do any work with your source-controlled files until connectivity is restored. As of yet, I have not discovered an activity that can be performed off-line in Perforce.
> 44 votes

# Answer
## Subversion

* Open-source, centralized
* Blender files - I'm not entirely sure if .blend files are binary (they look like it), but I have had no problems adding them to Subversion. Having done a few experiments, the file size increase for changed files appears nominal, so it's not simply copying in the entire file.
* Large projects - It works, though it can get quirky. It's definitely *able* to handle repositories of at least 5.5 GB (total size of repository dir on server; mostly binary assets).
* Duplicated Data on the Client - Subversion keeps a duplicate copy of every file in the user's workspace as a pristine copy. The advantage of this is you can do a diff or revert without going back to the server. The disadvantage is that your 10 gig of working files takes 20 gig of disk space.
* The ignore list is a property of a directory (simple with a gui, annoying on the command line).
* Subversion allows locking of files/assets - which is really helpful if multiple artists and designers work on the same files.
* Externals are a great way to handle shared (e.g. library or base) code between projects.
> 28 votes

# Answer
## AlienBrain

From Avid:

> Alienbrain is a digital asset management system for artists in the entertainment industry

* Commercial (more expensive than Perforce), centralized
* Designed to integrate with other professional 2D and 3D workflow tools such Photoshop, Maya, 3ds Max, Microsoft Visual Studio, etc.

I have *no* experience with AlienBrain, and only heard about it from the book Game Coding Complete by Mike McShaffry. He appears to think highly of it, however:

> Artists and other contributors will actually use this product, unlike others that are mainly designed to integrate well with Visual Studio and not creative applications such as Photoshop and 3D Studio Max. One of the big drawbacks of other products is their rather naive treatment of nontext files. AlienBrain was written with these files in mind.

Of course he also describes it as:

> For those of you with really serious asset tracking problems and **equally serious budgets**...
> 8 votes

# Answer
## Team Foundation Server

from Microsoft

* Commercial
* Centralized
* Integrates very well with Visual Studio
* Good Windows Explorer integration for non VS users (ie artists)
* Supports "Shelved" changesets, which is somewhat analogous to 'stashing' in git, but it goes up to the server; you can also make these shelvesets public, to allow other users to integrate them for you.
* Since 2012 it has a some very good code-review workflows built directly into Visual Studio
* Latest version of the merge tool is very nice. Auto merge works pretty well.
* Supports large and bindary files just fine (obviously you can't merge them)
* Very good build server
* Supports gated check-ins, which allow the quality of a shelveset to be evaluated (through automated builds, unit tests, code analysis) before it is committed to the repository.
* Very good project management tools (not strictly source-control features, but really useful), giving traceability from high-level requirements down to code.

I've used TFS extensively on MILSPEC simulator projects, and it is pretty good. Probably not the greatest if you're on a Mac, although there is an eclipse plugin these days. The cloud-hosted version supports git repositories for the source-control back-end.

It's free for up to five users on Visual Studio Online (allows closed source; no repository size limits), where it's hosted in the cloud. If you want to host it locally, it can be pricey.

The things I like most about it are the software engineering management features, and the fact that it handles large files and binary files quite happily.
> 4 votes

---
Tags: version-control
---


# Question
Title: What is the point of "delta" in this code? Does it reflect a standard thing in game dev?
I know very little about game programming but would like to learn more. I am trying to understand the code for this game. I am trying to understand why the code is passing a "delta" to Shipcontrols.js, which changes the direction of the ship based on user input.

Basically the game calculates "delta" every loop...

Here is an abbreviated version of the stack that uses delta thru one loop...

```
var delta = now - this.time;
this.time = now;
this.current.render.call(this.current, delta, this.renderer);

```

Steps into here...

```
ctx.manager.add("game", scene, camera, function(delta, renderer)
{
if(delta > 25 && this.objects.lowFPS < 1000) this.objects.lowFPS++;
var dt = delta/16.6;
this.objects.components.shipControls.update(dt);

```

Steps into here...

```
bkcore.hexgl.ShipControls.prototype.update = function(dt)
{
var pitchAng;
var yaw;
var roll;
if (undefined != hand){

```

Which does stuff like this...

```
if(this.key.forward)
    this.speed += this.thrust * dt;
else

```

and this...

```
if(this.key.right)
{
    angularAmount -= this.angularSpeed * dt;

```

What is the point of delta here? Is it just trying to introduce an element of randomness? The code for this game is very good. Why did this guy use delta?

# Answer
> 27 votes
This is the "time delta." It's how much time has elapsed since the previous update. It's necessary to ensure that animations, physics, and so on are running at the right speed.

The code is running once per frame update. However, there's no guarantee that frames are drawn at a constant speed. One frame might take 1/60th of a second and the next might take 1/30th. If you don't measure for and account for this, the game will be jittery and run either too fast or too slow in various circumstances.

Time deltas are often applied in physics as that's how the equations are specified for simple Euler integrations. Integrating velocity into position is defined as `x1 = x0 + v * (t1 - t0)` which simplifies into code like `x += v * dt`. Hence, time deltas are required to evaluate physics updates.

It is very, very normal for time deltas to be measured and applied.

# Answer
> 32 votes
"Delta", "d" or "Δ", means "difference" in a mathematical context. Whenever there's a difference difference between two numbers with similar meanings, that difference may be called a "delta", or a "d".

Deltas are very common in game development. For example, the difference between a character's X-coordinate one second ago and its X-coordinate now can be called "delta x", and is commonly denoted as `dx`, `delta_x` or `d_x`.

Also, it is very common to have the difference between two times, as you have in your code:

```
var delta = now - this.time;

```

In this case, that variable is denoting the difference between some time stored in `this.time`, and the time stored in `now`.

Deltas are commonly used to represent the change of something in time. So for example, if you know that a player's X coordinate should change 5 pixels every frame, you can store this change as a delta:

```
var delta_x = 5

```

And then use that delta to apply the change whenever you need it:

```
player.x = player.x + delta_x

```

But remember that this is only a convention. Nobody forces you to name your variables "delta" or "d", but doing so may help somebody else who reads your code, or yourself if you read it in the future, to understand what the variable is supposed to do.

Other common greek letters widely used in programming are:

**Epsilon**: for a very small value. Commonly used when comparing floating point, or other variables with precision problems:

```
const epsilon = 0.0001
...
if abs(some_float - other_float) < epsilon then
    -- close enough, let's say they're equal
end

```

**Pi**: for the eponymous constant

**Theta**: for representing angles

**Lambda**: for representing anonymous functions or closures

# Answer
> 3 votes
`dt` stands for `delta time`. It is used in the calculation of frame rate to insure the game runs at the same speed no matter what the frame rate is.

More information on `framerate independence` can be found here.

# Answer
> 3 votes
dt (delta time) is the time between each cycle/render frame (or any time stamp you desire) of your loop. With this delta time we can stretch certain values over time. Just like in the real world we measure certain physics properties over time.

Let's say we run our game 60 frames a second. If we want our our player to move 5 pixels per second we do

```
 5 * (1/60); //Assuming we have a stable delta time of 0.016
 // (1/60) = 0.016 || 0.016 * 5 =  0.083 --> moved per frame || 60 frames * 0.083 = 5

```

or

```
 5 * (newTime - oldTime); //aka dt

```

The character moves 5 pixels over 60 frames. The longer your cycle takes the bigger delta time will get.

For every framerate (1/30, 1/25, etc) the result will be the same.

---
Tags: physics, game-loop, control, motion-control
---


# Question
Title: Combining assets with different licenses
Is it OK to mix assets that are Creative Commons 3.0 BY-SA with other assets that are in the Public Domain in the same project? Thanks.

For instance here.

# Answer
> 2 votes
If you abide by the terms of all of the licenses, sure. Combining a BY-SA work with a public domain work results in a BY-SA work.

What "combining" means *might* include using them in the a project. It's legally fuzzy whether a whole media like a game is a "derived work" of its individual assets or not and may well depend on how critical a judge or jury deems that asset is to the game.

Safest bet is always to just make everything in-house from scratch.

# Answer
> 1 votes
Public Domain means either that the copyright has expired and thus it may be used freely or it means that the author relinquished all rights they have to the work as far as legally possible (in some jurisdictions it is impossible to do that). That also means that a PD work can be taken and relicensed under a different license like CC-BY-SA, GPL, BSD, MIT or a proprietary work. PD is not viral.

When your alterations to a PD work have enough merit to be eligible for copyright themself, these altered versions lose their PD status. Example: Beethoven's Symphony Number 5 is public domain (author died more than 70 years ago) but an audio recording of an orchestra playing it is not public domain, because their interpretation is eligible for copyright. A sheet displaying the notes can also be copyrighted, because the layouting and design is eligible for copyright, even though the content is not.

It would, however, be fair for end-users and licensees of your work when you would state which parts are unaltered from public domain sources so they know that they can reuse them individually without having to adhere to CC-BY-SA.

---
Tags: art, licensing
---


# Question
Title: Why do the ALPHA channel in TGA is not visible?
Good morning GDSE,

I am loading a TGA using loadTGA function found in superbible 4th edition source code. Here is how the image looks in Gimp

You can see I have enabled alpha channel in Gimp, I exported this to TGA image, without RLE compression, and 32bpp. But when I load the image in my OpenGL code, the part of the image which is supposed to be transparent is seen white.

Where I must be going wrong? The type of TGA is set to GL\_RGBA, 32 bpp.

Here is my Fragment shader code.

`out_fragColor = (vec4( ambAndDiff, 1 ) * texColor) + vec4(spec,0.0);`

I have calculated ambAndDiff and spec values earlier using ADS phong shading, and both of them are vec3. Let me know if you also want to view the TGA loading code. :)

Regards, A.

# Answer
> 1 votes
You have most probably not set the correct blendstates to the gpu. If you have not, the gpu dont know how to handle your Alpha values.

this link is a good resource on how blendstates works. and how you should use them.

Basicly alpha is only anohter channel containing data. the texture itself never states what blendmode will apply or how the gpu will use it. that is all done by code.

---
Tags: opengl, textures, glsl, alpha
---


# Question
Title: How do I know if my game's average game session time is too small?
My game has only one life, and the aim is to stay alive as long as possible to get as many points as possible (it's an endless runner).

Using Google Analytics I found that players are staying alive for an average of 17 seconds. I could easily increase or decrease this by manipulating acceleration or starting speed. The question is, should I change it at all? Is there any research or general ideas on the best playing time for a game like this? I would also like to know about any research about how long an ideal mobile game session should last.

# Answer
**17 seconds most probably will be frustrating for your players.**

The proper way to do things would be to **do playtests** \- ask some strangers to play the game for a few minutes while you watch. Also, play the game yourself! What is YOUR average life time in your game?

It is important to **playtest with unbiased people** \- your friends or family might say they like the game even if its terrible.

You should make notes. Does the player know how to interact with the game? Does he make mistakes? What makes him frustrated? What does he seem to enjoy?

Only **after doing your own observations you may ask the player for an opinion**, but it usually wont be as useful as your own observations. You as a game designer should have a better understanding of how games work and utilise a broader vocabulary of game related terms to verbalise the design problems your players encounter.

**There is no single mobile game session time.** Some people will play it at for three minutes, waiting for a bus, others will play for half an hour while commuting. **The game should be designed with a specific playtime in mind**, this should not be left out. The game should be designed to trigger some emotions and have a conclusion in the specified playtime. You cant do that in 17 seconds. Your game probably gets too hard to fast, making people quit after the first or second try.
> 3 votes

---
Tags: game-design, mobile
---


title: UDK - deferred rendering?

text:
# Question
Title: UDK - deferred rendering?
I plan to use UDK on PC to create commercial game. Can I use deferred rendering in UDK? Or it's only available with expensive UE3 license?

# Answer
With UDK, you have access to the whole UE3 kit, you will have to pay only when you start earning money. This means you have access to the deferred rendering.

> UDK provides access to the full UE3 feature set

Source: http://www.unrealengine.com/files/downloads/Why\_Independent\_Developers\_Turn\_To\_UDK.pdf

It could be expensive, if you are making millions. But still their royalties are quite fair
> 2 votes

---
Tags: udk
---


# Question
Title: Running multiple box2D world objects on a server
I'm creating a multiplayer game using LibGdx (with Box2d) and Kryonet. Since this is the first time I work on multiplayer games, I read a bit about server - client implementations, and it turns out that the server should handle important tasks like collision detection, hits, characters dying etc...

Based on some articles (like the excellent Gabriel Gambetta Fast paced multiplayer series), I also know that the client should work in parallel to avoid the lag while the server responds to commands.

Physics wise, each game will have 2 players, and any projectiles fired.

What I'm thinking of doing is the following:

1. Create a physics world on the client
2. When the game is signaled to start, I create the same physics world on the server (without any rendering obviously).
3. Whenever the player issues a command (move or fire), I send the command to the server and immediately start processing it on the client.
4. When the server receives the command, it applies it on the server's world (set velocity etc...)
5. Each 100ms, the server sends the new state to the client which corrects what was calculated locally.
6. Any critical action (hit, death, level up) is calculated only on the server and sent to the client.

Essentially, I would have a Box2d World object running on the server for each game in progress, in sync with the worlds running on the clients.

The alternative would be to do my own calculations on the server instead of relying on Box2D to do them for me, but I'm trying to avoid that.

My question is:

1. Is it wise to have, for example, 1000 instances of the World object running and executing steps on the server? Tomcat used around 750 MBytes of memory when trying it without any object added to the world. Anybody tried that before?
2. If not, is there any alternative? Google did not help me, are there any guidelines to use when you want to have physics on both the client and the server?

Thanks for any help.

# Answer
> 2 votes
The memory usage won't be the bottleneck in your game server, since an instance of the world object does not take that much memory. Tomcat alone takes a lot of the 750MB of memory you observed. The real issue will be CPU cost, if you have 1k instance of world with 2 players and many projectiles on each, your server will have some hard time unless it is very very powerfull. Even there, you will be limited on the number of players.

One solution could be having a dispaching server, where users will connect first and that will redirect the them on a light loaded server, that can run multiples instances of the world object. Of course if you have only 1 server, this won't help you but if you can have 2k players playing your game, I guess you can rent another server, all will be ready if you code it early. With this technique you virtually have no limit in the number of players.

Another solution, but this is not what you want at a first look, is creating the server on one of the two players, where every calculations will be done. From time to time, results will be sent to a master server that will check if everything has been done without cheat. (Using some hash and challenge over network to check if client and servers are acting as expected) But you will have to work a lot on predictions because one of the players will have lower ping. No limit in the number of players there too.

I think there is other ways to deal with your issue, but this is what came to my head.

Good luck for your project

---
Tags: architecture, box2d, libgdx, multiplayer, client-server
---


title: Overlaying grid for pathfinding

text:
# Question
Title: Overlaying grid for pathfinding
My game is not grid-based, so units can be at any arbitrary coordinate and move at different speeds. My obstacles are all rectangular and axis-aligned, so naturally it makes sense for me to overlay a grid over the map for pathfinding. Each unit will take up a grid cell (floor(unit.x / CELL\_SIZE), floor(unit.y / CELL\_SIZE)). I will then run standard A\* grid-based pathfinding on the grid.

The problem is that although the path is grid-aligned, the unit movement is not. Thus, in the midst of moving, the unit might end up colliding with a cell that is blocked, and get stucked. Here's a picture to illustrate:

I'm trying to get from point A to point B. B is the center of the grid cell, since it is a waypoint from the found path. A is the point the unit is currently at. The pathfinder thinks A to B is valid movement, since it takes the grid cell of A as the start point and the diagonal neighbour B is not blocked. But moving from A to B might result in position C, which is blocked.

I thought of using a soft collision radius for pathfinding, but it has its problems. The pathfinder will not return any paths where there's a soft collision. So if the current location of the unit already has a soft collision, the unit cannot move! It seems that it is necessary to keep the pathfinding collision and physics collision **identical**...

How do I resolve this problem, and what is the standard way to overlay a grid for pathfinding?

# Answer
> 2 votes
A simple solution would be to only allows a diagonal movement in the graph you use for pathfinding if both of the corresponding vertical and horizontal cell are clear.

In your case, since C is not clear, you should no be autorized to go from A to B directly.

---
Tags: path-finding, grid
---


# Question
Title: Using forces to reach a specific velocity
In my game, I currently move the player by **directly setting its velocity** on key press events. This makes the game feel very responsive and allows the user to quickly change direction.

However, I would like to implement *knockback* and elements like *conveyor belts* that should push the player around. My first idea was to add a `bool underControl;` variable that was set to `false` when the player was under the effect of an external force, but it didn't work well in practice.

Then I thought of another way: how about **adding the exact required force to move/stop the player at a desired velocity** instead of acting on the velocity itself? It would allow the user to move and stop like if velocity itself was being set, but also allow external forces to act on the player.

Basically I want this:

```
if(someKeyPressed()) player.setVelocityX(100); else player.setVelocityX(0);

```

to be expressed like this:

```
if(someKeyPressed())
    player.applyForce(getForceRequiredToReach(100, player.getVelocityX());
else
    player.applyForce(getForceRequiredToReach(0, player.getVelocityX());

Vec2f getForceRequiredToReach(float mDesiredVelocity, float mCurrentVelocity)
{
    // What goes in here?
}

```

How can I implement the `getForceRequiredToReach` function?

# Answer
As discussed in comments,

```
float getForceRequiredToReach(float mDesiredVelocity, float mCurrentVelocity)
{
    return mDesiredVelocity - mCurrentVelocity;
}

```
> 3 votes

# Answer
I cannot recommend using forces to set velocities. Using forces is for altering a player's acceleration, not for setting velocities.

If you know what velocity you want, just set it. If you want something to reach a certain velocity over time, use some kind of interpolation, setting the velocity as you go.

Forces become even more complicated when you remember that the results from forces are dependent upon the mass of the object being acted upon.
> 0 votes

# Answer
This is my code from a little platformer I made. Not sure if it will have the effects you want, but it's way of moving the player using forces. I used Java with Box2D, in case you're wondering. (The code isn't very cleaning as it was for testing mostly, but it works. :P)

```
    if (keys.get(Keys.LEFT)) {
        float desiredVel = -6f;
        float velChange = desiredVel - collidable.getBody().getLinearVelocity().x;
        float impulse = collidable.getBody().getMass() * velChange;
        collidable.getBody().applyLinearImpulse((new Vector2(impulse, 0f)), collidable.getBody().getWorldCenter());
    }

    if (keys.get(Keys.RIGHT)) {
        float desiredVel = 6f;
        float velChange = desiredVel - collidable.getBody().getLinearVelocity().x;
        float impulse = collidable.getBody().getMass() * velChange;
        collidable.getBody().applyLinearImpulse((new Vector2(impulse, 0f)), collidable.getBody().getWorldCenter());
    }

```
> 0 votes

# Answer
```
Vec2f getForceRequiredToReach(float mDesiredVelocity, float mCurrentVelocity)
{
    // What goes in here?
}

```

The function prototype will not allow the function to work as you expect. You are passing two scalars and you are expecting a vector as return value. Since, as you stated in an comment, your objects are without mass, so you need to treat acceleration rather than force. Given the current velocity and the desired velocity as scalar you can calculate the required acceleration (also a scalar) to reach the desired velocity within some time (let's call it `t`)

```
float getAccelerationRequiredToReach(float mDesiredVelocity, float mCurrentVelocity, float t)
{
    return (mDesiredVelocity - mCurrentVelocity) / t;
}

```

If you apply this acceleration for the time of `t` on your object it will slow down/ speed up to the desired velocity.
> 0 votes

---
Tags: c++, physics, movement
---


title: Breakout intersection logic issues

text:
# Question
Title: Breakout intersection logic issues
I'm learning Lua and thought I should try my hand at making a Breakout clone. It is pretty much playable, but there seems to be odd intersection logic at some points, specifically the ball-brick collisions.

In case you can't tell, the ball is behind 2 bricks (left-most light blue and dark brown). Also, most of the bricks that are missing seem to have been detected correctly.

I cannot seem to figure out why this is happening. Here is the code:

```
for i=1,rows do
  for j=1,cols do
    if bricks[i][j].x~=nil then

      --ball is between left and right edges
      if ball.x+dirx>bricks[i][j].x-radius and ball.x+dirx<bricks[i][j].x+length+radius then

        --ball is between top and bottom edges
        if ball.y+diry>bricks[i][j].y-radius and ball.y+diry<bricks[i][j].y+8+radius then

          --Ball hit top/bottom?
          if ball.y<bricks[i][j].y or ball.y>bricks[i][j].y+8 then
            diry=-diry  -- Reverse Y velocity
          end

          --Ball hit side?
          if ball.x<bricks[i][j].x or ball.x>bricks[i][j].x+length then
            dirx=-dirx  --Reverse X velocity
          end

```

I've kind of been doing this Lua thing on-the-fly so if I am doing any bad practices I'd appreciate knowing how it should be done.

# Answer
I haven't debugged your code for you, so here are some bits of general advice on how to make things more robust:

---

`dirx = -dirx` is a problematic way to implement bouncing, because if for whatever reason the ball is *already* inside an obstacle, or already moving the right direction, it will then be bounced the wrong direction and oscillate back and forth, and possibly zigzag its way into an even worse place. This could happen in your program if, for example, the ball hit two bricks simultaneously (the direction will be reversed twice).

Better is to set the sign appropriately. (Pseudocode:)

```
if collision on the left then
   dirx = abs(dirx)
else if collision on the right then
   dirx = -abs(dirx)
end

```

---

It also looks like your collision logic depends on the ball being just at the edge (its center being within `radius` but outside the brick itself) to determine collision direction. This could miss collisions. It would be more robust to, once you've decided a collision has occurred (the two outermost `if`s as they are), write logic which decides *which direction the collision was* and always gives *one* answer under all circumstances (never "both horizontal and vertical" and never "neither", which are both possible with your current logic).

---

Since you ask about bad practices: you have massively repetitive code and magic numbers. Take out that recurring 8 and use local variables to hold relevant values:

```
brick = bricks[x][y]   -- do this only once in the loop!
brickLeft = brick.x
brickRight = brick.x + brick.length    -- better: use a method on the brick
brickTop = brick.y
brickBottom = brick.y + BRICK_HEIGHT

```

Then you should never have to write `bricks[x][y].anything` again inside the collision logic.
> 3 votes

# Answer
For some reason, the center of the bricks is the x value. Changing the if statement to the following seems to have worked:

```
if ball.x+dirx>curBrick.x-radius-length/2 and ball.x+dirx<curBrick.x+length/2+radius then
  if ball.y+diry>curBrick.y-radius-4 and ball.y+diry<curBrick.y+4+radius then

```
> 0 votes

---
Tags: lua, corona-sdk
---


# Question
Title: What is the depth that a pixel shader may output? Is it necessary to write Depth?
In DirectX11, what does the depth that a Pixel Shader can output mean? Does a pixel shader need to output a depth so that we "write" the depth? If not, why would we output it?

For any doubts, I'm talking about the depth described in the last paragraph of this page of the MSDN documentation:

http://msdn.microsoft.com/en-us/library/windows/desktop/bb205146(v=vs.85).aspx#Pixel\_Shader\_Stage

# Answer
> 2 votes
The depth it is referring to is the depth value of a pixel, often (though not always) on a scale of 0 - 1 (relative, although usually nonlinearly, to the near plane and far planes).

This value is used for something called depth testing, or z-testing. Depth testing is an optimization that prevents pixels from being written to the buffer if they would be occluded by something that is closer to the near plane. This also makes ordering of opaque objects less important, and enables many post processing effects that are dependent on depth. This link provides additional information.

Depth testing is an optional step in the rendering pipeline that can be enabled or disabled at will. You will also frequently hear about the depth stencil buffer, which is a single buffer, that combines both depth and stencil testing values into separate channels as an optimization.

# Answer
> 0 votes
Depth Testing has it's advantages in Shadow Mapping and Light Mapping. If you were to create a render target at a point light location - you can have interesting effects with this sort of thing. I believe that's how ambient occlusion works but I've not yet ventured in that area yet. I want to maybe soon. I believe deferred lighting also uses depth buffer, normals, diffuse and another render target which I'm not sure what it is. In addition, I believe that's how sub-scattering surfaces work too! I have to dig deeper and get my hands into that stuff before I can say it's for certain.

---
Tags: directx, graphics, directx11, fragment-shader, sharpdx
---


# Question
Title: Circle to Circle collision - bad accuracy
Circle1 (blue) is moving and its X and Y bounds are the screen (meaning it bounces off the walls).

Circle2 (black) is stationary. Circle1(blue) is supposed to bounce off of Circle2 **without intersecting**, regardless of the collision point. As you can see on the image below, the blue circle bounces off properly only at the blue arrow spots, otherwise(red arrows), blue ball goes **INSIDE** the black circle, gets stuck in there for a second and then gets out.

I have no idea why this is happening. Please take a look at my code and help me out. Thanks.

```
public void handle(ActionEvent t) {
                if (counter++ % 5 == 0) {
                    // Moves the ball depending on the values of X and Y
                    circle.setLayoutX(circle.getLayoutX() + X); //velocity
                    circle.setLayoutY(circle.getLayoutY() + Y); //velocity

// Bounce off the walls (working perfectly)
                    final Bounds bounds = canvas.getBoundsInLocal();
                    boolean leftWall = circle.getLayoutX() <= (bounds.getMinX() + circle.getRadius());
                    boolean topWall = circle.getLayoutY() <= (bounds.getMinY() + circle.getRadius());
                    boolean rightWall = circle.getLayoutX() >= (bounds.getMaxX() - circle.getRadius());
                    boolean bottomWall = circle.getLayoutY() >= (bounds.getMaxY() - circle.getRadius());

//THE PROBLEM IS HERE

//Collision between circle1 and circle2 (stationary black circle.
                    double dx = circle.getLayoutX() - circle2.getLayoutX();
                    double dy = circle.getLayoutY() - circle2.getLayoutY();
                    double radii = circle.getRadius() + circle2.getRadius();

                    if ( (dx * dx) + (dy * dy) <= radii * radii) {
                        X = X * -1; //X gets inverted to change direction

                    }

 //The code below is working perfectly.
                    // If the bottom or top wall has been touched, the ball reverses direction.
                    if (bottomWall || topWall) {

                        Y = Y * -1;
                        //circle.setLayoutY(circle.getLayoutY() - 50); - Wasn't working. Had to create X and Y to fix the problem.

                    }
                    // If the left or right wall has been touched, the ball reverses direction.
                    if (leftWall || rightWall) {
                        X = X * -1;
                    }
                }
            }

        }));

        loop.setCycleCount(Timeline.INDEFINITE);
        loop.play();
    }

```

P.S. Apologies for the amazing paint skills :D

# Answer
> 3 votes
See this tutorial on circle-circle collisions: http://gamedev.tutsplus.com/tutorials/implementation/when-worlds-collide-simulating-circle-circle-collisions/

You seem to have most of the code implemented - go down to Step 4 (I think that's it anyway). It shows you how to calculate the new velocities.

You might have to change how you calculate your updates, as you have to update `circle` and `circle2`'s velocities at the same time (I'm not sure how that works for you).

Note, I could post some of the equations here, but 1. it'd be just a copy-paste (not sure about plagiarism), and 2. they are quite long.

---
Tags: java, 2d, collision-detection, mathematics
---


title: Camera chasing player

text:
# Question
Title: Camera chasing player
I want the camera to follow the player and lag a little bit and then catch up with the player when the player halts. When stopped the player is in the center.

At the moment im at the point where i get the camera to move with the player but i dont know how to get the lag effect!

On the camera object

```
    void Update () {
    var newX =  player.transform.position.x;
    var newZ =  player.transform.position.z;
    var y = transform.position.y;
    transform.position = new Vector3(newX, y, newZ);
}

```

# Answer
> 2 votes
In Unity `LateUpdate` is meant to be called after all the other updates are done. You'll want to utilize this method because you want to ensure the player position has been updated before you update the position of your camera. (Actually the Unity documentation mentions something very similar.)

Now that we know where to put it, there are two ways I can think of to make the camera follow the player:

**Use any kind of interpolation:** A simple example might be linear interpolation, expressed in parameterized vector notation, vectors are in bold

> **NewPos** = **CamPos** \+ *t* * normalize(**PlayerPos** \- **CamPos**);

Lerp is also a build in function that's available to you.

Using this with LateUpdate will give lag similar effect.

**Elastic based camera:** With the spring formula

> **F** = k **x**

* **F** stands for Force
* **k** constant based on the spring stiffness (you can choose as you see fit)
* **x** can be used distance between the camera and the player.

Note that `F`can be factored into **F**=m\* **a** where `m` is mass(constant) and **a** is acceleration so you can modify the camera position using the calculated values.

In general this will give you a spring like behavior, but you need to multiply with some damping factor so it won't "bounce" forever.

# Answer
> 0 votes
One easy way is to just add a percentage of the desired position to the camera position each update.

```
void Update () {
  var newX =  player.transform.position.x;
  var newZ =  player.transform.position.z;
  var y = transform.position.y;

  var chaseSpeed = 0.05;

  transform.position = transform.position +
       (new Vector3(newX, y, newZ) - transform.position) * chaseSpeed;
}

```

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


title: How does HLSL handle clip(vector)?

text:
# Question
Title: How does HLSL handle clip(vector)?
My goal is to convert clip() to GLSL, version 1.5. I'm currently doing a basic:

```
if (x < 0) discard;

```

But if x is not a scalar, obviously I can't use the "\<" operator.

So I'm wanting to understand exactly how HLSL treats a vector (or a matrix) in the clip function so I can account for those as well. Any resources would be much appreciated, as I couldn't find any detailed info about the function. Thank you!

# Answer
> But if x is not a scalar, obviously I can't use the "\<" operator.

You can simply do this:

```
if (x < 0 || y < 0 ) discard;

```

According to clip(x) documentation (emphasis mine):

> Use the clip HLSL intrinsic function to simulate clipping planes if **each component of the x** parameter represents the distance from a plane.

According to the docs `x` could be a scalar a vector or a matrix.

Which means, if *any* of the components where less than zero it discards the pixel, this is true since if each of `x`,`y`,`z` represented a distance to a plane, this means than anyone of them being less than zero means the pixel should be clipped/discarded. Which makes the implementation boils down to the original form:

```
if (x < 0 || y < 0 || z < 0 ) discard;

```

but I will be surprised if the compiler was not able to detect this pattern and optimize by replacing it with it's appropriate assembly instruction.
> 3 votes

---
Tags: opengl, directx, glsl, hlsl
---