title: deformable terrain

text:
# Question
Title: deformable terrain
I'm currently working on a 3d sandbox mmo and would like to know what would be the best way to store the terrain of the world. I was thinking about making some kind of mesh, like the kind you would get from an obj file, that would define the whole world. I would have one for every type of terrain there is (a stone layer covered by a dirt layer and the stone layer could have "tunnels" of ore, each with it's own mesh defining the shape of it). I would then pass part of that mesh to the players depending on where they stand in the world.

I'dd like to allow the players to deform the terrain and dig holes and caves (like you would see in planet explorers or space engineers) in a persistent world so no need to generate it on the fly.

I've seen many post online talking about isosurface and even tho i searched far and wide, i couldn't find a clear definition of what that was or if it applied in my case. I just want to know if storing the terrain as a mesh would be the best approach. And if so, would it be best to have it based on a strict x,y,z integers or would it be possible to have it stored as floats for more diversity?

I intend to have a smooth terrain using marching cubes or dual contouring. can you give me your thoughts?

# Answer
> 3 votes
I am going to go on a whim and say that you are using voxels, because you want to be able to dig holes and tunnels live. Storing a world whose state can forever change as a .obj would not be a good idea.

For your sanity, and your customer's sanity, you would be better off choosing a different format style.

First step: split the world up into chunks. If an area gets corrupted, you can just reload the chunks around it instead of the entire map.

Second step: writing to disk.

My suggestion would be to save information about the voxels themselves as a texture 1D, 2D, or 3D. You can reduce the bits for color information to reduce the size some. But you probably don't want to get rid of it all. You can then use the color parameters to store information about the world state.

(Roy Gee Biv = RGB colors) Example... For a 2D texture Roy can tell you the material in that location. Gee can tell you the depth. And Biv can store bit fields if needed.

For a 1D, Roy can tell you depth, Gee can tell you depth, Biv can tell you the X location, and Alpha can tell you the Y location.

Given the game is an MMO, it is expected that the servers will be up for a long time. It will not matter how quick it is to load an object, as long as it's efficient.

When the game saves, it just dumps each chunk into a texture somewhere on the disk as a backup. When it needs to revert back to a backup, it can load in the texture. So at this stage, you are re-reading cubes.

Your world is already capable of smoothing out geometry if it does. So you don't need to worry about the state of it's geometry. The game will simply rebuild it all once more in a couple of seconds.

The benefits would be that you don't have to make your own dang library or file format. There are also lossless compression algorithms for 2D textures as well.

The cons are that you might not be able to store information that is more than just the world's geometry. This could be a very big con... could be a very small con. But... there is no rule preventing you from loading in two files if this is the case. Which can be a nice feature.

---
Tags: java, lwjgl, terrain, 3d-meshes, terrain-rendering
---


# Question
Title: deformable and variable text on a mesh in unity
So I am working on a sports game and I want the jerseys to be customizables with names and numbers. I have the character models as a single mesh however I can't place a text on the back of the jersey for the player to customize. I've found that unity has a Text Mesh, however it is not deformable. When the player runs, the number and name instead of being glued to the shirt actually appear more as a sign attached to the avatar's back. How can I do this text on the players jerseys, that can change its value via user input and to have the properties of the shirt object?

# Answer
> 1 votes
You need to add the text through the material which is applied to the player. There are numerous ways to do this.

1) By code write the player's name and number on the shirt image , and then reapply it to the material.mainTexture for the player's mesh. (This has a downside tho :P)

2) Another way is to have an additional transparent rectangular mesh on the back which gets deformed exactly as the the shirt mesh. Then add the players number and name to that material. Note: The material should be transparent cutout.

3) Decals also works great , generally used as a overlaying texture over a mesh to illustrate dirt or wearing . You can apply name and number decals to the shirt material.

---
Tags: unity, models, text
---


# Question
Title: What does glTranslatef function is translating in this code?
I understand translation from mathematics view where we can have a triangle with a certain coordinates. We can translate this triangle by multiplying the coordinates of the triangle (expressed in the form of a matrix) by a translation vector.

In the code below, I could not see what glTranslate () is translating since we havent drawn anything yet. What are we translating? Are we applying the translation to some default objects or something?

```
         void display(void)
     {
     glClear (GL_COLOR_BUFFER_BIT);
     ///////////////////////////////////////////////////////
     glPushMatrix();
     glTranslatef (-1.0, 0.0, 0.0);
     glRotatef ((GLfloat) shoulder, 0.0, 0.0, 1.0);
     glTranslatef (1.0, 0.0, 0.0);
     glPushMatrix();
     glScalef (2.0, 0.5, 1.0);
     glutWireCube (1.0);
     glPopMatrix();
     ////////////////////////////////////////////////////////
     glTranslatef (1.0, 0.0, 0.0);
     glRotatef ((GLfloat) elbow, 0.0, 0.0, 1.0);
     glTranslatef (1.0, 0.0, 0.0);
     glPushMatrix();
     glScalef (2.0, 0.5, 1.0);
     glutWireCube (1.0);
     glPopMatrix();
     /////////////////////////////////////////////////////////
     glPushMatrix();
     glTranslatef(1.6, 0.22, 0.0);
     glRotatef ((GLfloat) finger, 0.0, 0.0, 1.0);
     glScalef (0.6, 0.1, 0.08);
     glutWireCube (1.0);
     glPopMatrix();
     glPopMatrix();
     ////////////////////////////////////////////////////////
     glutSwapBuffers();
     }

```

# Answer
> 1 votes
Each gl\* commad there changes the state of the OpenGl state machine. so the `glTranslatef` command sets the translation of whatever you draw after that command.

Its like setting a global World Transform matrix to that particular translation. All the vertices you draw after that call to `glTranslatef` will be rendered with that translation applied, until of course when you tell OpenGL to change that translation again with `glTranslatef` or something similar.

---
Tags: opengl, transformation
---


title: How to implement view bobbing?

text:
# Question
Title: How to implement view bobbing?
I'm developing a First-Person shooter game. Everything is just fine but I've a little problem with my camera moving.

My FPS camera is moving smoothly! But the camera should move like a human is walking and his head is doing up and down.

Now I'm stuck! So what kind of algorithm can I use for that purpose?

Any kind of help is appreciated.

# Answer
> 4 votes
Head bobbing consists of transformations to the camera to imply human movements of the player. The player would be using his/her feet to step from one foot to the other. This causes all sorts of changes to the viewpoint of the player but we're just going to look at a few.

Let's define a function to call with some time value which we can then plug into an oscillator to then apply the bobbing. I'm using Unity3D and C# as an example but the concepts apply to anything. For those unfamiliar `Transform` holds object transform data (position, rotation) and `Rigidbody` holds physics information (velocity).

```
void ApplyBob(float time, GameObject playerObj, GameObject camObj)
{
    Transform t = camObj.GetComponent<Transform>(); //Position and rotation of camera
    Rigidbody rb = playerObj.GetComponent<RigidBody>(); //Velocity of player

```

We want the head bob to be based both on time and the player's velocity so let's calculate the velocity as well.

```
    Vector3 vel = rb.velocity;
    vel.y = 0; //0 out y (up) component for xz velocity only
    float velocity = vel.magnitude;

```

Obviously if the player isn't moving, we don't need to apply any head bob (We check it against a threshold instead of 0)

```
    if(Mathf.Abs(velocity) <= 0.0001f)
        return;

```

Now we need to plug it into some sort of oscillating function, we'll stick with sine.

```
    float bobOscillate = Mathf.Sin(time * velocity * (2 * Mathf.PI));

```

So now we have an oscillating function from -1 to 1 which completes one cycle every at the same rate as the velocity (1 unit/second in velocity would give 1 Hz in bobbing).

What we do now is take this and apply it to all the values we want to bob.

```
    t.position.y += bobOscillate; //Oscillate the position in y (up) axis)
    t.rotation.x += bobOscillate * 5; //Oscillates 5 degrees in each direction around x axis, presented this way for clarity (if using Unity3D, use Transform.Rotate)
}

```

This is the most basic setup you'd need for head bobbing. To perfect it for your specific game you'd want to do with following.

* Replace the sine function with a different or transformed function. Sine is a very smooth, ideal function which probably doesn't best represent the jerkiness and subtleties of human motion. Using a different oscillating function (or even one that draws on a custom data set and interpolates between the values similar to what might happen with motion capture data) would be much better.
* Changing the oscillator frequency to better match your players velocity for your given engine and player walking animation. This would require adding some constant multiplier into the `time * velocity * 2*pi` portion of the line of code with the sine function.
* Adding more values to oscillate instead of just the height of the camera and the rotation to better simulate head bobbing.

All of these things would require more research into how humans actually walk and move or just playing around with things until they seem realistic enough / desirable.

---
Tags: algorithm, camera, movement, first-person-shooter
---


# Question
Title: Position Unity UGUI ScrollRect Content Position from Script
I have a map in my game the user can interact with. I am using Unity UGUI `ScrollRect` to let the user move the map on the screen. Only one area of the map is visible at a time and you can scroll it to get to the desired level (just like in King games). The content of this map system is an `Image` and level buttons which are all children of the map image.

I want my `ScrollRect` to point to the current active level when the map loads. For example, if I am on level 30 then on loading the map level the content of the `ScrollRect` should be on the portion of the map where level 30 is.

I can't find anything regarding managing `ScrollRect`'s content position

# Answer
I believe you're looking for the scrolling position parameters for ScrollRect

You would need to find your level marker's position in it's parent (the ScrollRect) and then convert it to a normalized position (divide position by the parents width/height). From there you can set the horizontal and vertical normalized position to the desired values.
> 1 votes

---
Tags: unity
---


# Question
Title: SDL_LoadBMP into glTexImage2D results in scewed colors
I read up on this but i can not find the error. Some suggest switching the format from RBA to RGBA but the surface data says it is 3 byte data.

Here are snippets and results of my source.

Loading the Image:

```
std::string bmpname = filename + ".bmp";

SDL_Surface * surface = SDL_LoadBMP(bmpname.c_str());
if (surface)
{
    glGenTextures(1, &m_texture_name);
    glBindTexture(GL_TEXTURE_2D, m_texture_name);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    GLenum mode;

    switch (surface->format->BytesPerPixel)
    {
    case 3: mode = GL_RGB; break;
    case 4: mode = GL_RGBA; break;
    default:
        BOOST_LOG_TRIVIAL(trace) << "" << *this << " failed recognize byteformat '" << bmpname << "'.";
        break;
    }

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, surface->w, surface->h, 0, mode, GL_UNSIGNED_BYTE, surface->pixels);
    SDL_FreeSurface(surface);
}
else
{
    BOOST_LOG_TRIVIAL(trace) << "" << *this << " failed to load '" << bmpname << "'.";
}

```

