# Question
Title: Why do I get this crash when dealing with SDL_Events?
I do not know if this is the best way to handle these `SDL_Event`s, but I am attempting to create a very abstract and generic code that will update my game object. I have a `Scene` which in my case is just a map from a string to a game object that has special functions to `Add(string key, gameobject value)`, `Remove(string key)`, `Render()`, and `Update(SDL_Event& event)`. I think this last method is the problem.

## Scene.cpp

```
void Scene::Update(SDL_Event& ev)
{
    for (std::map<std::string, GameObject&>::iterator it = x_ObjectDictionary.begin(); it != x_ObjectDictionary.end(); ++it)
    {
        it->second.Update(ev); //where the game crashes
    }
}

void Scene::Render()
{
    for (std::map<std::string, GameObject&>::iterator it = x_ObjectDictionary.begin(); it != x_ObjectDictionary.end(); ++it)
    {
        it->second.Render();
    }
}

void Scene::Add(const std::string& key, GameObject& value)
{
    x_ObjectDictionary.insert(std::pair<std::string, GameObject&>(key, value));
}

GameObject& Scene::Get(const std::string& key)
{
    std::map<std::string, GameObject&>::const_iterator iterator = x_ObjectDictionary.find(key);
    if (iterator == x_ObjectDictionary.end()) return GameObject();
    return iterator->second;
}

GameObject& Scene::Remove(const std::string& key)
{
    GameObject removed;
    std::map<std::string, GameObject&>::const_iterator iterator = x_ObjectDictionary.find(key);
    if (iterator == x_ObjectDictionary.end()) return GameObject();
    removed = iterator->second;
    x_ObjectDictionary.erase(iterator);
    return removed;
}

```

This iterates my map and updates all of the `GameObject`s. My game object update method is defined like this in the header file:

## GameObject.h

```
class GameObject
{
public:
    GameObject() {}
    virtual ~GameObject() {}

    virtual void Update(SDL_Event& ev){}

    virtual void Render(){}

    virtual void Destroy(){}

};

```

Now, I created a scene. This `Scene` is called `Splash` and extends `Scene` properly. I created it like so

```
void Splash::CreateScene()
{
    Add("something", GameObject());
}

```

Every time I execute/debug my project now, my program "breaks" on the `it->second.Update(ev);` line and inside the console after I stop "debugging" the message says something along the lines of `Exception thrown at 0x00007FF7CB457024 in XXXXXX.exe: 0xC0000005: Access violation reading location 0x00001CFA67BC13F9.`

Am I going about this completely incorrectly? Or did I just make a stupid mistake?

# Answer
Looks like you have some problems with references.

Strictly saying, you cannot return local object as a reference, nor you can bind non-const reference to a temp object like this:

```
Add("something", GameObject());

```

I wonder how did you get it to compile... If you want to remove references be sure that they are not destroyed (e.g. by goingout of scope). E.g. next code will not behave correctly:

```
if(some_condition==true)
{
    GameObject go1;
    scene.Add("a", go1);
}
scene.Update(); // possible crash or garbage, because go1 does not exist there.

```

Also both Get and Remove functions have errors. You cannot return references to local objects.

```
GameObject& Scene::Remove(const std::string& key)
{
    GameObject removed;
    std::map<std::string, GameObject&>::const_iterator iterator =
        x_ObjectDictionary.find(key);
    if (iterator == x_ObjectDictionary.end()) return GameObject(); // cannot return local object!
    removed = iterator->second;
    x_ObjectDictionary.erase(iterator);
    return removed; // cannot return local object!
}

```

You can either work with pointers, but make sure that they were correctly allocated/destroyed. This way your Get and Remove method will be simpler. You can just return nullptr/NULL/0 instead of constructing and returning dummy object. If you do not want to use pointers than you can have dummy static object inside your scene class and return it. But you still need to make sure that your ordinary objects are not going out of scope.

As an example, Get/Remove could look like this:

```
      const GameObject& Get(const std::string& key)
      {
              std::map<std::string, GameObject&>::const_iterator iterator = x_ObjectDictionary.find(key);
              if (iterator == x_ObjectDictionary.end()) return s_GO;
              return iterator->second;
      }

      // note: returned object is not a reference!
      GameObject Remove(const std::string& key)
      {
              GameObject removed("");
              std::map<std::string, GameObject&>::iterator iterator = x_ObjectDictionary.find(key);
              if (iterator == x_ObjectDictionary.end()) return GameObject();
              removed = iterator->second;
              x_ObjectDictionary.erase(iterator);
              return removed;
      }

```

where s\_GO is a static member in Scene class.

Hope this helps.
> 1 votes

# Answer
It seems that you have used different types in it-\>second.Update(ev) (ev - SDL\_Event&). And in it second type is GameObject&.
> 0 votes

---
Tags: c++, sdl2
---


title: Unity PHOTON/PUN Collision Detection

text:
# Question
Title: Unity PHOTON/PUN Collision Detection
I am trying to create a virtual 3D chat room based on character interaction (just like in Sims2), so I have added a collider on the "user's in-game character". The problem is that when I enable the box collider, the character movement looks like it's freaking out (the character is seen as if it is moving fast from left to right & the movement is not smooth).

When I remove the box collider, the player moves smooth and no other fake-movement can be seen. What is the problem??

Thank you

# Answer
> 0 votes
If you have attatched a rigidbody to your character it's likely that the collider is colliding with something in an unusual way(maybe it's stuck inside the floor) and the rigidbody spazzes out. Check if there are any other colliders next to your character's collider. Other than that, it may be a script issue. Check your OnCollision functions.

# Answer
> 0 votes
Property replication (which is what Photon does) and physics don't go well together. For first-person shooters, this is okay because all physics needs to be used for is keeping the player from going through walls and some local raycast detection. Complex physics where objects simulated on multiple computers are hitting and bouncing off each other leads to freaky behaviors. Since game states are different, one player sends off a position that isn't consistent with the object on other players' machines.

One solution is to just ditch the physics engine because it tries too hard to keep objects from overlapping. Instead, implement your own system where objects are slowly seperated if they overlap. This will remove the jitter and make snapping positions more acceptable. Alternatively, you could just take out collision between networked objects completely.

By the way, have you tested your game offline? It's possible that your movement scripts are just broken and this is unrelated to networking.

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


# Question
Title: How do I check for collision between transparent textures?
I am creating a 2D game using OpenGL. For sprites, I use textured quads (actually two triangles). The texures contain transparent pixels, since objects are not always perfectly rectangular.

How do I do collision detection on the objects, not the quads? I was thinking to first check the quads for collision and if they match, check the textures.

But how can I check if two non-transparent pixels are on top of each other (or next to each other) for the two objects?

Or is there a completely different way of how this is done best?

# Answer
I'm lazy, so here is the way I'd tackle this issue: it would be by coupling the graphics with a collision/physics engine. You could try and find a basic collision engine for your language and implement something like this for your collisions and graphics:

The image is composed with square sprites images; here is the colour coding (note that the first row, and the arrows, are just to illustrate what the original sprites look like):

* Yellow: the edge of the sprite (square quad)
* Red: collision box or collision circle
* Blue: mix of Yellow and Red -\> the sprite and the object collision rectangle match

So for each sprite, you also need to create a set of collision circles and collision boxes that are moved (transformed) around the same way your sprites are.

The rest depends on your implementation and the implementation of the collision engine you'll use. This will not give you pixel perfect collision, but it's a basis for more complex physics simulation.

> All tiles except "Xerathul's Revenge" tiles have been drawn by David E. Gervais, and are published under the Creative Commons licence. You are free to to copy, distribute and transmit those tiles as long as you credit David Gervais as their creator. (Original site).
> 1 votes

---
Tags: opengl, collision-detection, textures, transparency
---


# Question
Title: How do I draw an object that I always want to appear in the same place on screen on a scrolling orthographic camera using lib gdx?
So I want to make an endless scroller game and the orthographinc camera is scrolling downward so i want the character to stay with the camera. I'm not sure how to aproach this i've been looking a lot online but couldn't find anything that works. The 2 ways I thought about doing it is to either make the object scroll at the same speed as the camera or in someway draw the object on the cameras "graph". This is the first game i'm making with libgdx so any help or suggestions are appreciated. :) Thanks

This is the gamescreen:

```
package com.ounceoftech.mygame;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;

public class GameScreen implements Screen
{
 OrthographicCamera camera;
 SpriteBatch batch;
 Vector3 touch;
 ship ship;
 Game game;

 public static int ship_x = 540 - 26;

 public GameScreen(Game game)
 {
    this.game = game;
    camera = new OrthographicCamera();
    camera.setToOrtho(false, 1080, 1920);
    batch = new SpriteBatch();
    touch =new Vector3();
    ship = new ship();
 }
 @Override
 public void render(float delta)
 {
    Gdx.gl.glClearColor(255F, 255F, 0F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.position.y -= 5;
    camera.update();
    generalUpdate(touch, camera);
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    //Rendering Code
    batch.draw(ship.image, ship_x, ship.bounds.y);
    batch.end();
 }
 public void generalUpdate(Vector3 touch, OrthographicCamera camera)
 {
    ship_x -= Gdx.input.getAccelerometerX() * 2;
    if(ship_x < 0) { ship_x = 0; }
    if(ship_x > 1027) { ship_x = 1027; }
 }
}

```

This is the object/player:

```
package com.ounceoftech.mygame;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector3;

public class ship
{
 public TextureRegion image;
 public Rectangle bounds;

 public ship()
 {
   image = Assets.spriteShip;
   bounds = new Rectangle(GameScreen.ship_x, 1600, 53, 256);
 }
}

```

# Answer
You can just create a new batch and draw the sprite on the position desired. Since this new batch has nothing to do with the camera, your sprite will be always at the same position.
> 1 votes

# Answer
If you draw your "player" using screen coordinates, you will not have to project them. Screen coordinates range from (-1, -1, -1) to (1, 1, 1). (0, 0, 0) is the center of the Viewport and the coordinate system created by batch.setProjectionMatrix(camera.combined).

Using screen coordinates, View, and Projection are Identity and, so, can be omitted. You can still transform your ship with a "World" matrix though, to move it around the screen. It sounds like you want its Y component to stay fixed, while allowing the user to change it's X. Although you are drawing to a 2D texture, there is still Z. If the interface is drawn at Z = 0 (front) and the scrolling map is drawn at Z = 1 (back), draw the ship at Z = 0.5 (behind interface but in front of map).