Output on the left, texture on the right:

Shaders:

```
//Vertex Shader
#version 120
attribute vec3 position_ATTRIB;
attribute vec2 texcoords_ATTRIB;
varying vec2 texcoords;
void main()
{
    texcoords = texcoords_ATTRIB;
    gl_Position = vec4(position_ATTRIB, 1.0);
}

//Fragment Shader
#version 120
uniform sampler2D diffuse;
varying vec2 texcoords;
void main()
{
    gl_FragColor = texture2D(diffuse, texcoords);
}

```

What is going on here, why is the color palette blueish?

# Answer
You are checking how many bytes there are per pixel, but you are not checking how colours are ordered, and it could be RGBA or BGRA (or possibly something else). You need something like this instead of `mode = GL_RGBA` (little-endian machines):

```
if (surface->format->Rmask == 0x000000ff)
    mode = GL_RGBA;
else
    mode = GL_BGRA;

```

If you want a more generic solution, create a temporary surface (`SDL_CreateRGBSurface`) with the exact image format you want, then copy `surface` onto that temporary surface (`SDL_BlitSurface`).
> 3 votes

# Answer
For this case the BMP was not in RGB Format but in BGR Format. Switching those made the colors appear correctly.

Im am not sure how a generic version would look like.
> 0 votes

---
Tags: opengl, shaders, textures, color, sdl2
---


title: Assimp, Blender and model rotating

text:
# Question
Title: Assimp, Blender and model rotating
There is something I can't figure out.

I have two models - grass.blend and tower.blend.

grass.blend:

tower.blend:

Note X, Y and Z axises.

The problem is that when I load these models using Assimp the scene looks like this:

The tower should be placed vertically, but for some reason it is placed horizontally. I didn't rotate it this way. Why is it happening?

Project example is here (tower was rotated in Blender right way for now). Tower model could be downloaded from blendswap.com.

# Answer
A common problem exchanging 3D data between different programs is the axis directions. The cause of the issue comes when deciding the direction of each axis, blender uses the right handed cartesian system which is also common among cad modelling systems, while many other 3D programs have the y-axis pointing upwards with the z-axis pointing to the back, which matches up with the z-depth used when rendering.

Of your two models, the ground is selected and shows it's local y-axis matches the global y-axis. If you select the tower you will find it's local axis will not match the global display which will cause the difference when exporting. Applying the rotation of the tower `⎈ Ctrl``A`-\>Rotation may also help.

Many export addons give an option to alter the up axis during the export. The obj exporter even lets you choose the up as well as the forward axis.

This is just something you need to remember to consider when transferring data.
> 2 votes

---
Tags: opengl, c++, models, blender, assimp
---


# Question
Title: Finding the scale of pixels in map with given dimensions
For the game I am making, I have textures for planets. Each texture has a size of 2048 x 1024 pixels. I also know the size, thus the diameter, of each planet. Not every planet is the same size, you know.

**What is the size in kilometers of one pixel?**

I know it has to do with the circumference - but I'm not sure this translates into a scale.

For example, let's say a planet is 18,872 km in size, so it's a circumference of about 59258,08 km (diameter * PI).

Can anyone provide pointers in the right direction?

# Answer
> 0 votes
That depends entirely on your projection and on what pixel you are talking about.

For example, with the Mercator projection (i.e., mapping the texture to a cylinder, which is a common way of UV mapping a sphere for this) the projection depends on the latitude you are sampling at.

It would simply be a case of finding the radius and multiplying it with 2\*pi to get the circumference of a circle at that latitude, and dividing it by the amount of pixels.

For example, earth has a radius of about 6.371 kilometers, for a circumference of 40030 kilometers. Giving 20 kilometers per pixel. However going towards the poles this quickly decreases (less kilometers for a given pixels, so more detail) causing the distortion we're all familiar with when looking at a regular map.

# Answer
> 0 votes
It obviously depends on how you wrap the texture around the planet, but let's assume that those 2048 pixels precisely cover the entire equator of your planet.

Indeed the circumference equals (pi\* diameter). Divide that circumference by the amount of pixels (2048) and you have the length of your pixel. in this case:

18,872\*Pi = 59288km

59288/2048 = 28.95km/px

Note however, that this only applies to the equator. Assuming you're simply wrapping the texture around the equator, the width of the pixel will get smaller the closer you get to the pole. That's because the circumference you should be using in the calculation is no longer the equator, but the slice of the sphere you're measuring.

---
Tags: maps, pixel, scale
---


title: How to schedule 'events' inside a game?

text:
# Question
Title: How to schedule 'events' inside a game?
Within a game I want to schedule 'events', like a resource is running out, some storage is full, or a person is born. I see two ways of achieving this:

1. Check on all the parameters every fixed time interval. At that given time, the number of persons are adjusted, the resources are calculated...
2. Calculate the time at which something happens and use a database to store all these events. Create a 'scheduler' which sleeps until the first event happens, and do something. However, if one piece of data changes, all the other items also changes and need to be recalculated.

Is there a general approach how to solve this problem in game design? I hope my question is somewhat clear...

# Answer
> 1 votes
Most games go with #1 and a variant on #2

For timed events they use a priority queue to keep the events and in the game loop check for events to occur at this time step.

This means that an event gets a trigger time in the future with which it gets inserted into the queue.

In the game loop you extract only those events which trigger time are now and leave the rest for a future iteration.

For triggered events, as in triggered by another event depending on some condition like a harvester emptying the last resource from a field, then the event is run as the other event triggers it. For example to remove itself as a target for harvest.

```
void HandleHarvest(HarvestEvent e){
    resources -= e.harvestAmount;
    if(resources == 0) Game.triggerEvent(new EmptyFieldEvent(this));
}

```

Instead of running immediately these could also be set as a delayed event with a 1 tick timeout to avoid infinite recursion caused by events triggering each other freezing the game.

Note that neither of these solutions use sleeps or multiple threads.

# Answer
> 0 votes
Option #1 is a very reasonable method with making games. Making a variable which can hold a very big number and incrementing it every frame is an easy way to make multiple timers which can be reset when needed without messing up the flow of the game. I personally don't see the need of checking the parameters every other few frames (unless it's intense collision detection) because this easily creates bugs. While it can sometimes be annoying to pour through tons of if statements, if you lay everything out in an orderly manner, it's quite effective. This is my preferred approach.

As for option #2... I think this is more of an option for programming teams. While it makes the code neat and somewhat easy to understand, mess up in the data management in one place or with one sequence of events and the game wrecks itself completely and the user has to lose their current progress, reset the game, or uninstall and reinstall depending on the structure and how many disaster possibilities there are. This is just with my own experience - I've completely messed up the structure, gotten confused, and ditched my entire programs by doing this.

Obviously, both methods have upsides and downsides but both methods can work. Depending on your skills in certain areas like lists, other data structures, and/or creating flow control, you may find that one way is way easier than the next. There's also nothing wrong with combining these methods. You may find that most of the game can be done with if statements, but you'll need more event lists for maybe a continuously changing game arena. Although often you will want to lean towards your skills, it really just depends on what you're programming.

---
Tags: game-design
---


# Question
Title: My Sprite is disappearing when it collides with my floor (libGDX)
I am just starting to build the game "engine" and I am using a sprite drawn in the same position as a rectangle and the two always move together. I have another rectangle which is the floor when the two collide the sprite/rectangle will stay on top of the "floor" rectangle for a small while then it will disappear. I assume it is falling through it as when I hold the key to move the sprite up again it re-appears.

The class I am using to represent my walls and floor is here:

```
public class Solids {
    Array<Rectangle> floors;
    Array<Rectangle> walls;

    public Solids(){
        floors = new Array<Rectangle>();
        walls = new Array<Rectangle>();

        floors.add(new Rectangle(0, 0, 1280, 10));
    }

    public Array<Rectangle> getFloors(){
        return floors;
    }

    public Array<Rectangle> getWalls(){
        return walls;
    }

}

```

I am representing my character in a class called entities which looks like this:

```
public class Entity {

    Rectangle bottom, left, right, top;
    Sprite sprite;
    Texture texture;
    Solids solids;
    int action;
    float velocity = 100;
    float width, height;
    float velocityY = 0;

    public Entity(Rectangle b, Texture t){
        solids = new Solids();
        bottom = b;
        texture = t;
        width = b.width;
        height = b.height;
        sprite = new Sprite(t, 0, 0, (int)width, (int)height);
        this.setPosition(0, 0);

    }

    public void setPosition(float x, float y){
        bottom.x = x;
        bottom.y = y;
        sprite.setPosition(x, y);
    }

    public void draw(SpriteBatch batch){
        sprite.draw(batch);
    }

    public void moveLeft(float delta){
        bottom.x -= velocity * delta;
        sprite.setPosition(bottom.x, bottom.y);;
    }

    public void moveRight(float delta){
        bottom.x += velocity * delta;
        sprite.setPosition(bottom.x, bottom.y);;
    }

    public void jump(){
        velocityY = 15;
    }

    public void update(float delta){
        velocityY -= 50 * delta;
        bottom.y += velocityY;
        sprite.setPosition(bottom.x, bottom.y);
    }

    /*public int hits(Rectangle r){
        if(bottom.overlaps(r)){
            return 1;
        }
        return -1;
    }

    public void action(int type, int y){
        if(type == 1){
            setPosition((int)bottom.x, y);
        }
    }*/

    public void isCollidedFloor(){
        /* need to know if collided with floor or wall for jumping need two arrays also need array of entities */
        for(int i = 0; i < solids.getFloors().size; i++){
            if(bottom.overlaps(solids.getFloors().get(i))){
                action(solids.getFloors().get(i));
            }
        }

    }

    public void action(Rectangle r){
            setPosition(bottom.x, r.y+1);
    }

}

```

The calls worth noting to this class from the main class are as follows:

```
    player = new Entity(new Rectangle(0.0f, 0.0f, 128f,128f), new Texture(Gdx.files.internal("woman.png")));
    player.setPosition(1280/2, 100);
player.update(Gdx.graphics.getDeltaTime());
player.isCollidedFloor();

```

So my question is, why is this happening, tried just creating one Rectangle outside of the solids class and it still doesn't work. I have been playing around for hours and just cant seem to figure it out. Thanks in advance.

# Answer
You need to set velocity to 0 after a collision. Otherwise the negative velocity will keep building up until you pass through the floor in a single update.

Change your action function to this:

```
    public void action(Rectangle r){
        setPosition(bottom.x, r.y+1);
        velocityY = 0;
}

```

For a more general solution, see the answer here: Tile based collision detection failing when player is going too fast
> 2 votes

---
Tags: opengl, java, libgdx, collision-detection
---


# Question
Title: Entity to tile collision detection (C++, SDL)
I'm currently trying to handle collisions between entities and a tilemap, but I've hit a problem. My tiles are stored simply as integer tile IDs in a multidimensional array, and I wanted to perform a quick collision check by working out which tile the player is on (or will be on if the new position is valid), by simply dividing the player's position by the tile size to get the x,y of the tile in question. After this, I'd perform a simple SDL\_Rect collision check between the tile's rect and the entity's.

The problem of course is that depending on which direction I'm moving in, I may want to add the entity's width/height to the x,y position of the entity when working out which tile I'm on, otherwise the collision would only apply to the top left corner of the entity. I tried to do this myself, but couldn't produce consistent results. I didn't think it would be difficult, but I'm obviously missing something.

In my situation, my entity sprites are 32x32, while tiles are 16x16. Is it possible that using tiles that are smaller than my entity is making it more of a problem than it might otherwise be?

Thanks in advance for any help you can offer in suggesting a working solution.

# Answer
Here's a small pseudocode example of something kinda similar to the system I'm using for my game. Basically the important trick here is to check both the topleft of your player, and the bottomright of your player, which is enough as your player is rectangular and of the fitting size. If the player character would be bigger than two tiles, you would have to check more tiles.

```
class Player
{
    Vector2 Position, Velocity, Acceleration;
    Vector2 PlayerSize;

    void Update(time)
    {
        // Calculate the new position for the player.
        Velocity = Velocity + (Acceleration * time);
        Vector2 newPosition = Position + (Velocity * time);

        // Check the dimensions separately.
        // Maybe even let the functions return a valid position?
        newPosition = CheckCollision(TVector2(0, newPosition.Y))
        newPosition = CheckCollision(TVector2(newPosition.X, 0))

        // Now we should be able to safely move to the new position.
        Position = newPosition;
    }

    Vector2 CheckCollision(position)
    {
        // Calculate the tile coordinates for the player.
        // We need to check both the player's min position (topleft),
        // and player's max position (bottomright).
        // I'm assuming that Vector2 / Vector2 performs component-wise division.
        Vector2 minPos = position / TileSize;
        Vector2 maxPos = (position + PlayerSize) / TileSize;

        // Get the tile values here.
        // This code assumes that '0' will indicate an empty tile.
        bool tileAtMin = TileMap[minPos.Y][minPos.X];
        bool tileAtMax = TileMap[maxPos.Y][maxPos.X];

        // Then we need to check if the player collides.
        if (tileAtMin OR tileAtMax)
        {
            // Insert your own collision resolving here,
            // as that is way out of the scope of this question.

            return Vector2() // Some fixed position.
        }

        return position;
    }
}

```

Sorry for the complicated (?) example, but that should outline clearly what the important trick here actually is. This might not be the most effecient way, but already the fact that the level "geometry" is laid out in a grid makes the code a lot faster and simpler, as you don't need to actually go to look for collisions, you can just check a couple of positions.
> 2 votes

---
Tags: collision-detection, sdl
---


# Question
Title: How do i make an object to be visible only on a particular layer?
Please refer the image below to understand.

I am working on 2D game. I have three elements: "background(layer 0), foreground(layer 1) and the object".

I have used sprite renderer to set background and foreground images. Object gets instantiated during runtime.

How do i make Part-A of the object invisible? I want to make object visible only on foreground. If the object is completely on the background, it should be completely invisible. if the object is completely on foreground, it should be completely visible. Part-A and Part-B are just for reference. It is one single object.

The goal to be achieved is the image below:

# Answer
via editor or via script change sorting order in the `SpriteRenderer` as follows:

foreground: 0
your object: 1
background: 2

Via script you access this property by doing:

```
GetComponent<SpriteRenderer>().sortingOrder

```
> 1 votes

---
Tags: unity, masking, layers
---


# Question
Title: Handling multiple input mapped to single in-game controls
I am trying to map multiple input types to single in-game controls using libGDX's `InputProcessor` and `ControllerListener` interfaces. Currently, I have created a single `InputType` interface which is inherited by the following enumerations:

* Keys
* MouseButtons
* Buttons (Gamepad)
* Axis (Gamepad)

The InputType interface declares a single method `getCode();` as all inheriting enumerations have their own codes.

I have created a `Keyboard` class which implements `InputProcessor` and a `Gamepad` class which implements `ControllerListener`. Both classes extend from a generic `InputHandler` class which stores a `Set<T extends InputType>`. I also created a Mouse class and `AxisHandler` class which work similarly, although as touch events are handled within the `InputProcessor` and axis events handled within the `ControllerListener`, the `Keyboard` and `Gamepad` classes contain instances of these classes respectively.

Finally, to map multiple input types to single controls, I created a `ControlMap` class which stores an `EnumMap<Controls, InputType[]>`, where `Controls` is an enumeration containing all controls that are present within the game (MOVE\_UP, MOVE\_DOWN, ATTACK, etc.)

The obvious problem with this is that I'm going from an event-driven approach to polling. Every time input is processed, I'm storing the associated `InputType` accordingly, and this can create an overhead after some time.

My game uses a component-based architecture, so in my MovementSystem I'd check whether controls are down by using `if (Controls.controlDown(Controls.MOVE_DOWN))`. I can't seem to find any other way of approaching this problem just yet. There is no apparent drop in performance; when input isn't being handled, nothing is stored. Is my method fine as it is and am I over thinking the problem too much?

My UML is terrible but here's how I can best describe the process:

# Answer
> 1 votes
If the library you use only has polling for input then you will have to use polling there are no secrets.

To solve the issue of polling in a component system you can create an input system which will only check the status of the input sources your input components have subscribed to.

This way your components are all updated at the same time (and they are free to process the changes or lack of) the way they want after the polling of all inputs have ended.

Then you can have Intent Components which can process the change events sent from the Input components and process the complex scenarios where multiple inputs change within a timeframe or in particular conditions have to be handled independently from the controller type or other constraints.

---
Tags: libgdx, input, component-based
---


# Question
Title: Frequent stuttering, high FPS spikes with VSync option turned on in Unity standalone build
I'm experiencing an issue using Unity 4.3.2 and standalone builds. If I turn on VSync in the project's Quality settings, running the game at the native monitor resolution, I'll frequently get high framerate spikes (over 100FPS), and a strong stutter for a few frames, and then it drops back down to 60FPS and runs normally. If I run the game at a lower resolution (800x600 for example), the framerate stays at around 500FPS and the stuttering is consistent.

However, if I turn off VSync in the Quality settings, and force it on in the Nvidia Control Panel, I don't experience any stuttering or framerate spikes, nor when I turn off VSync completely (but lots of screen tearing, which is very ugly and distracting).

Can anyone explain this behavior? Is there anything that can be done to circumvent it? I'd imagine other Unity developers have used the built in Unity VSync with success before (or maybe not?!) so I'm hoping I'm just doing something wrong on my end.

# Answer
> 1 votes
this is more of an unity problem (because when you forced Vsync in the nvidia it fixed it), i would go to unity's own answers site **Unity answers** for better support and even contact unity support if this is something important

---
Tags: unity, frame-rate, vsync
---


# Question
Title: How area-of-effect effects are projected into games world?
I see a lot of skills in the games I play where they have a skill or a search area that projects a drawing on to a map, like a circle or something similar and I have no idea how that is done, and I don't think they use a texture to draw it. For the projection, I think, they use some kind of ray-cast to find the shape of the map and then go from there but I may be far off from truth.

In the linked image example you can see the circle is projected on the flat surface and the stairs. (And how is that glow effect around the circle achieved or is that part of a texture?)

Can someone tell me how is that done or point me to the right direction?

# Answer
An option would be to render a cylinder. To fade it out, you could use the depth map of the scene, compare it to the current fragment's depth of the cylinder and fade out according to how far is the current depth from the scene depth.
Kind of like you would do with a soft particle renderer, but instead "softening" (fading out) the geometry when the two depths are close, fade it out when they become more far away.
Also, in your picture, it looks like the fade is non-linear.

An other approach for a simpler effect you could also use decals.
> 1 votes

# Answer
This effect can be achieved by layering two textures on top of one another. The map exists in 3D space and is drawn with its normal texture, then drawn again with the circular texture, potentially with some additional calculations to get the correct texture coordinates since the circle texture is larger than any of the polygons it's mapping to.

The glow can either be part of the texture or done dynamically in the shader.
> 0 votes

# Answer
in most games it would most likely be an particle system drawn in a circle/sphere around the player to get that effect, i'd doubt a game would use ray casting to achieve such an effect
> -2 votes

---
Tags: graphic-effects
---