```
public static Matrix Identity;
public static int MaximumShipX = 1027;
public GameScreen(Game game)
{
...
Identity = Matrix4.idt();
}

@Override
public void render(float delta)
{
 batch.setProjectionMatrix(Identity);

 batch.begin();
 batch.draw(ship.image, ((float)ship_x / MaximumShipX) * 2.0f - 1.0f, 0.0f);
 //Y = 0.0f = vertical center of viewport
 //X component must be between -1 and 1
 //(float)ship_x / maximumShipX) ranges from 0 to 1
 //Multiplying by 2 and subtracting 1 moves the value into range
 //ship_x = 0, is now -1 instead (the left side of the viewport)
 //ship_x = maximumShipX, is now +1 instead (the right side of the viewport)
 //these are the same coordinates the camera matrix created previously
 batch.end();
}
public void generalUpdate(Vector3 touch, OrthographicCamera camera)
{
 ...
 if(ship_x > MaximumShipX) ship_x = MaximumShipX;
}

```
> 0 votes

---
Tags: libgdx
---


# Question
Title: Unity: cg fragment shader processing array of points
I need to write a fragment shader which would somehow be aware of N points that are in the scene and darken pixels based on their world coord distance to the points. I'm looking for a method that would be still suitable for mobile devices. I image I could pass the points as a texture but i'm stuck in figuring out how to effectively evaluate if a pixel is close enough to any of the N points (I know how to do this for 1 point, but for N without a loop?). Any ideas if this is doable in a performance efficient manner? All ideas are welcome. Thanks!

# Answer
> 3 votes
As discussed in the comments above, it may be easier to get this effect (and scale better to large values of N) by flipping the request around.

Rather than the shader for the scene geometry checking - in every rendered fragment - its distance to each of the N points, we can instead draw the scene geometry normally, then "stamp" the effects onto it by rendering some triangles for each of the N points.

This is effectively the same flip in thinking we do when moving from forward lighting to deferred. If each light/point's effect area is small (ie. less than the full screen) and there are many of them, we can reduce redundant work this way.

So, that leaves a few choices for how to render your points' effects:

**1. Shadow quads**

The images you've shown look a lot like blob shadows in older 3D games. If this is representative, that the blobs will always fall on some plane in a defined direction ("down"), we can do this very cheaply with no depth tricks:

In a CPU-side (C#/UnityScript) script, raycast down from each of your N points to find the nearest surface in that direction. Then position a quad at that position, scaled appropriately for how wide your effect is meant to be at that distance. Use a shader on the quad that will decal your desired effect onto the surface.

**2. Deferred decals/ screen-space decals**

This is the way to go if you want either an omni-directional effect, or one that shines "though" the first surface it encounters so it can affect multiple at once, or if the surfaces it's affecting are bumpy & irregular, hard to cover with a single quad. But it's much more complicated, so if you're not in one of these situations, you're probably better off using a quad.

The idea is to position a mesh representing the bounding volume of the point's effect. When your fragment shader goes to render the surface of the volume, it looks up into the depth buffer for the scene already rendered, to figure out what point in the scene has already been rendered to that pixel of the render target. It then shades the fragment as though it was located at that position. In your case, that means calculating the distance from this projected scene point to the source point for the volume.

The particulars will depend on the details of your use case (are your bounds cubes, spheres, cylinders? Can the camera get inside them? What type of shading effect needs to be applied within the bounds? Etc), but this type of technique is now pretty standard, so you should be able to find lots of references to get you started. Here's a sampling:

---
Tags: unity, shaders, fragment-shader, cg
---


title: Scaling surface changes colors

text:
# Question
Title: Scaling surface changes colors
I'm building a pixel art game with pygame, and I'd like to scale it to double the size. I have tried the `pygame.transform` methods like `scale` and `scale2x`, but they seem to alter the colors quite badly, there's an added red hue. Is there a way to scale pixel art correctly in pygame? Basically making each pixel 2x2 of the same color. Or do I have to do it manually, if yes, any suggestions?

This is the setup I have currently, "works" but messes up the colors:

```
#set scaling
scaling = 1

screen = pygame.Surface( (screen_w, screen_h) )
window = pygame.display.set_mode( (screen_w * scaling, screen_h * scaling) )

while not done:

    #do things...

    pygame.transform.scale(screen, (screen_w * scaling, screen_h * scaling), window)
    pygame.display.update()

```

E. for reference, here's what happens.

**No pygame scaling**

**vs. pygame scaling**

# Answer
Your `screen` and `window` surfaces don't have the same **pixel format**. One of them is most likely RGB, and the other is BGR. When you use the optimised `scale`/`scale2x` functions passing the `window` as the destination surface, no pixel format conversions are done, so all your reds become blue (or oranges become cyan), and vice versa.

If you do it the slow, normal way as Nick Jarvis suggested, you won't see this problem because `pygame.Surface.blit` does the conversion for you, hiding the problem.

What you should do is `convert()` or `convert_alpha()` your surfaces to match the output surface - `window` in your case. From the documentation:

> Creates a new copy of the Surface with the pixel format changed. The new pixel format can be determined from another existing Surface. Otherwise depth, flags, and masks arguments can be used, similar to the pygame.Surface() call.
>
> **If no arguments are passed the new Surface will have the same pixel format as the display Surface**. This is always the fastest format for blitting. **It is a good idea to convert all Surfaces before they are blitted many times**.
>
> The converted Surface will have no pixel alphas. They will be stripped if the original had them. See Surface.convert\_alpha() for preserving or creating per-pixel alphas.

That is, do this:

```
# no; pixel format will be different
screen = pygame.Surface( (screen_w, screen_h) )

# yes
screen = pygame.Surface( (screen_w, screen_h) ).convert()

```
> 2 votes

# Answer
Hmm... scale2x should be exactly what you want according to the documentation... Are you sure that the added red hue isn't due to there being more pixels of that colour and the shade you've chosen just stands out more? You might want to rule out your graphics card as being the problem by testing on another machine.

You could try resizing your scene with another library, or have a go at writing your own (probably way more of a pain in the ass than it's worth). You could apply a filter to reduce the redness, but that's more of a bandaid that a real fix. Actually, have you tried fiddling around with *set\_smoothscale\_backend* and seeing if that changes anything?

Last resort, if you're always going to want your scene drawn twice as big you can convert all your assets with a little script to make them that way. Just sample each pixel and draw it to a texture that's twice as large with each pixel being drawn at twice their original position (\[1,1\] -\> \[2,2\], \[3,9\] -\> \[6, 18\]) and then fill in the three pixels nearby the same colour (red: \[6, 18\], \[6, 19\], \[7, 18\], \[7, 19\]). Save those textures to file and use those as your assets (would be way too slow to do every frame). All of your current in game co-ordinates would have to be doubled as well, unfortunately.
> 0 votes

# Answer
I've used pygame extensively, and I have had problems with scale before. Have you tried not using destination surface and instead setting the returned function to another variable like:

```
scaled_screen = pygame.transform.scale(screen, (screen_w * scaling, screen_h * scaling))

```

Then blitting that to the window at (0, 0)?

It also might be easier to scale each tile (as it looks like you are using isometric tiles) and then scaling the position of each tile. The coloring may come from scaling the whole image rather than the subsequent elements.

And just to make sure: is there anywhere in your program that may be inverting the colors of the image?
> 0 votes

---
Tags: pygame, scale
---


title: OpenGL texture seams

text:
# Question
Title: OpenGL texture seams
I'm atempting to make a game using OpenGL. So far I have loaded an .obj model, and I have generated a terrain as well as a very simple UI.

My issue is that it 'seams' (tihi : P) that there are some visible seams on the the texturing. As seen on the image, each quad in the terrain has black line around it. The model also appears to have such quads on the seams that were marked when the uv's were made in the 3D software, yet this is not as clearly visible.

I'm not sure how or where the issue occurs.

When i Generate the terrain, I add 6 vertecies per quad, without using index buffers, so they are just added to a buffer on the fly. (I'm aware that this is not the best solution, but I chose it just to get started).

Below is the code that makes a 'region' of the terrain:

I'm sorry that it's rather long : /

TerrainRegion::TerrainRegion(glm::vec2 start, glm::vec2 dims, int samples){

```
// Prepare the mesh data
std::vector<glm::vec3> mesh_vertecies;
std::vector<glm::vec3> mesh_normals;
std::vector<glm::vec2> mesh_uvs;

// check if a quad, and uniformize samples
int x_samples, y_samples;
if (dims.x != dims.y){
    if (dims.x > dims.y){
        x_samples = samples;
        y_samples = floor((dims.y / dims.x) * float(samples));
    }
    else{
        y_samples = samples;
        x_samples = floor((dims.x / dims.y) * float(samples));
    }
}
else{
    x_samples = y_samples = samples;
}

// Make space for the height values
double **height_map = new double*[x_samples+2];
for (int i = 0; i < x_samples + 2; ++i) {
    height_map[i] = new double[y_samples + 2];
}
std::cout << x_samples << ", " << y_samples << std::endl;

// fillin the height map
for (int y = 0; y < y_samples + 2; y++){
    for (int x = 0; x < x_samples + 2; x++){
        double x_space = (float(x - 1) / float(x_samples-1))*dims.x + start.x;
        double y_space = (float(y - 1) / float(y_samples-1))*dims.y + start.y;
        //std::cout << std::setw(6) << std::setprecision(1) << std::fixed << x_space << ", " << y_space << " ";
        height_map[x][y] = OctavePerlin(x_space / 100.0f, y_space / 100.0f, 1.0, 6, 0.28) * 30.0f;
    }
    //std::cout << std::endl;
}
//std::cout << std::endl;

// print the height map
/*
for (int y = 0; y < y_samples + 2; y++){
    for (int x = 0; x < x_samples + 2; x++){
        std::cout << std::setw(6) << std::setprecision(2) << std::fixed << height_map[x][y] << " ";
    }
    std::cout << std::endl;
}
*/

// make mesh data from height map
for (int y = 1; y < y_samples; y++){
    for (int x = 1; x < x_samples; x++){
        double x_space = (float(x) / float(x_samples - 1))*dims.x;
        double y_space = (float(y) / float(y_samples - 1))*dims.y;
        double x_dspace = (float(x+1) / float(x_samples - 1))*dims.x;
        double y_dspace = (float(y+1) / float(y_samples - 1))*dims.y;
        double x_dmspace = (float(x-1) / float(x_samples - 1))*dims.x;
        double y_dmspace = (float(y-1) / float(y_samples - 1))*dims.y;

        glm::vec3 v0 = glm::vec3(x_space, height_map[x][y], y_space);
        glm::vec3 v1 = glm::vec3(x_space, height_map[x][y + 1], y_dspace);
        glm::vec3 v2 = glm::vec3(x_dspace, height_map[x + 1][y + 1], y_dspace);
        glm::vec3 v3 = glm::vec3(x_dspace, height_map[x + 1][y], y_space);
        glm::vec3 v4 = glm::vec3(x_dspace, height_map[x + 1][y-1], y_dmspace);
        glm::vec3 v5 = glm::vec3(x_space, height_map[x][y - 1], y_dmspace);
        glm::vec3 v6 = glm::vec3(x_dmspace, height_map[x-1][y], y_space);
        glm::vec3 v7 = glm::vec3(x_dmspace, height_map[x - 1][y + 1], y_dspace);
        glm::vec3 v8 = glm::vec3(x_space, height_map[x][y + 2], (float(y +2) / float(y_samples - 1))*dims.y);
        glm::vec3 v9 = glm::vec3(x_dspace, height_map[x+1][y + 2], (float(y + 2) / float(y_samples - 1))*dims.y);
        glm::vec3 v10 = glm::vec3((float(x + 2) / float(x_samples - 1))*dims.x, height_map[x + 2][y + 1], y_dspace);
        glm::vec3 v11 = glm::vec3((float(x + 2) / float(x_samples - 1))*dims.x, height_map[x + 2][y], y_space);

        mesh_vertecies.push_back(v0);
        mesh_vertecies.push_back(v1);
        mesh_vertecies.push_back(v2);
        mesh_vertecies.push_back(v0);
        mesh_vertecies.push_back(v2);
        mesh_vertecies.push_back(v3);

        // 0
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v1 - v0, v3 - v0))+
            glm::normalize(glm::cross(v3 - v0, v5 - v0)) +
            glm::normalize(glm::cross(v5 - v0, v6 - v0)) +
            glm::normalize(glm::cross(v6 - v0, v1 - v0))
            )));

        // 1
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v8 - v1, v2 - v1)) +
            glm::normalize(glm::cross(v2 - v1, v0 - v1)) +
            glm::normalize(glm::cross(v0 - v1, v7 - v1)) +
            glm::normalize(glm::cross(v7 - v1, v8 - v1))
            )));

        // 2
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v9 - v2, v10 - v2)) +
            glm::normalize(glm::cross(v10 - v2, v3 - v2)) +
            glm::normalize(glm::cross(v3 - v2, v1 - v2)) +
            glm::normalize(glm::cross(v1 - v2, v9 - v2))
            )));

        // 0
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v1 - v0, v3 - v0)) +
            glm::normalize(glm::cross(v3 - v0, v5 - v0)) +
            glm::normalize(glm::cross(v5 - v0, v6 - v0)) +
            glm::normalize(glm::cross(v6 - v0, v1 - v0))
            )));

        // 2
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v9 - v2, v10 - v2)) +
            glm::normalize(glm::cross(v10 - v2, v3 - v2)) +
            glm::normalize(glm::cross(v3 - v2, v1 - v2)) +
            glm::normalize(glm::cross(v1 - v2, v9 - v2))
            )));

        // 3
        mesh_normals.push_back(glm::normalize((
            glm::normalize(glm::cross(v2 - v3, v11 - v3)) +
            glm::normalize(glm::cross(v11 - v3, v4 - v3)) +
            glm::normalize(glm::cross(v4 - v3, v0 - v3)) +
            glm::normalize(glm::cross(v0 - v3, v2 - v3))
            )));

        double nul = 0.0;
        double et = 1.0;
        mesh_uvs.push_back(glm::vec2(nul, nul));
        mesh_uvs.push_back(glm::vec2(nul,et));
        mesh_uvs.push_back(glm::vec2(et,et));

        mesh_uvs.push_back(glm::vec2(nul,nul));
        mesh_uvs.push_back(glm::vec2(et, et));
        mesh_uvs.push_back(glm::vec2(et, nul));

    }
    //std::cout << std::endl;
}

this->mesh = new gf::Mesh();
this->mesh->set_vertex_data(mesh_vertecies);
this->mesh->set_normal_data(mesh_normals);
this->mesh->set_UV_data(mesh_uvs);
this->mesh->compute_tangents();
this->mesh->generate_buffers();

for (int i = 0; i < x_samples + 2; ++i) {
    delete height_map[i];
}
delete height_map;

```

}

And here is the vertex shader:

```
#version 410

struct LightInfo {
  vec4 Position; // Position of light
  vec3 Intensity; // Intensity of the light
  vec3 Ambient;  // Ambient component of the light
  vec3 Diffuse;  // Diffuse component of the light
  vec3 Specular; // Specular component of the light
};

struct MaterialInfo {
  vec3 Ambient;  // Ambinet component of material
  vec3 Diffuse;  // Diffuse component of material
  vec3 Specular; // Specular component of material
  float Shininess; // shininess of material
};

layout(location = 0) in vec3 VertexPosition;
layout(location = 1) in vec3 VertexNormal;
layout(location = 2) in vec2 VertexUV;
layout(location = 3) in vec3 VertexTangent;
layout(location = 4) in vec3 VertexBiTangent;

// Transform matricies
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
uniform mat4 ProjectionMatrix;
uniform mat4 MVP;
uniform mat3 NormalMatrix;

// Light uniforms
uniform LightInfo light[12];
uniform int n_lights;

// Meterial uniforms
uniform MaterialInfo material;

// texture
uniform sampler2D diffuse_texture;

out vec4 Position;
out vec3 Normal;
out vec2 UV;
out mat3 TBN;

void main(){

  Position = ViewMatrix * ModelMatrix * vec4(VertexPosition, 1.0);
  Normal =  normalize(NormalMatrix * VertexNormal);
  UV = VertexUV;

  vec3 Tangent =  normalize(NormalMatrix * VertexTangent);
  vec3 BiTangent = normalize(NormalMatrix * VertexBiTangent);
  TBN = transpose(mat3(
        Tangent,
        BiTangent,
        Normal
    ));

  gl_Position = MVP * vec4(VertexPosition, 1.0);
}

```

And the fragment shader:

```
#version 410

struct LightInfo {
  vec4 Position; // Position of light
  vec3 Intensity; // Intensity of the light
  vec3 Ambient;  // Ambient component of the light
  vec3 Diffuse;  // Diffuse component of the light
  vec3 Specular; // Specular component of the light
};

struct MaterialInfo {
  vec3 Ambient;  // Ambinet component of material
  vec3 Diffuse;  // Diffuse component of material
  vec3 Specular; // Specular component of material
  float Shininess; // shininess of material
};

uniform LightInfo light[12];
uniform int n_lights;

// Meterial uniforms
uniform MaterialInfo material;

// texture
uniform sampler2D diffuse_texture;
uniform sampler2D normal_map;
uniform sampler2D specular_occlusion_map;

in vec4 Position;
in vec3 Normal;
in vec2 UV;
in mat3 TBN;

layout(location = 0) out vec4 FragColor;

vec4 tex_col(){
    return texture(diffuse_texture, UV);
}

vec3 ads(LightInfo l){
  vec3 texcol = tex_col().xyz;
    vec3 n = normalize( texture( normal_map, UV ).rgb*2.0 - 1.0);
    vec3 s = normalize( TBN * vec3(l.Position - Position) );
    vec3 v = normalize( TBN * vec3(-Position) );
    vec3 r = reflect( -s, n );
    return l.Intensity * ( (material.Ambient * l.Ambient +
                          material.Diffuse * l.Diffuse * max( dot(s,n), 0.0 )) * tex_col().xyz +
               texture(specular_occlusion_map, UV).xyz * material.Specular * l.Specular * pow(max(dot(r,v), 0.0), material.Shininess));
}

void main() {

  //vec3 color = material.Ambient;
  vec3 color = vec3(0.0,0.0,0.0);

  for(int i = 0; i < n_lights; i++){
      color = color + ads(light[i]);
  }
  //color = Normal;

  FragColor = vec4(color, 1.0);
  //FragColor = vec4(Normal, 1.0);
  //FragColor = vec4(light[0].Diffuse, 1.0);
  //FragColor = vec4(Position.xyz, 1.0);
}

```

Is there something clearly wrng with this? Or shoudl I present more info on the errors?

Btw

The grass texture does NOT have a black border : )

**Edit:**

The code that lods textures:

```
gf::Texture *gf::Texture::load_texture_from_file(std::string filename){

  gf::Texture *texture = new gf::Texture();

  GLuint tex_ID;

  tex_ID = SOIL_load_OGL_texture(
    filename.c_str(),
    SOIL_LOAD_AUTO,
    SOIL_CREATE_NEW_ID,
    SOIL_FLAG_POWER_OF_TWO
    | SOIL_FLAG_MIPMAPS
    | SOIL_FLAG_MULTIPLY_ALPHA
    | SOIL_FLAG_COMPRESS_TO_DXT
    | SOIL_FLAG_DDS_LOAD_DIRECT
    | SOIL_FLAG_INVERT_Y
    );

  if (tex_ID > 0)
  {
    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, tex_ID);

    texture->texture_id = tex_ID;
  }
  else{
    delete texture;
    return (gf::Texture*) 0;
  }

  return texture;

}

```

I just use SOIL, and an example that I found online. The Texture class does only hold the texture id.

# Answer
> 0 votes
I found a solution.

I cannot really explain why it changes the outcome since all UV's are in the \[0;1\] range. Yet, addin the lines

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

Just after loading the texture solved the problem just fine.

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


# Question
Title: LibGDX: Colllisions between bullets and enemies in arrays
I am writing a "Gauntlet" style game. So far I have managed to successfully detect collisions between my player object and my ghost enemy objects, and when they collide they drain the player's energy.

The Ghosts are stored in an ArrayList. I now have bullets which the player can fire, these are instantiated from the Player class and added to another ArrayList called bullets.

I typically have around 50 ghosts on the screen dotted around the map.

```
ArrayList<Ghost> ghosts = new ArrayList<Ghost>();
ArrayList<Bullet> bullets = new ArrayList<Bullet>();

```

The ghosts and bullets are added to these lists when spawned/fired

I have tried to implement a method as per below, to try and determine whether a ghost's bounding rect and a bullet's bounding rect overlap, as follows:

```
/**
 * Check if a ghost has been hit by a bullet
 */
public void checkGhostsHit() {

    Iterator<Ghost> iterEn = ghosts.iterator();

    while ( iterEn.hasNext() ){
        Ghost g = iterEn.next();

        //initialise the bullet iterator each time here
        Iterator<Bullet> iterBul = Player.bullets.iterator();

        while ( iterBul.hasNext() ) {
            Bullet b = iterBul.next();

            if ( b.getBoundingRect().overlaps( g.getBoundingRect() ) ) {
                Gdx.app.log("Enemy", " Hit");
                iterBul.remove();
                iterEn.remove();
            }
        }
    }
}

```

This method is being called from my main render loop but I cannot get it working for love or money. I have tried various forms of the above method, including 'For' loops etc.

Am I performing the check in the correct place? Should the Bullet class instance iteself be checking for a collision, or is the above approach the correct idea.

As you can tell I'm a noob to this and I am still struggling with working out which activities should be undertaken by particular game Classes.

# Answer
> 2 votes
I guess the problem here is the so-called *Tunneling*.

Tunneling happens when an object moves to far in one update loop and therefore the collision is never detected, as it "jumps over" the other object.

There are several ways to solve this:

* **Continuous Collision Detection:** Instead of checking for an overlap at the current posiition, you could use the way from the last to the current position as the bounding box. Doing this, you would detect the collision, even if you would not collide at the new position.
* **Fixed update time:** Instead of using `delta` as update time you could use a fixed time (lets say 1/60second) and use an `accumulator`-approch (look at the code here). This makes sure, that the updates have a fixed time, so the way an object can travel in one update-loop is limited. Also the calculation of the logic usually takes less time then the rendering, so you can perform it multiple times/render loop without problems.

---
Tags: collision-detection, libgdx
---


# Question
Title: Physics: calculating angular acceleration in world vs local space
I have a pretty simple rigid body simulation written in Python. In my code I calculate the angular acceleration using formula:

angAcc = torque * inertiaTensor^-1 (note row-major matrix order)

Now, the torque is in world-space so my inertiaTensor should also be in world-space. My Python code that does the angular acceleration computation looks like this:

```
oriMat = quaternion.ToMatrix(self.ori)
inertia_world = self.inertia_local * oriMat
matrix.Invert(inertia_world)
angAcc = vector.Transform(self.totalTorque, inertia_world)

```

oriMat is effectively local-to-world transform. self.totalTorque is torque in world space. So this code transforms local inertia to world inertia and uses its inverse along with world torque to compute world angular acceleration. This code works completely fine.

I thought to check out if I could conduct the angular acceleration compuation in local space and eventually convert local angAcc to world angAcc. Here's the code:

```
oriMat = quaternion.ToMatrix(self.ori)
self.totalTorque = vector.Transform(self.totalTorque, matrix.Inverted(oriMat))
angAcc = vector.Transform(self.totalTorque, matrix.Inverted(self.inertia_local))
angAcc = vector.Transform(angAcc, oriMat)

```

Here I wanted to do the torque-inertia transform in local space. To do so, I transform self.totalTorque to rigid body's local space using inverse of oriMat. Then I mul that by inverted local inertia to get angular acceleration in local space. Finally, I transform angular acceleration to world space by transforming it with oriMat.

For some reason this code doesn't yield correct behaviour of my rigid body and I really can't tell why. Anyone got an idea?

# Answer
You say :

*Then I mul that by inverted local inertia to get angular acceleration in local space.*

This seems wrong, since "inverted local inertia" is "world inertia", so you are putting "that" to world space while you want it in local space ...

So code should be :

```
// oriMat: local -> world
oriMat = quaternion.ToMatrix(self.ori)

// put total torque in local space
self.totalTorque = vector.Transform(self.totalTorque, matrix.Inverted(oriMat))

// multiply local torque with local inertia to get angAcc in local space
angAcc = vector.Transform(self.totalTorque, self.inertia_local))

// put angAcc in world space
angAcc = vector.Transform(angAcc, oriMat)

```
> 1 votes

---
Tags: physics, rigid-body-dynamics
---


# Question
Title: Could frame interpolation like used by SmoothVideo Project be an option to increase the framerate of games without as big a performance hit?
The SmoothVideo Project uses frame interpolation to increase the fps of video from 24 to 60. The results are pretty impressive. I was wondering if this could be applied to, and whether it would look good in video games?

It uses much less resources than rendering all the frames so would allow lower end rigs to render at the quality of much better rigs at some level of compromise. I know it won't be as accurate, and would slightly increase input latency as it needs to hold on to the newest frame to be able to generate and insert the interpolated one. It's not as bad as a full frame though, by my reasoning only the lag would be the interpolation time plus half the original fps refresh time. So for 30 fps it would be 33ms/2 + interpolation time.

Maybe this lag would make it unsuitable for fast past first person games, but I doubt it would be a hindrance in slower paced games.

The lag becomes lower at higher start rates, so I would think it would be certainly worth it when going from 60fps to 100+fps which improves the experience though increasingly marginally, while being extreme taxing on the system.

# Answer
A system along these lines has been used in The Force Unleashed. I'm not aware of other titles that have used it though.
> 6 votes

# Answer
Yes it's possible, but it's not without its complications.

While frame interpolation can work real-time on videos, that isn't necessarily the case with video games. Even though this is processing real-time on videos, the software is able to "look ahead" to the next frame. This is a pretty critical component of interpolation. This is where the issue comes into play with games. Most of the time, next next frame has not been rendered yet! So the software doesn't know the next point in the interpolation.

There's certainly the possibility of running the game a frame or two behind in order to give your interpolation software the frames it needs to work with. However, this doesn't work as well for media that is interactive. Now what's being shown on screen is delayed from the input being received. This does make things more tricky for processing input and providing a good responsiveness to the game. It's like building in an artificial performance lag. Additionally, it's unlikely to have native support in any of the major game engines, which means writing your own.
> 9 votes

# Answer
Yes, this is not only possible, but available now: hook up your game PC/console to a TV that uses motion interpolation. Opinions vary, and this is less suitable for twitch games like FPS due to the interpolation lag, but for upscaling frame rates from 60 to 120Hz it works fine.

As for whether this can be done in the game itself, there's not enough impetus yet, in that most monitors can't output those high frame rates. 120+Hz monitors for computers are less common, although judging from how TVs are going, this may happen soon. Having a high refresh rate monitor has advantages even if the game can't reach those frame rates: besides the aforementioned TV-based motion interpolation, it can offer smoother frames if the game is allowed to output frames as they are ready, instead of synced up ala v-sync. Once 120+Hz monitors are commonplace, I expect game developers to catch up and start using more tricks, including motion interpolation, to reach those high frame rates.
> 2 votes

# Answer
The lag between when the user does something and when the result appears on the screen should never exceed 100ms or the user might notice the delay.

The monitor of the user might take about 30 ms to display the picture it receives. Much faster monitors are available, but many average users don't have these. If the video card calculates 30 frames per second, it takes 33 ms to calculate a frame. I assume 30 fps because we need no frame interpolation if the game already runs at 60 fps. If we use triple buffering this gets doubled to 66 ms. That's 90 ms.

I think we need triple buffering for frame interpolation to make sense. So if we use frame interpolation on top of that to get 60 fps, we increase the delay by one 60Hz frame, which is another 17 ms + interpolation time X, bringing us to 107 ms + X. The problem isn't the interpolation as such, but the fact that we are already close to the point where latency is noticeable before we introduce the interpolation.

It would probably be fine for a game that's mostly a virtual movie, but in a FPS the users would notice that something is off with the aiming.
> 0 votes

---
Tags: rendering, frame-rate, interpolation
---


# Question
Title: Using full resolution of depth buffer for 2D rendering
I'm working on a front-to-back renderer for a 2D engine using an orthographic projection. I want to use the depth buffer to avoid overdraw. I have a 16-bit depth buffer, a camera at Z=100 looking at Z=0, zNear is 1, and zFar is 1000. Each sprite rendered sets its Z co-ordinates to increasingly distant values, allowing depth test to skip rendering anything which is underneath.

However I'm aware the way Z positions end up with Z buffer values is non-linear. I want to make use of the full resolution of the 16-bit depth buffer, i.e. allowing 65536 unique values. So for every sprite rendered, I want to increment the Z position to the next position to correlate to the next unique depth buffer value.

In other words I want to turn an incrementing index (0, 1, 2, 3...) of the sprite being drawn in to the appropriate Z position for each sprite to have a unique depth buffer value. I'm not sure of the maths behind this. What is the calculation to do this?

Note I'm working in WebGL (basically OpenGL ES 2), and I need to support a wide range of hardware, so while extensions like gl\_FragDepth might make this easier, I can't use it for compatibility reasons.

# Answer
Indeed, the values stored in the z-buffer are not linear to the actual z coordinates of your objects, but to their reciprocal, in order to give more resolution to what's near the eye than to what's closer to the back plane.

What you do is that you map your `zNear` to `0` and your `zFar` to `1`. For `zNear=1` and `zFar=2`, it should look like this

The way to calculate this is defined by:

```
z_buffer_value = k * (a + (b / z))

```

Where

```
 k = (1 << N), maximum value the Z buffer can store
 N = number of bits of Z precision
 a = zFar / ( zFar - zNear )
 b = zFar * zNear / ( zNear - zFar )
 z = distance from the eye to the object

```

...and z\_buffer\_value is an integer.

Above equation is brought to you courtesy of this awesome page, which explains z-buffers in a really good way.

So, in order to find the necessary `z` for a given `z_buffer_value`, we just clear the `z`:

```
z = (k * b) / (z_buffer_value - (k * a))

```
> 6 votes

# Answer
Maybe you should change You'r approach to something simpler. What I would do; Keep your Z depth thing, but keep a list of what you render. Order that list based on the z Depth value, and render objects in the order of the list.

Hope this can help. People always tell me to keep things simple.
> -1 votes

# Answer
Since you already have a sorted list of things to render (front to back) do you really need to increment the Z index? Can't you use "less or equal" for the "checking function"? This way it would actually check if a specific pixel was already drawn or not.
> -1 votes

---
Tags: opengl, 2d, rendering, depth-buffer
---


# Question
Title: Applying velocity to objects in a specified direction
How to apply velocity to a particular direction?

Data which I have:

1. object position (P1)
2. destination (P2)

# Answer
> 1 votes
Velocity is speed and direction, and the only tricky part is the direction. Your question cuts right to that problem. This kind of vector math is linear algebra 101. However, since Wikipedia offers its usual incomprehensible notation for otherwise simple mathematics, here's a quick summary.

The vector from `P1` to `P2` can be found by subtracting:

```
v = [(P2.x - P1.x), (P2.y - P1.y), (P2.z - P1.z)];

```

For directions, it is very likely you want a unit vector (length = 1), so that you can apply more trigonometry to it (not so in this case, but it will be useful regardless).

Getting a vector's unit is easy; divide its components by its length:

```
vLength = sqrt(v.x * v.x + v.y * v.y + v.z * v.z);  // a scalar value
vUnit = [(v.x / vLength), (v.y / vLength), v.z / vLength)];

```

Now that you have a vector of length one, you can give your object a speed value, and move it in any direction at constant (or not constant) speed:

```
objVelocity = [(vUnit.x * speed), (vUnit.y * speed), (vUnit.z * speed)];

```

---

Hopefully this is easy to translate to C++ using whatever library you choose.

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


# Question
Title: Can't clip a sprite that has a custom shader in NGUI
I am using NGUI. I have an "NGUI Unity 2D Sprite". This sprite has a material with this shader:

```
Shader "DM/Ripple Shader" {
    Properties {
        _Color ("Color", Color) = (1,1,1,1)
        _MainTex ("Texture", 2D) = "white" {}
        _Scale ("Scale", Range(0.5,500.0)) = 3.0
        _Speed ("Speed", Range(-50,50.0)) = 1.0
    }
    SubShader {
        Tags { "RenderType"="Opaque"}
        LOD 200
        Cull Off
        CGPROGRAM
        #pragma surface surf Lambert
        #include "UnityCG.cginc"

        half4 _Color;
        half _Scale;
        half _Speed;
        sampler2D _MainTex;

        struct Input {
            float2 uv_MainTex;
        };

        void surf (Input IN, inout SurfaceOutput o) {
            half2 uv = (IN.uv_MainTex - 0.5) * _Scale;
            half r = sqrt (uv.x*uv.x + uv.y*uv.y);
            half z = sin (r+_Time[1]*_Speed) / r;
            o.Albedo = _Color.rgb * tex2D (_MainTex, IN.uv_MainTex+z).rgb;
            o.Alpha = _Color.a;
            o.Normal = (z, z, z);
        }
        ENDCG
    }
    FallBack "Diffuse"
}

```

It is basically a ripple effect.

Anyway, this sprite is a child of another Game Object, which an NGUI `UI Panel` one.

I want the Panel to use Soft Clipping. I want to clip the sprite.

However, when you activate Soft Clipping (or any sort of clipping really), the sprite's shader will not work anymore. The sprite will be drawn normally, but it won't have the desired ripple effect.

How can I clip my sprite without affecting its custom shader?

---

I am aware that NGUI has a shader that does the clipping, and I am supposed to "grab its logic and combine it with my shader". However, I do not understand how am I supposed to that. This is the NGUI shader that supposedly does the clipping:

```
Shader "Hidden/Unlit/Transparent Colored 1"
{
    Properties
    {
        _MainTex ("Base (RGB), Alpha (A)", 2D) = "black" {}
    }

    SubShader
    {
        LOD 200

        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
        }

        Pass
        {
            Cull Off
            Lighting Off
            ZWrite Off
            Offset -1, -1
            Fog { Mode Off }
            ColorMask RGB
            Blend SrcAlpha OneMinusSrcAlpha

            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            sampler2D _MainTex;
            float4 _ClipRange0 = float4(0.0, 0.0, 1.0, 1.0);
            float2 _ClipArgs0 = float2(1000.0, 1000.0);

            struct appdata_t
            {
                float4 vertex : POSITION;
                half4 color : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : POSITION;
                half4 color : COLOR;
                float2 texcoord : TEXCOORD0;
                float2 worldPos : TEXCOORD1;
            };

            v2f o;

            v2f vert (appdata_t v)
            {
                o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
                o.color = v.color;
                o.texcoord = v.texcoord;
                o.worldPos = v.vertex.xy * _ClipRange0.zw + _ClipRange0.xy;
                return o;
            }

            half4 frag (v2f IN) : COLOR
            {
                // Softness factor
                float2 factor = (float2(1.0, 1.0) - abs(IN.worldPos)) * _ClipArgs0;

                // Sample the texture
                half4 col = tex2D(_MainTex, IN.texcoord) * IN.color;
                col.a *= clamp( min(factor.x, factor.y), 0.0, 1.0);
                return col;
            }
            ENDCG
        }
    }

    SubShader
    {
        LOD 100

        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
        }

        Pass
        {
            Cull Off
            Lighting Off
            ZWrite Off
            Fog { Mode Off }
            ColorMask RGB
            Blend SrcAlpha OneMinusSrcAlpha
            ColorMaterial AmbientAndDiffuse

            SetTexture [_MainTex]
            {
                Combine Texture * Primary
            }
        }
    }
}

```

How am I supposed to use both?

# Answer
> 0 votes
I did a quick google search and found this question on the NGUI forum: http://www.tasharen.com/forum/index.php?topic=9004.0

In the first reply, Nikki says that NGUI does clipping in the shaders. This means that you'll have to modify your ripple shader to take clipping into account.

I did a quick browse through the shaders packaged with NGUI and found they all contain logic for clipping. Take a look at them, the clipping areas are well commented so you should be able to include them in your shader.

---
Tags: unity, ngui
---


title: unity 5.1 how to control the animation?

text:
# Question
Title: unity 5.1 how to control the animation?
i clicked a cube and added a simple transform animation by using animation timeline, and the cube has a "animator" component was added into the inspector. My questions are

1. how can i set the animation do not play automatically? I can't find any related option in animator in inspector
2. how can i set the script to control the animation? for example, play the animation after the scene started 5 seconds?

# Answer
> 5 votes
The animator view in Unity is a little confusing, so I've added screenshots for each step.

**Step 1: Set Up States**

The animator system has two default states, Entry and Any State. Entry is the point that the animator starts at when the scene starts. Right click on the background and create new Empty State. I called mine "NoAnimation," but you can call it whatever makes sense to you.

Right click on this and say "Set As Layer Default State". You'll see that the arrow from the entry state goes to this new Empty state now.

Your state that has the animation now needs a way to be entered. Right click on the Empty state and select "Make Transition." Drag the arrow to your existing state. Your screen should look like this:

By default, the transition you just created will execute at the end of the animation in the no animation state. Since this takes no time, it will just automatically move. To remedy this, you need to create a trigger.

**Step 2: Create A Trigger**

In the parameters panel, click the add button and select Trigger.

I named my trigger "AndGo" but you should choose a name that makes sense to you.

**Step 3: Hook Trigger to Transition**

Now, to make the transition happen when the trigger is triggered, select the NoAnimation state and then click the transition to your animation state in the inspector view. This will open up more options about that transition.

Uncheck "Has Exit Time" and then click the plus sign under the Conditions Box. The name of your trigger should show up as a Condition.

**Step 4: Add a behavior to set the trigger**

Finally, you need to create a Behaviour to attach to the object that will wait 5 seconds and then trigger the transition. I achieved this with a coroutine.

```
using UnityEngine;
using System.Collections;

public class DelayStart : MonoBehaviour
{
    public void Start()
    {
        StartCoroutine(delayThenStart());
    }

    private IEnumerator delayThenStart()
    {
        yield return new WaitForSeconds(5f);

        // get a reference to the animator on this gameObject
        var animator = gameObject.GetComponent<Animator>();

        animator.SetTrigger("AndGo");
    }
}

```

---
Tags: unity
---


title: Dynamically save prefabs

text:
# Question
Title: Dynamically save prefabs
We have made different types of prefabs, if we want to change small thing in all prefabs, we do drag all those prefabs to scene ,create script which will do its required work .All is fine till now after that problem arises for saving those prefabs.We need to manually click "Apply" on all prefabs.

Has there anyway where we can dynamically use "Apply" feature via script?

# Answer
> 1 votes
I found a workaround,use following code to do it so,

PrefabUtility.ReplacePrefab(gameObject, PrefabUtility.GetPrefabParent(gameObject), ReplacePrefabOptions.ConnectToPrefab);

---
Tags: unity
---


# Question
Title: It is feasible to complete decouple a graphics engine from game logic?
Is it possible, or even feasible, to have graphics engine completely decoupled from game logic?

Why I ask is because I want to start working on a game (I'm a complete beginner in game development, but I have 8+ years of programming under my belt), but there are more than a couple graphics engines out there to pick from. Also I do not anticipate my development speed will be very fast, so I would like to be able to swap out an old graphics engine for a new one if the old one becomes too out of date.

I want to work with OpenGL for possible cross platform compatibility, so that should at least reduce issues that may arise from supporting multiple graphics APIs.

# Answer
The answer to the question "Is it possible, or even feasible, to have graphics engine completely decoupled from game logic?" is "yes".

I would say it is even "advisable".

But in general, you'll find a lot of your game ends up tied to the engine you choose for other reasons, like input handling or use of their facebook integration or other cross-platform services.
> 4 votes

---
Tags: architecture
---


# Question
Title: handling wars in multiplayer browser game
I'm building a browser game about countries, cities, the user control his city, building it upgrading it, can fight other cities in the same country, elections and war between countries, peace, trade agreements, and many many more cool stuff. The game is in full size window, all of the website will be dynamic and will be playable in 1 page, and won't redirect to any other page.

i'm using php, javascript (jquery), css, html at work, so I'm very friendly with those languages.

I have few questions about developing this kind of a game:

1. I have chose node.js for the back-end programing, because as of my understanding it's fast, and will do the best job for my game, i chose node because its made for handling many call at the same time, but the only place I really need it is in wars between countries and cities, where a lot of people can participate in one battle. Should i use php in rest of my website, for login, register, elections and use ajax, or stick with node.js for all of the back-end stuff, and why? or even use other language that can suit me better?
2. The big question is my front-end, the majority of my website can be done with simple js and other small libraries, for drag and drop, cool effects and such, but my problems is as the above, the wars. The wars will be fought with max of 20 users in one window (battle), the idea of the battle is like the game LoL (league of legends), where the user is the hero, 10 heroes fight againsts 10 heroes, so it must be in real time, 3d and third person camera, all of the movement and attacks will be with the use of the mouse. I have no idea in programing 3d objects, i was looking into few js libraries and HTML5, like babylonjs, Three.js, playcanvas, the best i saw and i think that might suit me is playcanvas, but i'm afraid putting it all in one language just to find out that it can't be done with it. Does playcanvas suits my website, or should i take a look into any other plugin?

# Answer
Almost too many questions in one post, and a little too non-specific for stackoverflow, but I'll try to answer as best as I can:

1. As you've correctly discerned, you'll at least need a node.js server for the wars. Additionally, that node.js server might profit from not having to do anything other than wars. In other words: Even if you choose to use nodejs for the rest of your site, running 2 seperate nodejs servers (or at least processes) possibly even on different machines could help stability. I would probably do a node.js server for the main game and then have it spawn a seperate process for every war.
2. I think it's plausible to do everything in nodejs, a single dynamic page is definitely a better fit for javascript than php, which tends to shine for multi-page websites. Having the main game on a node.js server will also make it easier for it to communicate with the wars server (or process, if you decide to take that route). For client-server communication use websockets, or socket.io if you prefer to use a library instead of raw websockets.
3. I usually avoid using too many libraries unnecessarily, so going with just one library, or even writing your engine from scratch, is how I would do it. Also, make sure you use something that utilizes WebGL if you want 3D animation that runs well. Unfortunately I can't give you advice on any of the libraries you listed, as I have used none of them.
> 0 votes

---
Tags: javascript, html5, php, node.js, three.js
---


title: AABB collision resolution issues

text:
# Question
Title: AABB collision resolution issues
I'm trying to make a character collide with some tiled terrain.

I have an issue with the collision resolution, and after days of shooting in the dark ant not finding any relevant help online, I'm no closer to working collision resolution.

I can detect if the player is *colliding* with the tiles, but I can't figure out how to properly resolve the collision.

I have is so gravity is only applied when there is no collisions in the downward direction, and I have set it so that the proper velocity resolution, so that if I collide with the ground, I don't go through it, but I still go a few pixels into the tile if going at high velocities, and for some reason, if I'm colliding with a surface whose normal is along the x axis (floors and ceilings) It decides that I'm also colliding on the left and right sides as well, and I don't collide with vertical walls at all.

I should note that I'm using MonoGame 3.4.

Physics update code for character

```
public void Update()
    {
        Position += Velocity * TimeHandler.DeltaTime;

        //TODO: add tile collision based on the entity.world property
        var tiles = entity.World.Tiles;

        int minTileX = (int)Math.Floor (Bounds.MinX);
        int maxTileX = (int)Math.Ceiling (Bounds.MaxX);
        int minTileY = (int)Math.Floor (Bounds.MinY) - 1;
        int maxTileY = (int)Math.Ceiling (Bounds.MaxY) - 1;

        bool collidedNegY = false;
        for (int x = minTileX; x <= maxTileX; x++)
        {
            for (int y = minTileY; y <= maxTileY; y++)
            {
                bool kKeyDown = Keyboard.GetState ().IsKeyDown (Keys.K);
                if (kKeyDown)
                    tiles.SetID (1, x, y);
                bool jKeyDown = Keyboard.GetState ().IsKeyDown (Keys.J);
                if (jKeyDown)
                    tiles.SetID (0, x, y);

                AABB tileAABB = new AABB (new Vector2(x, y), new Vector2(1f, 1f), new Vector2(0f, 1f));
                //CollisionInfo info;
                if (tileAABB.Check (Bounds))
                {
                    if (tiles.GetID (x, y) == 0)
                        continue;

                    Vector2 collisionDirection = tileAABB.Position - Bounds.Position;
                    bool xIsRight = collisionDirection.X > 0;
                    bool yIsUp = collisionDirection.Y > 0;
                    bool differentX = xIsRight == Velocity.X > 0;
                    bool differentY = yIsUp == Velocity.Y > 0;

                    if (differentX)
                    {
                        Velocity.X *= 0f;
                        if (Bounds.MaxX > tileAABB.MaxX)
                        {

                        }
                        if (Bounds.MinX < tileAABB.MinX)
                        {

                        }
                    }
                    if (differentY)
                    {
                        Velocity.Y *= 0f;
                        if (Bounds.MaxY > tileAABB.MaxY)
                        {
                            collidedNegY = true;
                        }
                        if (Bounds.MinY < tileAABB.MinY)
                        {

                        }
                    }
                }
            }
        }
        if(!collidedNegY)
        {
            //apply gravity
            Velocity.Y -= entity.World.Gravity * TimeHandler.DeltaTime;
        }

        Bounds.Position = Position;
    }

```

AABB class:

```
public struct AABB
{
    private Vector2 min;
    private Vector2 max;
    private float y;
    private float x;
    private float width;
    private float height;
    private Vector2 offset;

    //position
    public Vector2 Position
    {
        get
        {
            return new Vector2 (x, y);
        }
        set
        {
            UpdateBounds (value.X, value.Y);
        }
    }

    public Vector2 Size
    {
        get
        {
            return new Vector2 (width, height);
        }
        set
        {
            UpdateBounds (x, y, value.X, value.Y);
        }
    }

    public float MinX
    {
        get
        {
            return min.X;
        }
    }
    public float MinY
    {
        get
        {
            return min.Y;
        }
    }
    public float MaxX
    {
        get
        {
            return max.X;
        }
    }
    public float MaxY
    {
        get
        {
            return max.Y;
        }
    }

    public float Width
    {
        get
        {
            return width;
        }
        set
        {
            UpdateBounds (min.X, min.Y, value, height);
        }
    }
    public float Height
    {
        get
        {
            return height;
        }
        set
        {
            UpdateBounds (min.X, min.Y, width, value);
        }
    }

    //update
    private void UpdateBounds(float x, float y)
    {
        this.x = x;
        this.y = y;
        min = new Vector2 (x + offset.X, y + offset.Y);
        max = new Vector2 (min.X + width, min.Y + height);
    }
    private void UpdateBounds(float x, float y, float width, float height)
    {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        min = new Vector2 (x + offset.X, y + offset.Y);
        max = new Vector2 (min.X + width, min.Y + height);
    }

    //constructors
    public AABB(Vector2 pos, Vector2 size, Vector2 offset)
    {
        this.x = pos.X;
        this.y = pos.Y;
        this.width = size.X;
        this.height = size.Y;
        this.offset = offset;
        this.min = new Vector2(pos.X + offset.X, pos.Y + offset.Y);
        this.max = new Vector2 (min.X + size.X, min.Y + size.Y);
    }

    //checking
    public bool Check(AABB b)
    {
        if (this.max.X < b.min.X || this.min.X > b.max.X)
            return false;
        if (this.max.Y < b.min.Y || this.min.Y > b.max.Y)
            return false;

        return true;
    }

    public static bool Check(AABB a, AABB b)
    {
        return a.Check (b);
    }
}

```

# Answer
> 1 votes
Collision resolution is no easy beast. You need to take a step back and realize that you're going to need to simulate some simple physics. Game physics don't have to be super accurate and you can tweak gravity and resultant forces however you want but you need a solid framework to build off of. I recommend that when handling collision resolution you have a Physics management system that's separate from your collision detection system.

How I usually do this is with something along the lines of

```
//Update game logic
//Detect collisions (and store collision data)
//Go through collisions, apply reactionary forces
//Apply forces to all objects (gravity is a force)
//Go back and re-detect collisions (if I want to be super accurate)

```

You're going to need to simulate some basic kinetics. There should be a way for you to apply forces to your objects and derive an appropriate acceleration from that. From there you can look into determining how objects will interact with each other after a collision.

Chris Hecker has some AMAZING resources on this. They apply to 2D and 3D. I've built an okay framework for 3D physics around his resources and it's turned out quite well so far.

http://chrishecker.com/Rigid\_body\_dynamics

http://chrishecker.com/images/e/e7/Gdmphys3.pdf

You might be thinking "Isn't rigidbody dynamics a bit much?" Yes and no. You don't have to try to implement everything in these papers, just focus on what you need. You don't need to rotate anything yet and you don't need to think about 3D.

Collision resolution isn't easy. You may need to come back and ask some more specific questions later :)

---
Tags: c#, collision-detection, monogame, collision-resolution
---


# Question
Title: How can I place the player into a 360° video in UE4?
I have a 360° video (6 separate videos stitched together into a panorama) with a first person view walking through an environment. I would like to put this in a game engine such that the actor can walk forward and backward and it will feel like they are in the environment.

I have tried this in UE4 but am somewhat new to all this. I'm not opposed to using UDK or Unity if that is easier. I have created a `MediaTexture` from the video asset. Now I'm trying to create a `Material` sphere that uses the `MediaTexture` and reflects it back so the actor is essentially in a spinning sphere. I keep getting stuck with these errors:

I understand that I must next construct a blueprint that reads the actor's movement to play back the video, and also rotate the texture coordinates according to the view of actor.

How can I do this?

# Answer
What you need is an animated skybox. You'd simulate player movement by scrubbing the animation depending on backward/forward input.

And a basic first person camera gives you the view rotation for free.

I don't if UE4 can do this, and how, but I'd start by checking these tutorials on YouTube and work out the blueprint from there:
> 1 votes

---
Tags: unreal, video, 360-video
---


# Question
Title: (Unity) Optimised networking solution for many moving objects
I've currently undertaking quite an ambitious project. In short, it's a real time multiplayer strategy game which has bacteria mechanics.

Essentially, I have two remote players in the environment, and they can spawn bacteria-like units which attack each other and multiply, duplicating themselves until a resource limit is hit. This often results in around 200+ game objects being rendered to the screen, each with their own state and movement. This sounds bad, but the local gameplay against a bot is actually very good, and I've managed to make it quite performant.

However, the issue arises when I try to network this game. I have already attempted to follow this guide to implement this feature: http://www.paladinstudios.com/2013/07/10/how-to-create-an-online-multiplayer-game-with-unity/

This produces quite a slow, displeasing game experience even with the best latency. This is likely caused by having to transmit movement data for hundreds of units.

# The question I am posing:

How can I optimize the networking and synchronization of many moving units between two clients?

I've already thought of one way to do this. After spawning a unit, they will only travel in one direction until they hit something - perhaps I can synchronize only when units are spawned and when they interact with another object? Would this have much benefit? What's the ideal way to implement this?

Thanks in advance for responses!

# Answer
For 200+ moving objects, you're definitely going to want to make your game lockstep. With lockstep, comes the need for determinism but that shouldn't be too hard for bacteria (which can be simulated with circle-circle collisions).

If you don't mind my shameless self-plug and want an example with the networking and simulation logic of a lockstep game, check out this asset for free: https://www.assetstore.unity3d.com/en/#!/content/36206. Unfortunately, that version doesn't include all the source code but feel free to hack it with my blessing ;). Here's a video of an early test of DPhysics: https://www.youtube.com/watch?v=NEzOghxfMdU.

The gist of lockstep is syncing input instead of output. This is because with a synchronous simulation, the only thing all clients don't know about is other clients' inputs. The article you linked in your comment explains it pretty well. I'm not sure how in-depth you'd like me to explain lockstep, so I'll cut it off here and expand this answer if you have any more questions.

Update: Think of it as an authoritative server, except the server sends input instead of game state. Since every player can produce the game state for himself from input, there's no need for the server to distribute the gamestate.
> 1 votes

---
Tags: unity, c#, networking, optimization, mmorts
---


# Question
Title: Running and Jumping using Box2d and libgdx
.this is my first trial on making a 2d game and currently struglling how to run and jump smoothly. My problem is when the player keep pressing on left or right botton then jump. the player won't jump, also when keep on holding left or right. the speed gets faster

```
if (KeyInput.isPressed(KeyInput.Button.JUMP)) {
    body.applyForceToCenter(0, playerJumpForce, true);
}

if (KeyInput.isDown(KeyInput.Button.LEFT)) {
    body.setLinearVelocity(new Vector2((body.getLinearVelocity().x - (playerSpeed * delta)), 0));
}

if (KeyInput.isDown(KeyInput.Button.RIGHT)) {
    body.setLinearVelocity(new Vector2((body.getLinearVelocity().x + (playerSpeed * delta)), 0));
}

```

# Answer
> 3 votes
You don't want to use `setLinearVelocity` for horizontal movement as that set's the velocity to a value it will cancel out any force applied because of a jump.

For moving left and right you want to use either `applyForceToCenter` (like what you do for your jump), or `applyLinearImpulse`.

You might want your code to do something like this to limit the ever increasing speed when walking;

```
if (KeyInput.isPressed(KeyInput.Button.JUMP)) {
  body.applyForceToCenter(0, playerJumpForce, true);
}

if (KeyInput.isDown(KeyInput.Button.LEFT)) {
  body.applyForceToCenter(Math.abs(body.getLinearVelocity().x) < MAX_SPEED ? speed * deltaTime, 0));
}

if (KeyInput.isDown(KeyInput.Button.RIGHT)) {
  body.applyForceToCenter(Math.abs(body.getLinearVelocity().x) < MAX_SPEED ? -speed * deltaTime, 0));
}

```

Also note that you will probably need to detect if the player is standing on the ground and only allow jumping then.

---
Tags: libgdx, box2d, platformer
---


# Question
Title: issue with ray/physics collision detection
All,

I am trying to pick object using ray collision and bullet physics

I am initializing my projection and view matrix only once, here is the code

```
projectionMatrix = glm::perspective(90.0f, 4.0f / 3.0f, 0.1f, 100.0f);

float horizontalAngle = 3.14f;
float verticalAngle =0.0f;/// problems here

glm::vec3 direction(
    cos(verticalAngle) * sin(horizontalAngle),
    sin(verticalAngle),
    cos(verticalAngle) * cos(horizontalAngle)
);

glm::vec3 position = glm::vec3( 0.0, 10.0, 32.0 );

glm::vec3 right = glm::vec3(
    sin(horizontalAngle - 3.14f/2.0 ),
    0,
    cos(horizontalAngle - 3.14f/2.0 )
);

// Up vector
glm::vec3 up = glm::cross( right, direction );

viewMatrix =  glm::lookAt(
                            position,           // Camera is here
                            position+direction, // and looks here : at the same position, plus "direction"
                            up                  // Head is up (set to 0,-1,0 to look upside-down)
                       );

```

See below screenshot with actual object in the world

when I click on red area - it does not pick up object, but when i am click on green one - it does.

**SMALL DETAIL:** I've used this tutorial http://www.opengl-tutorial.org/miscellaneous/clicking-on-objects/picking-with-a-physics-library. While I've applying constant change to view and projection matrix throug my mouse move and keys - detection work perfect, but once I've stooping doing it - it does not work.

Can someone help me out what I am doing wrong ?

# Answer
it was about NDC conversion on Y axis. this should be properly calculated. I have to reflect it.
> -1 votes

---
Tags: bullet-physics, glm, picking
---


title: Parse/Write JSON with Unity iOS

text:
# Question
Title: Parse/Write JSON with Unity iOS
anybody know a tutorial or maybe can help me to develop a parser/reader for JSON compatible with Unity iOS pro? I've already tried different third part libraries but without luck (i've tried json.net, jsonfx, litjson).

Im pretty in hurry of doing a simple parser/writer that i can use also under iOS and not only in Desktop.

P.s. i can also use third part library, but please, first of suggest be sure that it will work under iOS! Thank you all

# Answer
> 1 votes
I've tested a lot and finally i've found this: https://gist.github.com/1411710

It'is not the best, but is iOS friendly and fit pretty well for now.

---

Matt i dont have test the library that you suggest me, but when i will find some free time i will test and let you know :)