# Question
Title: Most efficient way for nested loop to not repeat a value of parent loop in pair-wise structure (C# or Javascript)
It's hard to choose the correct title for this question, so let's see if I am able to better convey here what I am in search for. If the title is too far away, suggestions are welcome and I can edit it or put a new question.

So, what I am trying to do is the following. I have the following set of values: A=\[a1,a2....a100\]. Now, suppose I want to loop trough them to check something for each possible pair of these values but without repetition and avoiding to check a value against itself.

It means that we start with a1 and check it against a2, then a3, then a4, until checking it against a100. Next, we start with a2, but we do not check it against a1 because that was already checked. We go directly to check a2 against a3, then a4, until a100. Next, we start with a3 and check it directly agains a4, then a5, and so on. The idea is that there will be 100+99+98+97...+1 checks, instead of 100^2 checks.

A naïve way of doing that would be to use two loops, one nested in the other, both going trough all the values of A. However, after the main parent loop completes each iteration, it stores the current iterated value in a list. So, when the child nested loop starts it checks if its currently iterated value is already on that list - if it is, the nested loop breaks.

However, it is very likely that this is not a very efficient way of doing that, since one would have to create a list, add to the list every iteration of the first loop and search the list every iteration of the second loop. Considering that I will be dealing with enormous amount of values in A, not only 100, that is real concern.

So, what are the most efficient ways one can do that kind of pair-wise comparison without repetition? I can handle both C# and Javascript. Many thanks.

# Answer
> 1 votes
Something like this, perhaps?

```
private void CompareList(List<foo> listToCompare)
{
     for(int i = 0; i < listToCompare.Length - 1; i++)
     {
          var item1 = listToCompare[i];
          for(int j =i+1; j < listToCompare.Length; j++)
          {
              var item2 = listToCompare[j];

              DoWhateverComparison(item1, item2);
          }
     }
}

```

Might need to add some index/null checks, I haven't run the code.

---
Tags: c#, algorithm, game-loop, efficiency
---


title: What defines a AAA game?

text:
# Question
Title: What defines a AAA game?
I tried to find a precise definition. I found clues on Wikipedia and on Gaming SE, but I cannot find more than an approximation like:

> Equivalent of blockbuster movie in cinema, an AAA game is a game with highest development budgets and levels of promotion.

The definition seems imprecise. How can I be sure a game is AAA?

Let's imagine a small indie studio making games and growing up. They hire more and more people through the years and invest more and more money in their game. At which milestone would their game be considered as AAA?

# Answer
There really isn't a precise metric for being "AAA" or even a solid definition of the term. *Generally* it means the game in question had a large budget, which usually translates to having a large team and lots of promotional spending. But how large is large? Nobody can really agree (or has really bothered to try), just like nobody agrees on how many concurrent players you need to be a "massively" multiplayer game.

Most people would probably agree that games with budgets in the millions are "AAA," and games with budgets in the thousands aren't. But the middle? Is a hundred thousand dollars an AAA game? What about half-a-million?

If you want to call your game a AAA game, go for it. If you "pull it off" in the sense that your game manages to wow people enough that they don't disagree with that assessment, then I guess you're a AAA game (or similarly, just wait until people start calling your games AAA or calling your studio a AAA studio).
> 10 votes

# Answer
While there is no hard definition as to what makes a game 'AAA', it's safe to say you can call a game 'AAA' if it has top-class production values for the technology available in its time.
> 0 votes

---
Tags: marketing, terminology
---


title: Is database necessary?

text:
# Question
Title: Is database necessary?
Hi I have studied c# for good few months and I'm at intermediate level at the moment.
And few days ago I decided to make simple 2D Games like "Mr Jump" after studying Unity.
So my question is as follow :

1)Should I study database to make simple mobile games? and if so what would be good language to study?

2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge?

3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database?

4)Could tell me examples of database in games?

5)Should I study database as much as c#?

# Answer
> 1)Should I study database to make simple mobile games? and if so what would be good language to study?
>
> 2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge?

No. A game like Mr. Jump could easily be made without any database knowledge.

> 3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database?

There might be a database involved, but you don't need to know how to work with it directly. There are API calls for iOS, Android, and Windows Phone that will do all of the database work for you.

> 4)Could tell me examples of database in games?

An MMORPG like World of Warcraft would use a database to store all of its player data on the server.

> 5)Should I study database as much as c#?

Definitely not. Learning the language you're programming is far, far more important. I wouldn't bother studying databases at all until you hit a point in your development where you find a need for them.
> -1 votes

# Answer
Not really. There are *very, very* few games that require a full featured database engine.

A database engine is a very general piece of software, capable of storing nearly anything, reading and writing to it, and ensuring things like referential integrity.

A game does not care about that. It typically has 2 kinds of data; the first of which is game data which is not changed by the game.

It's the level, textures, models, sounds, (some) game logic, etc. This is quite often a case of "Load this data directly from memory and fix up some references, done" or "Parse this fixed format text file and bail on an error". A database engine is way overpowered for that and slow (not to mention large in size due to being generic).

The other type is player save game data, this is usually also a custom format and does need to be written to by the game engine, a more likely target for something small like PostgreSQL but still not exactly common in my experience.

That is not to say that they *can't* be useful, they're probably the best target for things like storing *online* achievements and statistics; however that's not really part of the game, that's hidden behind a web service somewhere.
> 1 votes

# Answer
I would highly recommend learning the basics of databases and how they work if you are going to follow a career in the game industry. Data is essential to most games today and understanding how the data works, is queried and put together is certainly useful.

Many game developers nowadays though are using BaaS (Backend as a Service) offerings such as GameSparks, which provide you with a database in the cloud for your game to connect to, instead of storing data on the device. There are many benefits to this, namely...

1.) If a player's device is lost, they can install the game on a new device, authenticate, and be back in the game where they left off

2.) Having the game data and configuration data on a server allows the developer to configure game settings/difficulty etc easily without having to push game updates to the clients. The client would simply open the game and download the updated config/settings data.
> 1 votes

# Answer
Databases are designed to handle vast amounts of data. There are many types, with different ideas behind them; but in general they are for A LOT of data. Because of this, databases do require at least some complicated set up and a fair amount of knowledge.

However, they are not what you need right now. If you are saving the data of just one player locally, there is no need for a database. There are plenty of other solutions out there that will work fine and not require extensive set up. Here is a good tutorial for Unity: https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/persistence-data-saving-loading
> 0 votes

---
Tags: unity, c#, 2d
---


# Question
Title: Mapping simulated onto real with a Kinect and projector
I have this partially working already, but my implementation doesn't animate very well (lots of jitter, some random movements) and I thought that you guys in Game Development might be able to point me in the right direction.

1. I have a "Listener" application that listens to updates from the Kinect, finds the object in the frame, and sends an update of that objects location. (I just care about x/y in my case, not the z axis)
2. In a separate "Projector" program I listen for that update, and update the actual position of the object in my model.
3. In the "Projector" program there is also a rendering thread, triggered once per screen update, that attempts to move the projected object smoothly along the path of the real object using that model. (trying to project the image on top of the real object)

The problem I need to solve is: *How do I track the object's real location with my projected object in a way that animates smoothly?*

The kinect updates the location at 30 FPS, the render cycle happens at 60 FPS (on a ui thread), but I'm trying to project on top of my object as best I can while keeping the rendered image moving smoothly. (right now it tracks with the object but jitters quite a lot) I came across http://gafferongames.com/game-physics/integration-basics/ on the RK4 algorthim, which is probably more complex than I need but I wasn't able to implement it correctly for my case. (likely because I don't fully understand it)

# Answer
> 0 votes
I wanted to post what I have so far in case anyone else comes across this question, apparently: ***It is very important that all calculations are based on the same time step!*** In my case I have two separate threads:

1. Process data from the kinect
2. Render stuff on the screen

I did not have these two separate threads synchronized very well, which turned out to be a lot of the reason for my jitter. I fixed this by creating a central timer, picking an arbitrary heartbeat (33 milliseconds), and calculating everything based on where it fell in relation to that slice of time. For example if I got a Kinect message at 40 milliseconds, I'd back-calculate the location to where it would have been at the 33 millisecond mark, 7 milliseconds ago. In my render cycle I then calculate how long it's been since the last heartbeat to determine current render location.

And no, I haven't figured out the best way to project kinect movement into the future, I'm just using the previous \[velocity\] x \[time\] right now, sorry. I may look into how you calculate the overall trend in velocity to get a more accurate prediction.

---
Tags: kinect, rk4
---


# Question
Title: Where can I find/download a decent, free voice synthesizer?
I've been looking all over the net, and I've found *some* voice synthesizers, but they either don't work, aren't free, or just have 5 or so voices to choose from... I need to get a synthesizer with which I'm able to **edit** the voice myself. This is needed for GLaDOS-like robotic character for my game.

I did some searching here on GDSE, and it seems that questions like this often get closed as "not constructive". I believe that this is not the case, as this could help many other people who happen to be searching for the same thing.

# Answer
Since you're looking for a non-realistic voice check this out, if Java doesn't frighten you then there is: http://freetts.sourceforge.net/docs/index.php

If it doesn't help then going further back Amiga had a TTS engine built into it that may be available somewhere.

Search terms for further investigation would be "text to speech" or "speech synthesis," anything with "voice" in it tends to go off track.
> 4 votes

# Answer
I know this isn't a direct answer to your question, but I'd like to drop in that GLaDOS's voice isn't synthesized though - it was recorded by an actual voice actress and *post-processed*. That's certainly another possibility to consider.

And just because I thought it was interesting, here's a video that shows how it's possible to create something that sounds very much like GLaDOS in the games, by taking an unprocessed sound clip recorded by the aforementioned actress, and processing it in a voice manipulation tool such as Melodyne. Most of the changes were removing pitch modulations between words, changing the pitch here and there, and messing with the formant of the sound.

I think the original sound clip could even have been recorded with no pitch variation between words, with pitch changes then being added in the application. Melodyne is not free though but there is a 30 day trial you can try. And there might be a free alternative out there, although I'm unaware.

Another alternative to editing the voice like this, is to use software that applies the changes as a whole to your sound clip, and automatically makes it sound like a robot. I'm thinking for instance about using some sort of Vocoder VST, which you should be able to find by googling a bit.
> 6 votes

# Answer
If you're ok with a singsong quality, UTAU. It's decent for a free synthesizer. Also Sinsy. For UTAU, countless tutorials for use are on the web, however it is Japanese and has an English patch, and MANY voicebanks( librarys of samples of recorded voices for concatantive synthesis) Sinsy is on the web, but requires music XML files, which you can make with free software like Musescore. It's not easy though- hence the free part. CeVio is another one, a singthesizer that also has a speechsizer but it's only in Japanese and currently has no released voices in any other language!

As for Stephen Hawking, he could change his voice at any time for better options, but it is part of his idenity now, and at the time he got it- it was the best available. There is better out there though.
> 1 votes

---
Tags: assets, asset-management, voice
---


# Question
Title: libGDX : Paint And Remove Color From Actor with touchDragged
I created two-dimensional array of `Button` actor, then I added `new ClickListener() {
touchDragged }` as the following code:

```
buttons = new Button[3][3];

for (int row = 0; row < buttons.length; row++) {
    for (int col = 0; col < buttons[0].length; col++) {

buttons[row][col] = new Button(drawable);

buttons[row][col].addListener(new ClickListener() {

                @Override
                public void touchDragged(InputEvent event, float x, float y, int pointer) {
                    for (int row = 0; row < buttons.length; row++) {
                        for (int col = 0; col < buttons[0].length; col++) {
                            if (buttons[row][col].isOver()) {
                                buttons[row][col].setColor(Color.GREEN);
                            }
                        }
                    }
                }
   }
}

```

the code inside `touchDragged` method if the buttons `isOver` the buttons colored `GREEN` (it works fine) as shown in image

Now, How can I remove `Color.GREEN` i.e. (`Color.WHITE`) from buttons in the same calling `touchDragged` method, I mean undo `GREEN` to `WHITE` ??

this image clear my question :

like Alphapetty Game from king company, if you know it :).

Sorry, For bad English

# Answer
1- Create `List` :

```
private List<Integer> list;

// In create OR show Method
list = new ArrayList<Integer>();

```

2- Create this line code (as ID for `buttons[row][col]`):

```
buttons[row][col].setName("" + id++);

```

3- Write this code inside your `touchDragged` .. after your loop:

```
if (buttons[row][col].isOver()) {
    try {
        if (list.contains(Integer.parseInt(buttons[row][col].getName()))) {
            if(Integer.parseInt(buttons[row][col].getName()) == list.get(list.size() - 2)) {
                stage.getRoot().findActor("" + list.get(list.size() - 1)).setColor(Color.WHITE);
                list.remove(list.size() - 1);
            }
        } else {
            buttons[row][col].setColor(Color.GREEN);
            list.add(Integer.parseInt(buttons[row][col].getName()));
        }
      } catch (Exception e) {
           System.out.println(e.getClass());
      }
}

```

4- See the answer in this video
> 0 votes

---
Tags: libgdx
---


# Question
Title: Spawning Object 1 Within Object 2's Collision Box [Gamemaker]
I was wondering if any of you could help me with a specific Gamemaker question. Am using Gamemaker Studio.

I have an object (oSpecialSolid) which rotates and moves across my level. At random intervals, another object (oEmitter, an animated spark or flash of smoke) spawns *somewhere* within the x and y of oSpecialSolid, give or take 45px.

Unfortunately, oSpecialSolid has some transparent areas (the sprite is not perfectly rectangular, and has empty space at either side) where I would not like the oEmitter to spawn. However, as the object spins, I cannot tell if the x and y values that I am telling it to spawn in will be transparent or not in that moment. I would also like the oEmitter to spawn anywhere on the oSpecialSolid object,not just in a 45 x 45px box in its centre.

What I am looking for is **a method of telling oEmitter to only spawn within the collision box of oSpecialSolid**. Is there a way to do this? I am using the precise settings for collision.

# Answer
> 0 votes
Firstly, you need find bounds of your object

```
// top left point
var a = point_direction(0, 0, -sprite_xoffset, -sprite_yoffset) + image_angle;
var d = point_distance(0, 0, -sprite_xoffset, -sprite_yoffset);
var px1 = lengthdir_x(d, a);
var py1 = lengthdir_y(d, a);

// top right point
a = point_direction(0, 0, sprite_width - sprite_xoffset - 1, -sprite_yoffset) + image_angle;
d = point_distance(0, 0, sprite_width - sprite_xoffset - 1, -sprite_yoffset);
var px2 = lengthdir_x(d, a);
var py2 = lengthdir_y(d, a);

// bottom right point
a = point_direction(0, 0, sprite_width - sprite_xoffset - 1, sprite_height - sprite_yoffset - 1) + image_angle;
d = point_distance(0, 0, sprite_width - sprite_xoffset - 1, sprite_height - sprite_yoffset - 1);
var px3 = lengthdir_x(d, a);
var py3 = lengthdir_y(d, a);

// bottom left point
a = point_direction(0, 0, -sprite_xoffset, sprite_height - sprite_yoffset - 1) + image_angle;
d = point_distance(0, 0, -sprite_xoffset, sprite_height - sprite_yoffset - 1);
var px4 = lengthdir_x(d, a);
var py4 = lengthdir_y(d, a);

// calulate bounds
var left = x + min(px1, px2, px3, px4);
var top = y + min(py1, py2, py3, py4);
var right = x + max(px1, px2, px3, px4);
var bottom = y + max(py1, py2, py3, py4);

```

Now you can take any random position in this area

```
var posx = irandom_range(left, right);
var posy = irandom_range(top, bottom);

```

and check precise collision with spawn object using `position_meeting()`

```
if position_meeting(posx, posy, obj_spawn)
{
    // The point have collsion with a sprite. Spawn
}

```

and you need using loop here, like

```
repeat 100
{
    var posx = irandom_range(left, right);
    var posy = irandom_range(top, bottom);

    if position_meeting(posx, posy, obj_spawn)
    {
        // The point have collsion with a sprite. Spawn
        break;
    }
}

```

---
Tags: collision-detection, game-maker, spawning
---


# Question
Title: How will Unity games work on Chrome now that NPAPI is disabled?
As expected, this September Google disabled NPAPI in Chrome, which Unity Web Player relies on. As far as I know, Chrome now has its own API plugin API.

Will the Web Player returning to Chrome without NPAPI?

If not, what is Unity's future on Chrome?

# Answer
> 4 votes
Unity detailed their plans in this blog post. Unity plans to target the WebGL platform, and recommends that new web games start with Unity 5 WebGL as the default target.

The Web Player will remain supported "as long as it's useful for developers", as NPAPI still works in other major browsers.

---
Tags: unity, plugin, chrome
---


# Question
Title: How can I obtain a window handle in SDL 2.0.3?
I need to obtain the handle of the window for SDL 2.0.3. I got the suggestion to use `info.window` after initializing SDL and filling the info variable with data by calling `SDL_GetWindowWMInfo();` included in the header file `SDL_syswm.h`. My compiler (Visual Studio 2008) gives the following error:

> 226) : error C2039: 'window' : is not a member of 'SDL\_SysWMinfo' 1\> include\sdl\_syswm.h(173) : see declaration of 'SDL\_SysWMinfo'

# Answer
Getting the window handle from an SDL window is pretty straightforward:

```
SDL_SysWMinfo systemInfo;
SDL_VERSION(&systemInfo.version);
SDL_GetWindowWMInfo(window, &systemInfo);

HWND handle = systemInfo.info.win.window;

```
> 7 votes

---
Tags: sdl2
---


title: When are games legal to mod?

text:
# Question
Title: When are games legal to mod?
I'm just curious when and what games are legal to mod and what are the processes I must follow to keep the mod project from becoming illegal. To be specific i'm trying to do a side project while in college. The idea is to make a completely modded version of Pokemon red/blue. The main idea of the project is to see how faithfully we can recreate the game in a modern language (like java, C++, or C#) since the games were originally written in Assembly(I think). It would have the same battle system but updated graphics and potential bugs worked out.

# Answer
> 1 votes
In the context of trying to re-create one of Nintendo's older games, Nintendo won't allow it. For example, a fan-made Super Mario 64 remake received a DMCA copyright infringement complaint from Nintendo, even though it was made as a tech demo for remaking a Nintendo game in Unity. It sounds like your intentions are to do something similar for Pokemon.

More information can be found in this polygon article.

# Answer
> 0 votes
I am not a lawyer, and you should consult one for legal advice, particularly given that you intend to be doing something with Nintendo's intellectual property (they are particularly litigious).

That said, modding a game is generally legal if:

* the TOS of the game in question allows it (or perhaps, in some jurisdictions, does not explicitly forbid it; see the next point)
* you are granted the legal right to modify the software you own a license for by some other law in your jurisdiction, independent of what the TOS says (and/or in a fashion that the TOS is not legally allowed to override)
* your modification does not otherwise break any other, broader laws -- such as copyright infringement.

"Recreating the game in a modern language," doesn't sound like a *modification* to me. It sounds like it's own project, using (probably illegally) somebody else's intellectual property. This seems like a bad idea.

---
Tags: game-design, legal, modding, copyright, nintendo
---


title: "Painting" elements in html5 canvas

text:
# Question
Title: "Painting" elements in html5 canvas
I'm making a game in coffeescript (although for the sake of this problem that's probably not all that relevant) and html5's canvas. It's a game that involves a paint cannon, that fires circular particles of paint that can paint elements of the level and the player. The problem is I'm not sure how to accomplish the painting. The diagram below illustrates what I'm trying to accomplish:

Using canvas, the particles are drawn using `context.arc()`, the players using `drawRect.arc()` and the floor can be an arbitrary polygon with drawing code as follows:

```
    @drawingContext.beginPath();

    tV = b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, @vertices[0]))
    @drawingContext.moveTo(tV.x, tV.y)
    for i in [1..@vertices.length - 1]
        v = b2Math.AddVV(pos, b2Math.MulMV(body.GetTransform().R, @vertices[i]))

        @drawingContext.lineTo(v.x, v.y)
    @drawingContext.lineTo(tV.x, tV.y)

    @drawingContext.closePath()
    @drawingContext.stroke()
    @drawingContext.fill()

```

It would be too intensive to keep track of all the circles that should be painted on to objects and would soon bog down, with potentially 60 clipped circles per second being added to be drawn on top of objects.

The original thought was to stack two canvases on top of each other, so then we could draw the levels once and then when ever necessary just draw the paint splat over them once and forget about it (changing the composition mode to source-atop to get appropriate clipping), and since we're not redrawing it would stay there. However, this won't work on moving objects (like players) (that can also rotate and change size relative to the camera). I'm not sure how to do it, since all objects are made up of solid colour to start with there's no texture data or anything we can modify.

# Answer
> 1 votes
Your best bet would probably be to use images, with several variations with paint on them. E.g. have one image with paint on the left, one with paint on the right, one with more paint on the right, one with more paint on the left, you get the idea. When something get's hit with paint just change the image to one of those. When it get's hit again change it to one with more paint splats, and so on, until it's covered with paint.

If you wanted something a bit more robust you could manipulate the actually pixels of the image and change it to have a circle on it when it's hit. This would be harder however. Google 'canvas getImageData' for more on this.

Hope this helps and best of luck on your game!

# Answer
> 0 votes
I realize that this question already has an accepted answer, but I wanted to point this out.

If you don't need to redraw the rectangles at each frame, then you can just paint over them and not redraw them. That way, if something moves over the rectangle and is drawn, then it will still be there if the rectangle isn't drawn again.

You could also make something like this: if a circle is colliding with a rectangle, add the current circle to a rectange's array of circles that have collided with it, and redraw only the portion that each circle overlaps with the rectangle

---
Tags: javascript, html5, html-canvas, coffeescript
---


# Question
Title: How to implement a mechanism to select language specific expression (python)?
On a game server, programmed in python, I want to be able to select language specific expression, according to the user's preference. Provided a 'name tag' and a 'language identifier' I want a function to return the appropriate text for the specified tag in the given language, for example

```
> print(foo("turn left","de"))
Bitte nach links abbiegen
> print(foo("turn left","en"))
Turn left please

```

I hope you get the point.

Is there something available for python which can provide a solution? I am **not** looking for `gettext` or something which uses the computer's locale setting for the language! I am looking for a solution which might work similar, but works as given in the example.