If someone find some other library (a porting of Json.net would be beutiful) please post :)

# Answer
> 3 votes
I'd personally recommend SimpleJson from The Outercurve Foundation (link below), Works very well on withe portable platform I'm working on (playstation mobile) which like unity is c# :)

https://github.com/facebook-csharp-sdk/simple-json

# Answer
> 2 votes
We have spent quite a lot of time in :

searching -\> testing -\> trying to modifying the json pluggin -\> trying to modifying our code to fit this json plugging -\> fail again -\> searching a new json.

And at last, we have to came back to the easiest json like DannoEterno said, the MiniJSON. Although this one has the least functions.

We have tried : LitJson, a strong pluggin, can be used in iOS, support object mapper, but it can't use a integer as key for dictionaries, which is very important for our game

Newton Json, like litJson, support object mapper too. it works well when serialisation in ios, but failed in deserialization.

MiniJSON, simplest pluggin, doesn't support object mapper. You have to do quite a lot of work to organize your data structures, write your own serialization and deserialization for every object you want to save. It is a lot of physics work.

We have even tried :

MsgPacker, a great pluggin, if you want save something in using object mapper, try this first, it can be used in ios. Due to some issue caused by networking, we have to give up this pluggin. There is a someone who write a MsgPacker special for unity3d. The official one cannot be used in unity3d. Try to google it by MsgPacker unity3d.