Or is it better to code something like this by oneself? How then to store the language phrases in a best way? Just in a big text file? A data base? ...?

# Answer
> 5 votes
I would create a directory containing language text files. The directory could look like this:

en.txt

```
0 "Start game"
1 "Load game"
2 "Enable cannons"
3 "Join server"
4 "Kill the enemy"

```

fr.txt

```
 0 "Démarrer le jeu"
 1 "Load game"
 2 "Activer canons"
 3 "Rejoignez serveur"
 4 "Tuer l'ennemi"

```

de.txt

```
 0 "Spiel starten"
 1 "Spiel laden"
 2 "Enable Kanonen"
 3 "Join-Server"
 4 "Töte den Feind"

```

ch.txt

```
0 "開始遊戲"
1 "載入遊戲"
2 "啟用炮"
3 "加入服務器"
4 "殺死敵人"

```

Now make hashmap, with the language names as keys, and a String array as object. In each string array you load up the values and they are now ready to use.

A method to get the values. (Pseudo code)

```
public String getText(String languageCode, int messageId) {
    return languages.get(languageCode).get(messageId);
}

```

Initialization method (Pseudo code)

```
HashMap<String, HashMap<Integer, String>> languages;

public init(String directory) {
    for(file; each file in directory) {
        HashMap<Integer, String> languageArray = load file contents and add to array;
        languages.get(languageCode).add(languageArray);
}

```

This can of course both be implemented on the client side(for less bandwidth) or server side for more customize ability.

# Answer
> 0 votes
Here is a JSON-based solution, with the same concept exposed by Kaarez

languages.json

```
{
 "fr" : {
   "turn left" : "tournez à gauche s'il vous plaît"
 },
 "en" : {
   "turn left" : "turn left please"
 }
}

```

And then, using the `json` module:

```
import json

with open('languages.json') as fd:
    lang = json.load(fd)

print(lang["fr"]["turn left"])

```

However, note that a JSON file could be bigger than a txt file.

---
Tags: python, localization
---


# Question
Title: Given a 3d goal point and a turn rate in radius, find max speed to reach goal
I'm working on a 3d space sim with AI agents flying ships through space. I am trying to get them to follow a waypoint path nicely, which involves figuring out how fast they can be travelling and still manage to pass through the waypoint.

Given a point in 3d space and an an agent that only travels forwards and has a given turning rate in radians / second and an acceleration rate, how can I find the maximum speed the ai can travel and still manage to face the point before overshooting it?

Can any math wizards lend a hand?

```
public class AIPilot { //relevant fields from my class
   float turnRate_radians;
   float acceleration;
   Transform transform;

  public float FindMaxSpeedToFace(Vector3 goal) {
    //trying to fill the body of this method
  }
}

```

# Answer
> 1 votes
Is it critical that your function be "What is the max speed"? Finding a closed-form calculation for that is a bit hairy.

It seems like a more useful/general-purpose function might be "Can I keep accelerating and still face the target point?"

You already know from your previous answer from zehelvion how to calculate whether you can reach a target given a your current velocity and max turn speed.

So, assuming each time step you are turning towards the target as fast as you can, then you can also calculate whether additional acceleration will make it impossible to face the target. If not, go ahead and accelerate.

The max speed you arrive at is your original answer, but now you maybe don't need it. :)

(I.e., using this approach your AI agent should arrive at the point as fast as possible given its physical constraints.)

---
Tags: unity, c#, rotation, ai, path-finding
---


# Question
Title: Limiting x and y movement so you can't go off camera
So I want to make an on rails shooter like that of Star-Fox in the Unity engine. What I would like to do is limit the ship from moving off the screen. You move along the X and Y axis so i wont have to keep these invisible colliders in their place but I cant get another way to work.

and I know I have to find a way to convert camera space to world space I just can't find a way how.

This is my current controller and I commented a few failed attempts.

also I'm using a perspective camera and I'd like to keep the rigibody movement if possible.

```
public float turnSpeed = 10;//Horizontal

//private Vector3 moveDirection = Vector3.zero;

public Rigidbody rb;
void Start()
{
    rb = GetComponent<Rigidbody>();
}
void Update()
{//Screen.width
    //transform.position = new Vector3(Mathf.Clamp(transform.position.x, -holdMyRatio, holdMyRatio),
   //                                  Mathf.Clamp(transform.position.y, -holdMyRatio, holdMyRatio), 0);
    //CharacterController controller = GetComponent<CharacterController>();
    rb.AddRelativeForce(Vector3.right * turnSpeed * Input.GetAxis("Horizontal"));
    rb.AddRelativeForce(Vector3.up * turnSpeed * Input.GetAxis("Vertical"));
  //  moveDirection.x = Input.GetAxis("Mouse X") * turnSpeed;// * Time.smoothDeltaTime;
   // moveDirection.y = Input.GetAxis("Mouse Y") * turnSpeed;// * Time.smoothDeltaTime;
  //  controller.Move(moveDirection * Time.smoothDeltaTime);
}

```

# Answer
> 1 votes
http://answers.unity3d.com/questions/799656/how-to-keep-an-object-within-the-camera-view.html

```
Vector3 pos = Camera.main.WorldToViewportPoint (ship.transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
ship.transform.position = Camera.main.ViewportToWorldPoint(pos);

```

As the answerer noted in that question, Viewport space has the origin (0,0) in the lower-left-hand corner, with the upper-right-hand being (1,1).

This will clamp the movement; i.e. it will feel like an invisible wall around the edges of the screen.

Just make sure this code happens after any physics movement adjustments, and you should be able to keep your rigidbody stuff. If you encounter jitter, consider changing the code to something like this:

```
Vector3 pos = Camera.main.WorldToViewportPoint (ship.transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);

Vector3 speed = ship.rb.velocity;
if(pos.x == 0 || pos.x == 1)
    speed.x = 0;
if(pos.y == 0 || pos.y == 1)
    speed.y = 0;

ship.transform.position = Camera.main.ViewportToWorldPoint(pos);
ship.rb.velocity = speed;

```

---
Tags: unity, camera, rigidbody
---


# Question
Title: How should a circuit or power system (like redstone in Minecraft) be implemented
I want to implement a power-system like the redstone system in minecraft.

I have n power sources and m cables. If I disconnect the power source or a cable the circuit should turn off.

How do I avoid circles? If each cable with the status "on" powers the nearby cables I can create infinite circles where there is no power source involved (see image). Plus site is that it runs in T=m

I could send power burst through the graph starting at every power source and in each update call I turn every cable off. Problem is it runs in T=n\*m.

Is there a best practice? In Minecraft the redstone system was very slow so I think I overlooked something.

EDIT: The system should work without a distance based decay.

# Answer
> 7 votes
Recursive propagation. For example, you have a lamp connected by N cable objects to a battery. The lamp asks the Nth cable if it's powered (this is the cable attached directly to the lamp). The Nth cable then asks the N-1 cable if it's powered and so on. Each time an object is asked if it's powered or not, it sets a `lastEvaluated` variable to the current frame time. The recursion bottoms out on an end node, like a battery, or when it reaches an object that's already been evaluated that frame (this avoids infinite recursion). These propagations only occur when the system changes. Changes include adding/removing parts or switches being toggled.

There is no distance decay or similar restraints with this system. I used it to create a logic gate simulator and it works for various logic examples like a flip-flop.

# Answer
> 2 votes
In minecraft there is a distance based decay with a very short decay distance (16 blocks range).

What you need it a connectivity test between graphs.

One way to do it would be repeatedly take each edge and combine the connected nodes and into a single node. After all edges are gone you will end up with a node for each network. Then sending power is trivial.

# Answer
> 1 votes
A powered block has several input/output connections, but at a starting point, we do not know whenever it is input or output.

Each block has a "Voltage" which is the energy that arrive to it minus the lost/used.

A powered block will provide power to all surrounding blocks, and each block take as input the higher voltage from surrounding blocks. You could also complicate the system by defining an Intensity, but I will stay with Voltage only for simplicity.

Every time a change is performed to the circuit, by adding/removing blocks, or by the circuit itself, the change need to be propagate to all the circuit until stability.

I would suggest you to design an interface for any powered object (cube in MC):

```
class PowerInterface
{
protected:
    std::vector<shared_ptr<PowerInterface>> sibling;

    double energy=0;
    bool   isActive = false;

    virtual void propagate(double inEnergy) = 0;

    virtual void addSibling(shared_ptr<PowerInterface> newSibling) = 0;
    virtual void removeSibling( shared_ptr<PowerInterface> remSibling) =0;
};

```

So supposing you implement the addSibling and removeSibling, the most important part is the propagate function:

```
void PoweredCube::propagate( double inEnergy )
{
    // Define the behaviour
    energy = inEnergy-1.0; // Normal device
    energy = inEnergy-0.1; // Normal cable
    energy = 10.0;         // Normal source of power.

    if (energy<0.0)
    {
        energy = 0.0;
        isActive = false;
        // No energy, so do not propagate anymore
        return;
    }
    isActive = true;

    // Propagate
    for (auto &s: sibling)
    {
        // Only propagate to sibling with less energy.
        if (energy > s->energy) s->propagate( energy);
    }
}

```

As a recursive solution, each block should reduce a bit the energy, never increase it. The source of power can set a fixed value, but never increase based on inputs. That should not be an issue as all "real" system work in this way.

---
Tags: algorithm, graphs
---


# Question
Title: How to fire a touch event only for the touched sprite?
I have a set of sprites, each one implementing `InputProcessor`, and registered to an `InputMultiplexer`, when a sprite is touched, everyone fires the `touchDown` event.

Ok, so I can get the touch coordinates, unproject, and compare with the sprite bounds to know if it was touched, but it wasn't what I had in mind when I implemented InputProcessor into my sprites, I thought only the touched one would fire.

Don't even know if it is a problem, I'm planning to have about 80 sprites reacting to touch. Is this the best solution?

Is there a way to fire an event only for the touched sprite?

I'm not using scene2d or actors.

# Answer
> Ok, so I can get the touch coordinates, unproject, and compare with the sprite bounds to know if it was touched

This is how I would proceed, especially for only 80 sprites. How is the InputProcessor to know to fire only when certain geometry is touched? There's no concept of geometry for an InputProcessor. I recently implemented a similar model with 10,000 sprites - each with their own InputProcessor (a GestureDetector, actually). While this worked just fine on PC, Android had significant (perhaps 1 second) lag between touch and full render.