In my opinion, avoid using object mapper. Because it depends on reflection in c#, which means you cannot use micro mscorlib for your app. WTF!

Best wishes. my friends!

# Answer
> 1 votes
Danno -

Here's a Unity port of JSON .NET: Unity JSON .NET Works for JSON, BSON and it works in IOS

# Answer
> 1 votes
Reference unity asset : Easy JSON Hashtable

This package is very easy and can be easily converted JSON.

JSON string can be easily converted into Hashtable.

Hashtable that also can be easily converted into a JSON string.

# Answer
> 0 votes
We're using JSONObject from the Unify wiki. Not sure how this compares to other options people have brought up.

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


# Question
Title: How do you make a Pong slider using touch events for mobiles?
I am stuck with an issue of moving the slider on android mobiles with finger touch event while developing pong game in unity 3D, though its working fine for pc.

This game is developed in 2D environment... please help me if anyone have available solution to this issue

Actually I have developed this game for pc so I have code for the movement of slider accordingly as below:

```
var keyup:KeyCode;
var keydown:KeyCode;
var speed:float=1;

function Update () {
    if(Input.GetKey(keyup))
        rigidbody2D.velocity.y=speed;
    else if(Input.GetKey(keydown))
        rigidbody2D.velocity.y=speed*-1;
    else
        rigidbody2D.velocity.y=0;
}

```

But now i want to use this game for android mobiles.

# Answer
> 1 votes
You can create a script attached to the object you want to drag and adapt your code to work inside OnMouseDown() & OnMouseDrag()

---
Tags: unity, 2d
---


# Question
Title: How to make different 2 object's collider with the same location in Unity 2D
I have made my own game, but I can't change the object's collider properties from the interface. I can't click on the expand button, because behind it there are other colliders.

How could I change the collider's properties ?

# Answer
I suppose you are using `Raycasting` to detect mouse clicks. You can use `Object's name` or `Sorting Layer` or `Order in Layer` or a combination of those properties to identify which layer you hit. There is no standard way to do what you are trying to do. It is just preference.

You can attach this script to your camera, or background or an empty object you made specifically for this script.

```
// In your Update method
void Update()
{
    // If left mouse was clicked
    if (Input.GetMouseButtonDown(0))
    {
        Vector3 clickPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        // Use raycasting to determine which objects were clicked
        RaycastHit2D[] hits = Physics2D.LinecastAll(clickPosition, clickPosition);
        // If any object's 2D-collider was clicked
        if (hits != null)
            // This will iterate through ALL clicked objects
            foreach (RaycastHit2D hit in hits)
            {
                // The clicked object
                GameObject clickedObject = hit.collider.gameObject;
                // The clicked object's sprite renderer
                SpriteRenderer renderer = clickedObject.GetComponent<SpriteRenderer>();

                // Print a few properties of the clicked object
                Debug.Log(clickedObject.name); // Object's name
                Debug.Log(renderer.sortingLayerName); // Sorting Layer
                Debug.Log(renderer.sortingOrder); // Order in Layer
            }
    }
}

```
> 0 votes