The other way this is commonly done is to have just one input processor, and 'find' the sprite under the touched area in that context (perhaps by drawing a ray from the camera's plane at the x,y of the touch event, and using an Intersector to find the intersecting object).
> 5 votes

# Answer
When your actor get touched it fires a method `touchDown`/`touchUp` in the listener class, where it supplies an Event object which you can use to get the listening actor and you can use it to compare with other actors

```
Actor actor 1, actor2;

actor1 = new actor () ;

actor2=new actor () ;

actor1.addinputListener(new yourInputListener())

actor2.addinputListener(new yourInputListener())

```

In your input listener class

```
touchDown(Event event,........) {

  if(event.getListenerActor().equals(actor1){

    //do something
  }
}

```
> -1 votes

---
Tags: libgdx
---


# Question
Title: How to iterate through the frames of an AnimationClip in editor mode
I'm working on a 2D game, using spritesheets as the basis for four `AnimationClip`s. (Every frame from the spritesheet is a keyframe in the animation.) I'm trying to step through the frames of these `AnimationClip`s and programmatically create `Collider2D`s which fit the dimensions of each frame.

The problem is, I'm having an impossible time actually iterating through the frames. My character has an `Animator` component, with 4 different states. I've tried various inputs to my editor script, but the closest I've gotten has an `AnimationClip` as input:

```
private AnimationClip clip; // set in inspector
private GameObject targetForColliders; // set in inspector

void createColliders() {
    Animation animation = new Animation();
    AnimationUtility.SetAnimationClips(animation, new AnimationClip[] { clip });

    foreach (AnimationState state in animation) {
        // do useful things here
    }
}

```

Unfortunately, somehow the `animation` local variable is null, crazy as that sounds. I've confirmed that by both logging it and attempting to use it, which causes a `NullReferenceException` every time.

I can't access the `Sprite` containing the spritesheet directly, because I've made manual adjustments within Unity to the keyframes (removing some, duplicating others) and I don't want to have to manually sync my colliders with the modified assets.

Has anyone attempted to do something similar to this before? **tl;dr: What's the easiest way to iterate through the frames of a 2D animation in an editor script?**

# Answer
If you want more control over when the sprite frame changes, you should just use a script to change the object sprite instead of using an animation. Then you would have an array of Sprites and an array of corresponding Collider2Ds set via serialization. The script could flip through the frames however you see fit.
> 1 votes

# Answer
You don't need to add collider to each frame. You add the collider to your character.This video should clarify using sprites for animation. It is one hour, 19 minute session dealing with 2D character control and animating the character for idle,run and jump actions.
> 0 votes

# Answer
You don't need to create different collider 2D for each frame , it might be performance heavy. Add a new property to the animation clip i.e. "Box Collider 2D - Offset" and "Box Collider 2D - Size" , now your animation clip will be having three properties one sprite and other offset and size. Now change the size of the collider and offset for key frames in the animation where it is needed to fit the bounds of the sprite.
> 0 votes

---
Tags: unity
---


# Question
Title: Why has my refractive water shader become reflective
So I was making a water shader in unity and well it looked fine in the scene view but as soon as I went into the game view the refraction texture basically flipped up 180 degrees and made it look like the water was reflective. The problem with this is that it breaks the transparency of the shader.

---

Scene View (how it should look):

Game View (how it does look):

Shader: (I can't post more than 2 images)

Part of the shader:

```
float4 Lerp2=lerp(Tex2D2,float4( 0.0, 0.0, 0.0, 0.0 ),_Refraction.xxxx);
float4 Subtract0=Lerp2 - _RefractionCorrection.xxxx;
float4 Add2=((IN.screenPos.xy/IN.screenPos.w).xyxy) + Subtract0;
float4 Tex2D0=tex2D(_GrabTexture,Add2.xy);

```

# Answer
Have you tried flipping it back in the shader?

```
float4 Tex2D0=tex2D(_GrabTexture, float2(Add2.x, 1.0-Add2.y));

```
> 3 votes

# Answer
This is a shot in the dark. Check the scene output for different rendering path options for the main camera. My distortion shader acted weird for deferred rendering, got no clue why. It got fixed for forward rendering path.
> 0 votes

---
Tags: unity, shaders, water
---


title: Unity LoadLevel Loads Late

text:
# Question
Title: Unity LoadLevel Loads Late
We are developing a 2D game for Android on Unity. It's our first project, we don't have a lot of knowledge on Unity. We have 2 scenes, in first scene there is only a "Play" button. When that button clicked, other level loads.

```
void Update () {
    startButton.onClick.AddListener(() =>
    {
       Application.LoadLevel(1);
    });
}

```

Problem is; when we click on Play button, it takes at least 10 seconds to load other level. There isn't much objects on other level so it shouldn't take that much time to load. Sometimes it takes 20 seconds and sometimes game freezes and level won't load. How can we reduce that loading time?

# Answer
> 0 votes
You should read the documentation about *AddListener()*. It **adds** the specified argument as callback to the onClick event.

That means, once you call the function with your callback, it will be registered and called, whenever the event is fired. Since *Update()* is called once per frame, you keep adding the callback to the event, which will result in hundreds of calls to it, once the event is being triggered.

In order to fix this, you can simply move the call to *AddListener()* to the *Start* or *Awake* function, which is only called once per GameObject.

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


# Question
Title: Specular intensity of non-metals(plastics) in metalness pbs workflow
The specular color in metalness/roughness workflow is usually defined as following:

```
float3 specColor = lerp(0.03f, albedoColor, metallic);

```

The Cook-Torrance BRDF is given with the following formula:

The final color will be:

```
Ci = (diffColor*(n.l)+Ks*specColor*cook);

```

My question is - won't specular be too dim for non-metals? Cook-Torrance term will be multiplied by 0.03 in case of dielectrics - this will make the specular component virtually non-existent. This doesn't seem realistic to me, because smooth plastic reflects a lot of light, almost as much as metals:

What am I missing?

# Answer
> 1 votes
I think I got my answer - Beckmann distribution term from the Cook-Torrance equation becomes really high when the roughness is low: For roughness = 0.01 the Beckmann term becomes 3183; for 0.001, it becomes 318310.

The roughness has to be much lower on non-metals to make the specular highlight noticeable.

---
Tags: shaders, pbr
---


title: HTML5 clicking objects in canvas

text:
# Question
Title: HTML5 clicking objects in canvas
I have a function in my JS that gets the user's mouse click on the canvas.

Now lets say I have a random shape on my canvas (really its a PNG image which is rectangular) but i don't want to include any alpha space.

My issue lies with lets say i click some where and it involves a pixel of one of the images. The first issue is how do you work out the pixel location is an object on the map (and not the grass tiles behind).

Secondly if i clicked said image, if each image contains its own unique information how do you process the click to load the correct data.

Note I don't use libraries I personally prefer the raw method. Relying on libraries doesn't teach me much I find.

# Answer
You carry out a point-shape intersection at the clicked point.

Your event will carry a .clientX and .clientY property which gives you the location of the click relative to the browser window. You can calculate where this is on the canvas.

Once you've got the canvas (x,y), then you need to convert view coordinates into world coordinates, which would effectively reverse any transformation you have used to draw things (e.g. scrolling offszet).

Once you have the world-coordinates, then it's just a matter of doing a point-shape intersection in world-coordinates. If it's a rectangle that is pretty trivial.
> 0 votes

# Answer
Use the following for mouse movement:

```
window.addEventListener("mousemove", function(e)
{
    // offsetX and layerX are actual positons of the canvas, while clientX is the position
    // in the page
    mouse.x = e.offsetX || e.layerX;
    mouse.y = e.offsetY || e.layerY;
    // detect a mouse click here
    updateCanvasForClick();
});

```

You can also round the position to get the tile:

```
function getTile(canvasX, canvasY)
{
    var x = Math.floor(canvasX / tileWidth);
    var y = Math.floor(canvasY / tileHeight);
    return map[x][y];
}

```
> 1 votes

# Answer
If I understand your question correctly, you have the coordinate in screen space of the click and want to know if there is an object there. And I'm assuming this is in 2D.

Do you have the height and width of each object and their location in the canvas? You could just then iterate over your object and figure out if that x,y is inside your objects rectangle. Than look at that pixel in the image (your could use a hidden canvas an put the objects image in there and then get the pixel color using https://developer.mozilla.org/En/HTML/Canvas/Pixel\_manipulation\_with\_canvas then figure out if it's alpha value is above 0.

You could make it faster by organizing your objects in a Quadtree
> 0 votes

---
Tags: javascript, html-canvas
---


title: Tile Map Coordinates

text:
# Question
Title: Tile Map Coordinates
I am have now this code: http://jsfiddle.net/DK67k/2/ In here is 2D tile map and when you click on tile you get coordinates on alert. But for get precises coordinate you need click on top left tile(tiles is 16x16) and if I click on bottom right tile I am get second tile coordinates.

Maybe anyone have idea how to fix this?

# Answer
> 4 votes
When you rely on mouse coordinates on the web browser it takes in count the whole screen. So you must not rely on absolute mouse coordinates, you have to subtract the canvas offset on the page from it to use it on the 2D Tile Map.

An example of code

```
var x = e.pageX - canvas.offsetLeft;
var y = e.pageY - canvas.offsetTop;

```

# Answer
> 1 votes
```
window.addEventListener("mousemove", function(e)
{
    mouse.x = e.offsetX || e.layerX;   //refers to x relative to canvas
    mouse.y = e.offsetY || e.layerY;   // y relative to canvas
    // update for click here - it is should not be done each frame
});

```

---
Tags: javascript, html5, html-canvas
---


# Question
Title: Calculating ln (natural logarithm) in games
I am developing a game for tablets using the Marmalade SDK and Cocos 2dX.

In my game I have implemented a separation steering behavior in order to keep some of my characters separated from eachother. Currently I am calculating the magnitude of this steering force using a y = -ln(x) function, in which ln is the natural logarithm.

However, I am wondering if this is a wise choice of function, because it may be costly for the processor to calculate this, just like the square root function.

What do you think, should I try to replace my function for something similar to optimize my game's performance, or there will be minimal gain in replacing a logarithm function for a 1 / x function, for example.

# Answer
> 1 votes
**No. Definitely don't worry about this.**

Even if your game calls `log()` a lot of times in a frame, that's still very, very unlikely to be a CPU bottleneck. Memory access latency is where the bulk of you CPU time is going to be spent on. To give you an idea of the disparity between instruction costs and memory access costs, take a look at this segment from the talk Data-Oriented Design and C++ from CppCon 2014.

According to sample data collected by the author, a costly instruction like a square-root is around ~15-20 cycles latency. A more expensive instruction like sine/cosine is in ~100-150 cycles range. A memory access in main RAM, resulting from a cache miss, is going to have anything from 200 or more cycles of latency. So modern optimizations should focus a lot more in making sure data locality and CPU caches are well used, rather than optimizing at the instruction level, like in the old days when memory and CPU clocks weren't so far apart.

---
Tags: mathematics, game-mechanics, optimization
---


# Question
Title: How can I detect if a gameObject has collided with two other specific objects at the same time?
How can I detect if a gameObject has collided with two other specific objects AT THE SAME TIME?

This is what I intend to do but it does not work:

```
void OnCollisionEnter (Collision col)
{

if(col.gameObject.name == "object1" && "object2")
{
    Destroy(gameObject);
}
}

```

How can I correct this piece of code?

# Answer
You can keep track of collided objects. In simple it looks like:

```
private bool isCollidedWithObj1 = false;
private bool isCollidedWithObj2 = false;

public void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.name == "object1")
        isCollidedWithObj1 = true;
    else if (collision.gameObject.name == "object2")
        isCollidedWithObj2 = true;

    if (isCollidedWithObj1 && isCollidedWithObj2)
        Destroy(gameObject);

}

public void OnCollisionExit(Collision collision)
{
    if (collision.gameObject.name == "object1")
        isCollidedWithObj1 = false;
    else if (collision.gameObject.name == "object2")
        isCollidedWithObj2 = false;
}

```

You can implement more flexible solution:

```
private List<string> collisions = new List<string>();

public void OnCollisionEnter(Collision collision)
{
    collisions.Add(collision.gameObject.name);

    if (collisions.Contains("object1") && collisions.Contains("object2"))
        Destroy(gameObject);

}

public void OnCollisionExit(Collision collision)
{
    collisions.Remove(collision.gameObject.name);
}

```

But keep in mind that this code will be much slower, especially for many collisions at the same time. BTW, strings are slow.
> 4 votes

# Answer
Expanding Exerions answer, you can define public list of GameObjects. This will allow you drag&drop objects in editor which will be collision checked with - no hardcoded values *and* it removes the need of storing *every single* collided object name (and optionally also not performing slow string comparisons). Moreover, if you add custom delegate, you can subscribe directly to multiCollisions, like it was built-in event, moving logic onto subscriber. Removing hard-codded strings and logic will make your script much more reusable.

```
public List<GameObject> CheckedObjects;
private int match_count = 0;

public delegate void FireAction(GameObject obj);
public event FireAction OnMultiCollisionEnter;
public event FireAction OnMultiCollisionExit;

void OnCollisionEnter(Collision other)
{
    if (collisions.Contains(other.gameObject))
    {
       match_count++;
       if(match_count == CheckedObjects.Count)
          OnMultiCollisionEnter(this);
    }
}

public void OnCollisionExit(Collision collision)
{
    if (collisions.Contains(other.gameObject))
    {
       if(match_count == CheckedObjects.Count)
         OnMultiCollisionExit(this);
       match_count--;
    }
}

```

*note: did not checked if object can enter twice without exiting, if that is possible, store set of currently colliding objects instead of incrementing logical value*
> 2 votes

# Answer
```
if (col.gameObject.tag == "object1" && col.gameObject.tag == "object2")

```

You forgot the 2nd col.gameObject.id

Sorry... I changed the name to tag (you must tag the object first)
> -1 votes

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


# Question
Title: OpenGL: Objects wont draw at certain angles while using lighting(shaders)
I was following this tutorial (http://www.lighthouse3d.com/tutorials/glsl-12-tutorial/point-light-per-pixel/) but when the camera is at a certain angle, if I had alpha test and blend enabled the cube i have in the scene wouldn't draw, otherwise they would be black(if alpha and blend was disabled) Any thoughts on what's going on?

here is some relevant code:

```
glClearColor(0.6, 0.6, 0.6, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(80, (float)window.getSize().x / (float)window.getSize().y, 0.01f, 1000.0);
glMatrixMode(GL_MODELVIEW);

glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glEnable(GL_ALPHA_TEST);
//glAlphaFunc(GL_GREATER, 0.1f);

glEnable(GL_COLOR_MATERIAL);
glShadeModel(GL_SMOOTH);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

glEnable(GL_AUTO_NORMAL);
glEnable(GL_NORMALIZE);
    .....

void Lighting(Camera cam, sf::Vector3f Pos) {
GLfloat amb[] = {0.2, 0.2, 0.2, 1};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, amb);

GLfloat diff[] = { 1, 1, 1, 1 };
GLfloat pos[] = { Pos.x, Pos.y, Pos.z, 1 };
glLightfv(GL_LIGHT0, GL_DIFFUSE, diff);
glLightfv(GL_LIGHT0, GL_POSITION, pos);
}
....
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
cam.up(delta, window);
Lighting(cam, Pos);
sf::Shader::bind(&shader);

cube.draw();
cube1.draw();
window.display();
sf::Shader::bind(NULL);

```

draw function for cubes:

```
glPushMatrix();
    glTranslatef(pos.x, pos.y, pos.z);
    glBegin(GL_QUADS);
        glColor3f(color.r / 255, color.g / 255, color.b / 255);

        glVertex3f(0, 0, 0);
        glVertex3f(width, 0, 0);
        glVertex3f(width, height, 0);
        glVertex3f(0, height, 0);

        glVertex3f(width, 0, 0);
        glVertex3f(width, 0, -length);
        glVertex3f(width, height, -length);
        glVertex3f(width, height, 0);

        glVertex3f(0, 0, -length);
        glVertex3f(0, 0, 0);
        glVertex3f(0, height, 0);
        glVertex3f(0, height, -length);

        glVertex3f(width, 0, -length);
        glVertex3f(0, 0, -length);
        glVertex3f(0, height, -length);
        glVertex3f(width, height, -length);

        glVertex3f(width, 0, 0);
        glVertex3f(0, 0, 0);
        glVertex3f(0, 0, -length);
        glVertex3f(width, 0, -length);

        glVertex3f(0, height, 0);
        glVertex3f(width, height, 0);
        glVertex3f(width, height, -length);
        glVertex3f(0, height, -length);
    glEnd();
glPopMatrix();

```

# Answer
Without digging too deep, I noticed a couple things in your code:

First, you're using old style OpenGL functions (pre-3.0) which haven't been relevant for years. I suggest studying from a more up-to-date tutorial site, such as this one I've been using: http://ogldev.atspace.co.uk/

Second, in your call to glColor3f (which is outdated) you're dividing your color by integers. I can't see your declaration of 'color' but if it is also integral then all those values are being rounded down to 0 so your color is all black. Get in the habit of specifying things as floats when that's what they're expected to be, like this: `256.0f`
> 0 votes

---
Tags: opengl, shaders, sfml
---


title: Which MoCap Animation Sits

text:
# Question
Title: Which MoCap Animation Sits
I have an UMA that I want to be in a sitting position basically forever. I assume I need an animation that will put him in an idle sitting position.

I found the MoCap Huge Animation library for free in the Assets Store, but it is so big that I don't know which animation is sitting.

Does anyone know of an idle sitting animation that I could use? Or specifically which number (ie 02\_01) of the MoCap Huge Library which has one?

# Answer
> -1 votes
See the 13\_01 - 13\_42. Many look weird though.

---
Tags: animation, unity
---


title: Smooth matrix rotation

text:
# Question
Title: Smooth matrix rotation
I have a coded a simple example for a matrix rotation. The example rotates a sphere around its center. The problem is that the rotation is not running perfectly smooth and I'm wondering why.

Here is a minimal code sample:

```
float totalMs = 0.0f;
int animationDuration = 5000;

void update(float deltaMs) {
    totalMs += deltaMs;
    float degrees = (totalMs % animationDuration) / animationDuration * 360.0f;
    glm::mat4 rotation = glm::rotate(glm::mat4(), radians(degrees), rotationAxis);

    //multiply modelViewMatrix by rotation matrix
    //and use the resulting matrix in shader to transform points
}

```

I'm programming in C++, using GLM Library for Maths, SDL2 for rendering context and OpenGL for the rendering.

Any hints what could cause the rendering to not look totally smooth?

Edit: Ok I found out that the time needed for **SDL\_GL\_SwapWindow()** at the end of my gameLoop varies between \<1ms and \>30ms. What could be causing this?

# Answer
> 1 votes
If you have v-sync enabled ( SDL\_GL\_SetSwapInterval(1) ), SDL\_GL\_SwapWindow will wait until your monitor refreshes.

---
Tags: opengl, c++, glm, sdl2
---


# Question
Title: How should I define interaction modes in a strategic game?
I am creating a typical strategic game that gamer can select, deploy and move the game characters (Human mostly) and move or create buildings on its isometric map.

These all are going to be done by gamers gestures obviously, So each time I am handling a tap, pan, swipe or pinch, it is important to know what was the gamer at the middle of or was doing so the new gesture can be handled.

Doing this, I created a global enumerated type including Idle,Select,PanMap and Place and defined a variable with name *gameMode* to control what the gamer is about to do. for example when the game starts it is valued "Idle" and when gamer touches a building or a character it will be selected only if the gameMode is Idle and if so gameMode will be changed to Select so the handlePan() method can manage the new gesture and sees if the user is moving the map or a selected building for instant.

When the gamer selects a building and does a pan afterward, the game logic should update the gameMode. When the first touch point of the pan gesture is recieved by handlePan() function, the function will check it against the selected building(currentSelection) to see if the gamer is tended to move the building or it is just a simple map panning, by changing the gameMode to "Place" or "PanMap" and check which gameMode is the case while processing the rest of the touches so they can be handled correctly.

> As I have mentioned above, I have four game modes including idle, select, panmap(while something is selected), place (when gamer is moving something on the map)

*Can anyone with strategic experience tell me is this kind of handling user interaction is the best way?*

*if yes do you think these modes are enough?*

*Can you tell me what was your modes in case you used this method?*

I am using **SpriteKit** with xcode.

# Answer
> 1 votes
I can't tell you if this method is good, but I have a similar system in my game Blight of the Immortals.

It's even called gameMode.

Basicly a global state that I use to interpret what a gesture means and even what kinds of things should be rendered in the map.

I have a gameMode for when the player is plotting a movement path for units, one for when they are selecting a targets for powers, even one for when the editor is open and I am designing maps.

---
Tags: game-design, game-loop, isometric, strategy
---