# Answer
It is not very clear what you're asking. If it is about rendering objects in desired order, then @Shiro clarified that. If you're asking about working in the editor, then, create temporary layer called "temp". Assign this to the desired GameObject. Then, at the top of inspector, you see a layers drop down. Here you will see some options with an eye symbol. This determines visibility. Click on symbol for "Nothing". Now everything in your scene disappears. Next, click on the symbol in front of temp. Now, only objects belonging to the layer "temp" are visible.
> 0 votes

---
Tags: unity, unityscript
---


title: What projection is this?

text:
# Question
Title: What projection is this?
Could someone tell me what this projection is called?

It's as if you are looking at an object from directly above it and then smear it up and left equally. Only the one dimension seems to be true scale while the other two are skewed.

I'm not finding many games that uses this style, but some of the Ultima Series seemed to or at least something similar:

# Answer
That's an Oblique Projection.

Oblique is a type of parallel projection where the projection "rays" are not perpendicular to the image plane.

Usually this is used to show two spatial axes perpendicular & without foreshortening (as though looking directly down the third axis), while the third axis is splayed off at a diagonal. In an orthographic projection, this third axis would be invisible because we're looking at it edge-on.

Depending on the amount of foreshortening on the diagonal axis we might call it a more specialized name:

* a Cavalier projection (no foreshortening of the receding axis)
* a (45-degree) Cabinet projection (receding axis foreshortened to 50% its normal length)

Note that both of these projection titles are used most commonly with the front or side of an object presented undistorted, with the depth axis skewed. In your case, it's the top view that's undistorded, with the height axis skewed. The principle is still the same though.

Further reading, including examples of additional games using oblique projections.
> 22 votes

---
Tags: projection, terminology
---


# Question
Title: How to resolve collisions when using ray-casting to predict the location of future collisions?
I ran into a question I can't seem to solve, while implementing the movement/ collision checking code for my game. The game is in 2D and all objects in my game use either AABBs or circles as collision masks. My current procedure for moving a game object uses the following steps:

1. **\[Motion definition\]** Set the motion vector for the game object as vec2(xSpeed, ySpeed)
2. **\[Broad-phasing\]** Broad-phase to find potentially colliding objects
3. **\[Collision detection\]** Raycast the AABB along the motion vector, against all objects found in step 2, and find the first collision
4. **\[Collision resolution\]** Move the game object to this position where the first collision occurs

Below is a screenshot of the collision detection. It casts the object's AABB (bottom-left blue rectangle) along the motion vector (red line) and finds the points where the AABB would enter and exit the other object's AABB (big blue rectangle). It returns me the position, normal and lambda (progression \[0.0, 1.0\] along the motion vector when entering/ exiting the other object).

Practically, the ray casting of AABBs is performed as a line-raycast on the configuration space obstacle of the two AABBs. I've implemented this for line-circle, line-aabb, circle-circle, and aabb-aabb cases and they work correctly.

---

My **problem** is the **collision resolution** step. The problem is that my objects get stuck in eachother using the current procedure. The reason being that the raycast procedure returns the position where the object "just collides" with the other object. Because of this, on the next update of my game world, the object is already colliding before it even moves. When I perform my collision detection step, the results is that the "first collision" occurs at the starting position of the object.

I've been reading related questions here, but haven't found a definitive answer yet. Here are some of the things I've read and problems I found with them (from "bad" to "better"):

1. **\[Don't move if a collision is encountered on the way\]** This could cause jittery and weird behavior when moving towards an object. As, e.g. if the object is moving at 5 pixels per frame towards a wall, it will end up somewhere between 5 and 0 pixels away from the wall, depending on it's position. I suspect jittery behavior to happen when this solution is extended to collision checking between moving objects.
2. **\[Implement IsTouching() methods to check whether an object is colliding but not penetrating another object\]** I have no idea how to elegantly use this information in the raycasting algorithms to allow "sliding behavior" of shapes, without sacrificing performance (as the algorithms are very optimized right now). Also, I imagine objects "touching" is defined as having a penetration depth of 0.0. Checking for this could cause errors in case of float rounding errors.
3. **\[Push away both the object and the colliding object upon colliding\]** Some of my objects (such as walls and terrain) are static and I'd rather not move them even slightly to resolve collision problems.
4. **\[Push the object out of the colliding object along the collision normal\]** Using this solution, the object can get stuck in another object, as it gets "blindly" pushed out of a colliding object.
5. **\[Push the object out of the colliding object backwards along the motion vector\]** This sounds good as the object won't get stuck in other objects. However, I'm not sure how to choose "how much" to push the object out of the other object. The best thing I can think of is to move it using "a very small float number" such as 0.00001f. But this sounds very ad-hoc.

---

**In short:** Where do I move my object, if I know exactly where the first collision would occur, without getting it stuck in other object?

# Answer
> 1 votes
There are two steps to solving this problem.

First you need some extra data on collision. When two objects collide you want to know how far they've collided into each other.

After that you want to move the two objects backwards. Depending on how accurate you want it you could just take the amount that they overlap, divide it in half and then just move each object back by that amount (not good if only one object is moving obviously). If you want to be more accurate you can try to determine how fast each object was going on impact and move them apart depending on which one was going faster.

After you've separated the two objects from colliding you can apply your resultant forces. Again if you don't need to be SUPER accurate you can end here and just let further collisions sort themselves out.

A way to increase the accuracy of your collision response here is to iterate this process. Each object will detect and react to collisions multiple times per frame so that if one collision results in another immediate collision you can account for it. You want to put a limit on this so that you don't end up with an infinite loop of collision detection. Objects that are more important will have higher iteration limits.

There are a few different algorithms to determine object overlapping that can be done as apart of the collision detection step. If you use the Separating Axis Theorem (SAT) you can do this pretty easily but that's more for 3D. It's even easier to do it with circles and AABBs in 2D.

Here's a quick example to get the overlap for two circles colliding:

```
float IsColliding(Circle c1, Circle c2)
{
    float distanceBetweenCircles = (c2.center - c1.center).magnitude;
    float radiiSum = c1.radius + c2.radius;

    if (radiiSum > distanceBetweenCircles)
    {
        //Return the amount of overlap
        return distanceBetweenCircles - radiiSum;
    }

    //No overlap, no collision
    return 0;
}

```

---
Tags: collision-detection, collision-resolution, raycasting
---


title: 2.5D Game design principles

text:
# Question
Title: 2.5D Game design principles
I want to make an isometric game like in the picture.

At point "1" character must be visible and the train car drawn behind the character. At point "2" the train car should cover the character so that the character is behind the train car.

This is not a 3D game but a 2D game, what is the principle called that makes this happen? or maybe there is a good tutorial somewhere.

Thank you.

# Answer
You will need to take a look at isometric rendering principles. Read more about isometric projection for more details on wiki

Since you are in the 2d space you will need to specify the order of drawing. By drawing things all on the same "layer" you will run into tiles rendering "strangely". By applying proper layering you can draw the farthest away tile(typically top left corner) and draw the rest of the map which will be on a higher layer in order to accomplish the desired rendering.

Will write up some more details this weekend and link them here if it's helpful.
> 1 votes

---
Tags: game-design, 2.5d
---


# Question
Title: Why do we need a fourth coordinate to divide by z?
I read the response here:

What does the graphics card do with the fourth element of a vector as the final position?

> "The fourth component is a trick to keep track of perspective projection. When you do a perspective projection, you want to divide by z: x' = x/z, y' = y/z, but this isn't an operation that can be implemented by a 3x3 matrix operating on a vector of x, y, z. The trick that has become standard for doing this is to append a fourth coordinate, w, and declare that x, y, z will always be divided by w after all transformations are applied and before rasterization. "

but I didn't understand why couldn't we divide by z using a 3x3 matrix?

can't we just multiply by

```
1/z 0 0
0 1/z 0
0 0 1/z

```

to get `[x/z y/z 1]`

?

# Answer
> 16 votes
Because if you only divide `[x, y, z]` by `z` you get `[x/z, y/z, 1]` and you lost the actual value of `z`, which is actually useful if you want to do near/far plane clipping or fill a Z-buffer.

The best way to keep some information about `z`, at least on the GPU, is therefore to use 4 components instead of 3. In practice, what is actually in the last two vector components before the perspective division depends on what kind of projection and effects you want.

For instance, in the case of a perspective projection, this is the resulting 4-component vector:

```
| a 0 0 0 |   | x |   |   ax   |
| 0 b 0 0 |   | y |   |   by   |
| 0 0 c d | × | z | = | cz + d |
| 0 0 1 0 |   | 1 |   |    z   |

```

After perspective divide the vector becomes:

```
|  ax/z   |
|  by/z   |
| c + d/z |
|    1    |

```

And the `c + d/z` part leaves us with enough information to fill the Z buffer.

# Answer
> 3 votes
Technically, you *could* do that. But why bother? By the time you have that final `z`, you could either:

* construct a 3x3 matrix as you described, wasting `9 * sizeof(float)` bytes of space, spending cycles to compute `1/z` (one division) and then doing nine multiplies and six adds to get your final vertex, *or*
* you can do three divisions, as the modern pipeline currently does

One of these seems far more optimal to me, and it's not the first one. Even if optimized hardware exists for the matrix multiply, as it most certainly does, it's still conceptually more complex than a simple division.

Plus, a 3x3 matrix cannot encode a translation, and so a 4x4 matrix (and thus the fourth `w` coordinate) is used earlier in the pipeline *anyway*. This means you already have that fourth component sitting there so you may as well use it to transport a useful value and do your division with it.

---
Tags: matrix, transformation, projection-matrix
---


# Question
Title: Unity3D Interactive Cloth Basketball Net Falling Apart Though Not Tearable
I have a basketball net mesh attached to an Interactive Cloth with the following attributes:

The mesh is not segmented and is not marked as tearable but as soon as the game starts the net falls apart into individual ropes like so:

First moment:

A moment later:

I am not great at 3D Modeling and have tried several downloadable nets with similar results. What would you do to keep my net together?

# Answer
> 1 votes
I have made 2 similar basketball games in Unity. What I ended up doing was:

* create a torus in blender with the same number of segments around as your rim and stretch it out into a funnel shape matching the general outside shape of your net.
* create / find an net image that looks like a flattened out net.
* in Unity, import your funnel and use your net image your texture.
* use a shader that supports transparency (like Mobile/Transparent/Vertex Color) and tile the texture so the seems line up both around the net and on both the inside as outside

The resulting mesh should have far fewer polys and look nearly as good but most importantly, the cloth physics work better with it.

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


# Question
Title: cocos2d-js displays only one type of tile from a tmx file
I am using **Tiled** to produce a `tmx` which I use in my code using **cocos2d-js**. The problem is that when I run it on the browser, a wrong tile gets displayed, the first one of the image (0,0) and repeats for the whole map. The relevant js code is this:

```
this.farm = new cc.TMXTiledMap(res.farm_tmx);
this.addChild(this.farm);

```

where `res.farm_tmx` the path to the tmx file.

What could be the source of the problem? And how do I fix it? It seems to me that it is specific to my code. I do not find any other reports of the same problem.

# Answer
Maybe you forgot to preload the tileset image?
Besides preloading `"res/farm.tmx"`, you may have to preload, say, `"res/farm.png"`.
I had the same problem, and that solved it for me.
> 1 votes

---
Tags: javascript, cocos2d, tiled
---


title: reflection plane 3d

text:
# Question
Title: reflection plane 3d
Hey there I'm trying to create a plane that can have a texture on it and reflect the 3d elements around it. for example a plane with a laminate floor texture and above it a cube rotating. I want the plane to retain the floor texture but have a reflection of the cube.

I've been trying to figure out how to go about doing this. I'm using flash stage3d capabilities and a 3d engine but i'm sure the same principles will apply from other engines and languages.

From what I can tell I create some kind of reflection matrix from the plane? and then use that somehow with the camera position?

Any further info/drawings/guidance is greatly appreciated.

# Answer
1)Create a plane that usually contain a point and a normal that represents the floor.

2)Reflect your camera position and rotation from this plane.

3)Create a view matrix from these point and rotation.

4)Render scene from this matrix into a texture.

5)Transmiss those texture and matrix into a shader.

6)Project texture onto a surface of floor using transmissed matrix.

7)???

8)PROFIT!
> 2 votes

---
Tags: camera, matrix, reflection-rendering
---


# Question
Title: Cloning a gameObject which use properties similar to original gameobject
How to make clone of gameobject have the same properties as the original gameobject just placed right to it and the clone should fire exactly parallel to original character. Every property should be same.

actually I have a player having 4 skills and I wanted to add one more skill to my player (5th skill) so that it can clone itself and do everything like its original player and one restriction will be there is clone player should be just right(2-3 units) to the original player.

# Answer
> 0 votes
Instantiate()

```
var clone = Instantiate(originalGameObject, position, orientation)(GameObject);

```

See this tutorial for more information.

I'd encourage you to read the scripting documentation or try some tutorials - this type of answer is very easy to find on your own.

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


# Question
Title: Can Unity support / use textures that are not square?
I have been told by another highly skilled Unity artist that Unity cannot efficiently handle non square images. Since that doesn't sound right to me, I wanted to get a second or third confirmation to that claim.

Having worked in the game development industry for almost 15 years, I have always understood that best practice was keeping in powers of two, but that if the UV map called for it, a 1024x512 map was acceptable, rather than using a 1024x1024 map with 1024x512 pixels of wasted UV space. Granted, that was best practice on game engines other than Unity.

Can anyone confirm that in Unity's case, it is better (best practice) to have a 1024x1024 image containing UV islands occupying 1024x512 pixels, rather than using a 1024x512 image map to exactly accommodate the UVs?

Which platforms can use non-square images and which ones cannot with the Unity engine? I am particularly interested in whether or not this limitation affects PC builds.

# Answer
Yes, it can. But certain devices will suffer. For example, iOS PVRTC texture compression doesn't work without square textures. I think Unity makes them square, so you end up with your textures taking up a bunch more RAM to accommodate PVRTC.

See Unity Documentation: 2D Textures for more details.
> 4 votes

---
Tags: unity, textures, uv-mapping
---