# Question
Title: Best Way to allow players to "Dye" images without losing color quality?
I am creating a 2.5D isometric (2D images) game.

I want the players to be able to "dye" their armor, clothes, and other things. I find that grayscaling everything leads to losing out on some of the more "natural" coloring. For example, making a dragon with red/yellow grayscale and then applied overlay color, leads to a purely red dragon with all loss of the secondary color. Meanwhile, dying that same Red/Yellow Dragon Blue, makes it Blue/White which looks great.

The characters in my game do not have a huge variety of equipment. The game is closer to how League of Legends handles characters and graphics. There may be a single type of character (ex. Hero) but multiple outfits for the character as options. I want players to be able to have as much customization as possible in the limited number of "outfits" and characters.

So I want players to be able to select a character, pick one of several weapons, alternate between a handful of costume choices (layered onto the characters), and then dye most of everything (pick a specific metallic color for weapons, pick any color at all for clothing).

If I were to be able to use grayscale without losing some of the coloring, I would.

Here is an example as to what I am talking about:

It is not even possible to "dye" the Dragon, no matter what I use in Photoshop's "Color Overlay" options. Obviously, I am doing it wrong if it is possible to color it better using grayscale. For a color like Green or Yellow or a Lighter Purple, this works okay. For any other color, it destroys the art.

However, it looks much better if I do NOT grayscale it, and instead simply apply a "HUE" color to the original (Red/Yellow) image.

Red Hue

Purple Hue

Now the players could dye the Dragon ANY color, and it would still look great! (The yellow turns white, while the red turns to any color of the rainbow.)

Does this mean that WHITE or BLACK is the best secondary color? Then use some sort of method or shader to change white (secondary) color to something different?

Are there any articles on this complex method of taking a single image, and based on the coloring, dye different pixels?

For the Dragon, would it work best as a White/Black high Contrast Dragon? Is Red/Yellow the best color set? It turns out a lot better for images than a few other colors I tried. Is Grayscale still superior?

Does Photoshop's "Blending Options" not include the method to appropriately "dye" images for a video game? Are there complex Shaders/Methods that allow me to achieve better success?

**Note: If GrayScale allows me to reduce the RAM consumption of my images, or prevent loss of quality during lossy compression, that would be something I would seriously consider.**

# Answer
Hue-shifting is one possibility that would let you get a range of colors without losing the color details. The basic idea is to convert each pixel from RGB to HSV space, then offset the hue by a user-defined amount, then convert back to RGB. Actually, this can be done more efficiently by applying a rotation matrix to the RGB values: create a matrix that rotates around the (1, 1, 1) axis by the user-defined hue angle. Then you can simply apply this matrix to each RGB value in your pixel shader.

This will allow the red-yellow dragon to be shifted to a yellow-green, green-cyan, cyan-blue, blue-magenta, or magenta-red dragon. This is a bit restrictive as the two colors can't be altered independently with this approach. They'll maintain their relative hue as they're authored in the original image. There are also some colors you can't access, e.g. you can't make a black-and-white dragon this way. Still, this may be enough for your purposes.

Another possibility, if your models have two or three "key colors" (red and yellow here), you could author the original image using a separate color channel for each key color. In this case, you'd author the dragon red and green instead of red and yellow, and if you had a third color you could author it in blue. Then, you can let the user pick the three key colors, and use the red, green, and blue values in the image as amounts of those user-defined colors to blend in. So your pixel shader would look something like

```
finalColor = image.r * userColor1 + image.g * userColor2 + image.b * userColor3;

```

This would let the users pick any color combination they wanted, including things like black and white, or purple and gold.
> 19 votes

# Answer
The problem you are facing is that you can't simply "tint" the whole image, the appearance you see is more than just a base color. For one you have fine gradients from one one material to the other, but more importantly you also have reflections,highlights and shadows, which are not influenced by the base color. (Those are basically added on top of it.)

So you need to decompose the image into it's components.

**A Example**:

In this case we have 3 layers:

* The Background - This contains the elements that shouldn't be colored.
* The Part that should be colored - This is multiplied by the color. (OpenGL multiplies by default if you specify a color other than white.)
* The Highlights - These are drawn additive over the whole image. It's not white but yellow, to emulate a hue change. Objects aren't just a single color, the hue changes together with the brightness.
> 11 votes

# Answer
I would personally recommend using mask textures to achieve what you want. This will ensure that your main RGB24 texture will keep its original colour quality without sacrificing any precision. It will also give you plenty of artistic freedom to blend your main texture with your colour mask.

Each mask can be viewed as a grayscale texture that will linearly interpolate the colour of your base texture with your custom color. Let's say you are letting your users customize two colors, the pixel shader will look something like this:

> inputs: MainTexture(RGB), Mask1Texture(A), Mask2Texture(A), Colour1(float), Colour2(float)
>
> output: (Mask1Texture+Mask2Texture)-MainTexture + Colour1\*Mask1Texture + Colour2\*Mask2Texture

This suggests that the more a mask has a large value for one pixel, the less your main texture will impact the output colour of that pixel. For example you could convert your dragon texture into a grayscale and erase everything but your wings to have custom wing colour no matter the body colour.

I have used this technique for mobile games and it won't affect your overall performance. It might cost you a 33% more RAM per texture but the trade-off for quality is probably worth it.

P.s. If you're only thinking of using one custom colour, you can simply use the Alpha channel of your RGBA32 main texture as your mask.
> 3 votes

# Answer
you can use color palettes and let the player edit the palette. If you use shaders, you can use 1D textures as palettes and the original gray value as index.

To convert a true color image into an image with 255 colors, you can take all your pixel color values and group them in the 3d color space to 255 clusters with the k-means algorithm. Or use generic image conversion tools. Then it is important to mention that interpolation of the gray value texture will be an interpolation of indices in your color textures. This can lead to a result where you have several colors between two texels of your original image. This can be solved by disabling interpolation (I think you do not want to do that) or by sorting your color palette in a useful manner.
> 2 votes

# Answer
you could convert the image to a gray image but still save it with rgba channels. store a weight value in the alpha channel then use this to decide how much dye to apply to a pixel. this weight can be calculated based on how close the color is to white. the closer to white the pixel is, the less dye should apply or the lower the weight should be. this will leave most highlights with their original lightness, but apply a bit of the dye to it. the final pixel color can then be found by calculating each channel Ro + (Rd * Ao) where Ro is the original red, Rd is the red in the dye color and Ao is the Alpha of the original. so all white pixels get no new color and all black pixels assume the dye color.
> 1 votes

---
Tags: 2d, image, color, image-effects
---


# Question
Title: How do you calculate the rotational velocity of a flying object?
When a arrow shaped object is fired it slowly adjusts it's rotation to match the direction it is moving. But what is the actual physics behind it?

The question is: **How many degrees does the ship turn in a second?**

I usually approximate the effect by simply setting the rotation to the angle of the velocity, however this is not possible this time since the player is able to influence the rotation of the ship by steering.

# Answer
### 1: Simple physics

There will be a subtle difference in drag on either side\*, because the side rotating into the wind will have greater dynamic pressure than the one that rotates with the wind. For an arbitrary shape, this will be somewhat difficult to calculate (although possible) for correct physics. You should not try, and approximate it instead. This approximation can simply be proportional to flow velocity. This is *sort of* physically accurate, and very simple to calculate.

For a ship, which presumably has roughly the same shape as an arrow with something "draggy" at the downstream end of it, this effect will be proportional to the ship's alignment with the direction. For example, `(1 - direction.dot(rotation))` might work well. This will also be affected by the magnitude of rotational speed.

So for an overall system, rotational acceleration due to drag will be roughly:

```
velocity.length * rotationSpeed * (1 - direction.dot(rotation)) *
    SOME_UNSCIENTIFIC_CONSTANTS * getDragRotationDirection();

```

This will likely result in an oscillating rotation. It will bounce around its own aligned direction. You will need to tweak the code to dampen that somehow.

### 2: for 2D physics-based system:

Treat the tail-fins (or whatever) as the location to apply a constant impulse proportional to velocity in the direction opposite velocity. Because this location should be offset from the center of mass, it will yield a moment that will rotate the ship back toward the forward-direction. When the ship is aligned with that direction, it will yield no rotation.

For this method, be wary of the special case where the tail is pointed almost directly into the wind. That might yield weird results.

---

**\*Side:** The cross product of the flow direction (opposite direction of movement) and the axis of rotation (for 2D, unit-z), will yield a "side". The other side is the opposite direction.
> 4 votes

# Answer
> When a arrow shaped object is fired it slowly adjusts it's rotation to match the direction it is moving. But what is the actual physics behind it?

The Physics behind it is a combination of G-Force(gravity acceleration) and Aerodinamics. An arrow usually has a head, a body segment and a tail, the mass center will be near to the head. Although G-Force pulls the whole arrow towards the ground, the shape differences between the head and the tail create different Aerodynaics reactions.

The tail of the arrow offers more air resistance along the G-force direction than the head, thus the head will fall to the ground faster. As head and tail are connected through the body segment, the tail will act as a pivot creating rotation. The rotational speed (degrees) will depend on the shape of the arrow.

In your case the rotational speed will depend on the ship shape. If I were you I would separate the ship into segment and give each segment different gravity acceleration penalty, this penalty will simulate air resistance and the segment with most resistance will act as the pivote point.

Calculate the mass center of each ship segment and calculate the following cross product for each ship segment:

Ti =(distance to pivot)cross(PivotPenalty-SegmentPenalty)\*m

Penalty must be un the opposite direction of G Force.Whit m being the masas of the segment

Sum all Ti to get the final total Torque, now you can associate this value to a rotational speed value.
> 1 votes

# Answer
To answer: How many degrees does the ship turn each frame? u need to know how many frames per second u will have. But let's say u have 60 frames per second.

Knowing how many degrees the ship turns per second is just a matter of math. I would solve this using vectors:

* Calculate the new vector every 1/60th of a second
* Save the current position of the object(will become the old position after move)
* Move the object using that new vector every 1/60th of a second
* Use trigonometry to calculate the angle between the old and new position ( use center circle as third vertex)

Remember:

* Gravitational acceleration's unit is m/s^2
> -1 votes

---
Tags: rotation, physics
---


# Question
Title: Why does my character scroll off the screen instead of staying within the bounds of the screen?
In my XNA game, I have my "big boss" loaded and in the game screen. I put the code to update its position in the `Update` method of the main class.

The objective is to get the "big boss" to move from the right hand side of the screen to the left. But instead, it moves off the screen and will not move back again.

Here's my code in the `Update` method:

```
public void UpdateBigBoss()
{
  // make the updateBigBoss boss move from r to l
  // and l to r
  // next, take count the collision,
  // by increasing the hit counts by 1
  // when hit counts reach to 10
  // make the big boss alive to false (mean disappear)
  // position of the paddle - start
  motion = Vector2.Zero;

  if (score > 200)
  {
    motion.X = 1;
  }

  motion.X *= BigBossSpeed;
  BigBoss.position += motion;
}

```

# Answer
> 0 votes
```
public void UpdateBigBoss()
{
   motion = Vector2.Zero;

  // make the updateBigBoss boss move from r to l
  // and l to r
  motion.X += dir;
  if(BigBoss.position.X >r || BigBoss.position.X< l){
    var at = BigBoss.position.x
    BigBoss.position.X = Math.max(l,Math.min(r,at));
    dir *= -1;
  }
  // next, take count the collision,
  // by increasing the hit counts by 1
  if(BigBoss.isCollided) hitCount++;

  // when hit counts reach to 10
  // make the big boss alive to false (mean disappear)
  if(hitCount>=10)BigBoss.alive = false;

  // position of the paddle - start
  //

  if (score > 200)motion.X = 1;

  motion.X *= BigBossSpeed;
  BigBoss.position += motion;
}

```

# Answer
> 2 votes
Your code only ever instructs the boss character to move in one direction, forever.

You set the X component of the motion vector to 1 when the score is greater than 200, and then increment the boss's position by that value. You *never* attempt to check if the boss's position after incrementing is within an appropriate threshold of the world boundaries and, if so, set some state to move him the opposite direction.

A simple way to do this would be to check if `bigboss.position.X + bigboss.size.Width >= RightEdgeOfScreen` and if so, set `motion.X` to be -1. Do the same for the opposite edge of the screen.

---
Tags: xna, c#
---


# Question
Title: Collision detection via adjacent tiles - sprite too big
I have managed to create a collision detection system for my tile-based jump'n'run game (written in C++/SFML), where I check on each update what values the surrounding tiles of the player contain and then I let the player move accordingly (i. e. move left when there is an obstacle on the right side).

This works fine when the player sprite is not too big: Given a tile size of 5x5 pixels, my solution worked quite fine with a spritesize of 3x4 and 5x5 pixels.

My problem is that I actually need the player to be quite gigantic (34x70 pixels given the same tilesize). When I try this, there seems to be an invisible, notably smaller boundingbox where the player collides with obstacles, the player also seems to shake strongly. Here some images to explain what I mean:

* Works:
* Doesn't work:
* Another example of non-functioning: (the player isn't falling, he stays there in the corner)

My code for getting the surrounding tiles looks like this (I removed some parts to make it better readable):

```
std::vector<std::map<std::string, int> > Game::getSurroundingTiles(sf::Vector2f position)
{
    // converting the pixel coordinates to tilemap coordinates
    sf::Vector2u pPos(static_cast<int>(position.x/tileSize.x), static_cast<int>(position.y/tileSize.y));
    std::vector<std::map<std::string, int> > surroundingTiles;

    for(int i = 0; i < 9; ++i)
    {
        // calculating the relative position of the surrounding tile(s)
        int c = i % 3;
        int r = static_cast<int>(i/3);
        // we subtract 1 to place the player in the middle of the 3x3 grid
        sf::Vector2u tilePos(pPos.x + (c - 1), pPos.y + (r - 1));

        // this tells us what kind of block this tile is
        int tGid = levelMap[tilePos.y][tilePos.x];

        // converts the coords from tile to world coords
        sf::Vector2u tileRect(tilePos.x*5, tilePos.y*5);

        // storing all the information
        std::map<std::string, int> tileDict;
        tileDict.insert(std::make_pair("gid", tGid));
        tileDict.insert(std::make_pair("x", tileRect.x));
        tileDict.insert(std::make_pair("y", tileRect.y));

        // adding the stored information to our vector
        surroundingTiles.push_back(tileDict);
    }

    // I organise the map so that it is arranged like the following:
    /*
     * 4 | 1 | 5
     * --  -- --
     * 2 | / | 3
     * --  -- --
     * 6 | 0 | 7
     *
     */
    return surroundingTiles;
}

```

I then check in a loop through the surrounding tiles, if there is a 1 as gid (indicates obstacle) and then check for intersections with that adjacent tile.

The problem I just can't overcome is that I think that I need to store the values of all the adjacent tiles and then check for them. How? And may there be a better solution? Any help is appreciated.

P.S.: My implementation derives from this blog entry, I mostly just translated it from Objective-C/Cocos2d.

# Answer
I believe that the cause of the problem, is that you are only checking for collision with the 9 surrounding tiles. This is OK, as long as the width and height of the entity that is being checked for collision is less than or equal to the width and height of the tiles. In order to fix this issue, you need to check for collision with the tiles from (x - 1, y - 1), to (x + width + 1, y + height + 1). The following image should demonstrate what I mean.

By doing this, you ensure that all of the tiles that the player can collide with (assuming that the player isn't going fast enough to move through a tile), will be checked for collision.

With this in mind, you should now have collision code that looks something like this:

```
xPos += velocityX;

// Note that xPos and yPos are the pixel x and y of the player, not the tile x and y of the player.

int left = xPos / TILE_WIDTH;
int right = (xPos + PLAYER_WIDTH) / TILE_WIDTH;
int top = yPos / TILE_HEIGHT;
int bottom = (yPos + PLAYER_HEIGHT) / TILE_HEIGHT;

for(int xt = left; xt <= right; xt++)
{
    for(int yt = top; yt <= bottom; yt++)
    {
        Tile t = world.getTile(xt, yt);

        if(collidesWith(t))
        {
            // Handle X collision
        }
    }
}

yPos += velocityY;

for(int xt = left; xt <= right; xt++)
{
    for(int yt = top; yt <= bottom; yt++)
    {
        Tile t = world.getTile(xt, yt);

        if(collidesWith(t))
        {
            // Handle Y collision
        }
    }
}

```

You may be wondering why I am moving and checking for collision on each axis separately. Unfortunately this would take too long to explain. However, I have already explained this in an answer to another question. I hope this helps.
> 3 votes

# Answer
I want to just comment, but alas I don't have 50 freaking points. :)

Your posted code makes no mention of the player size, all it seems to be doing is retrieving a set amount of the surrounding tiles. Which if they are as you say 5x5 pixels in size, and you are only getting the surrounding 3x3 tiles, than you are only checking the tiles within 15x15 pixels of your characters POSITION. Which makes sense for your smaller character of 3x4 or 5x5, but for a 34x70 you are not checking the tiles out far enough. So your character is clipping through the tiles.

I think you should expand your search of the surrounding tiles based upon the size of your character.

Like

```
int tilesToCheckWide=characterSize.w/tileSize.w;
int tilesToCheckHigh=characterSize.h/tileSize.h;

```

and then put that in your for loop to get the surrounding tiles. I think it may be better to change your whole system to a polygonal collision check instead of a pixel/tile check. But that has its own whole range of problems with platformers.

Good luck and I hope I made sense. -Mike

EDIT: LOL, I just saw aidan's answer and he has a picture :(
> 3 votes

---
Tags: collision-detection, tiles, physics, tilemap, sfml
---


# Question
Title: Poor text rendering quality with freetype
This is my first time that I use freetype library and I think I've got some problems. Right now, I draw the bitmap generated by freetype, but the generated image is really low quality. I've been reading about hinting and anti-aliasing, but the thing is none of them helped me and the problem is still here.

Take a look at my picture:

You can actually see what I mean.

I have applied a vertical hinting before rendering in my font class:

```
float scale = 100.0f;
FT_Matrix transform =
{
    (int)((1.0 / scale) * 0x10000L),
    (int)((0.0) * 0x10000L),
    (int)((0.0) * 0x10000L),
    (int)((1.0) * 0x10000L)
};

FT_Set_Char_Size(this->mFace, 0, (int)(this->mSize * 64), (FT_UInt)(72 * scale), 72);
FT_Set_Transform(this->mFace, &transform, NULL);

```

I'm loading the character with:

```
FT_Load_Char(this->mpFont->Face(), this->mText[i], FT_LOAD_RENDER);

```

which is supposed to make the generated bitmap anti-aliased immediately as documentation has stated.

The part which I translate the buffer is here:

```
...
    BYTE intensity = bitmap->buffer[q * bitmap->pitch + p];
    D3DXCOLOR pixel(this->mColor.r * intensity,
    this->mColor.g * intensity,
    this->mColor.b * intensity,
    this->mColor.a * intensity);

    this->mpTexture->SetPixel(i, j, pixel);
...

```

My texture format is `A8R8G8B8` and I don't think I have anything wrong with my texture rendering part. The only thing that I'm not sure this is related to is the resolution. Currently I'm using the window size (640x480) which turns to lower resolution for device because of borders. By the way, this is a regular Tahoma font that I've used.

# Answer
Your image suggests you're getting the Alpha wrong. Even if you do antialias, but then treat all non-transparent values as fully opaque, you'd get that.

You don't show the Render call, are you using FT\_RENDER\_MODE\_DEFAULT?
> 0 votes

---
Tags: fonts, text
---


title: Trying to make sprite float up and down

text:
# Question
Title: Trying to make sprite float up and down
Using LibGDX + Box2D and my understanding of the answer posted from this question: Here

I apply the following impulse:

```
// modify sprite's Box2d Body object
int a = 8; // amplitude
int f = 1; // frequency
int p = 1; // phase
float value = (float) ( a * Math.sin( 2 * Math.PI *f * TimeUtils.millis() + p ) );
body.applyLinearImpulse( 0, value, body.getPosition().x, body.getPosition().y, false );

// render it
sprite.setPosition( body.getPosition().x, body.getPosition().y );
sprite.draw( spriteBatch );

```

But this just causes my sprite to go straight up and offscreen rather than doing a wave. What part of the algorithm am I doing wrong?

# Answer
> 0 votes
```
TimeUtils.millis()

```

Maybe you mean to do:

```
final long floatyPeriod = 3000; //3 secs
long now   = TimeUtils.millis();
long delta = lastTime - now;
lastTime = now;
object.floatyTime += delta;
if (object.floatyTime > floatyPeriod )
    object.floatyTime -= floatyPeriod;

...

float value = (float) ( amplitude * Math.sin( 2 * Math.PI * frequency * object.floatyTime/1000 + phase ) );

```

I don't understand how your code would make it go straight up though, I think it should wobble up and down like crazy with yours.

---
Tags: mathematics, physics, libgdx, box2d
---


title: problem with git on a unity project

text:
# Question
Title: problem with git on a unity project
I tried to version control my project folder with git. When it came to pull the project from the repository, though, something went wrong: apparently scripts are missing and the prefabs and kind of all the graphical elements appear to be pinkish. Does anybody know how to fix this?

This is the .gitignore I'm using at the moment:

```
Temp/
Obj/
UnityGenerated/
Library/

ExportedObj/
*.svd
*.userprefs
*.csproj
*.pidb
*.suo
*.sln
*.user
*.unityproj
*.booproj

.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db

```

Thanks in advance.

# Answer
Go to `Edit -> Project Settings -> Editor` and make sure that the `Version Control Mode` property is set to `Meta Files`, not `Disabled`.

Starting from Unity 4.2 you can also set the `Asset Serialization Mode` property to `Force Text` without needing a Pro license, which is supposed to work better with version control too.

And here is the gitignore that I use:

```
[Ll]ibrary/
[Tt]emp/
[Oo]bj/

# Autogenerated VS/MD solution and project files
*.csproj
*.unityproj
*.sln
*.apk
*.sln.DotSettings.user
*.suo
*.userprefs
*.pidb

```
> 12 votes

# Answer
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

1. **Enable `External` option in `Edit(or Unity on Mac) → Preferences → Packages → Repository`**
2. Switch to `Hidden Meta Files` in `Edit → Project Settings → Editor → Version Control Mode`
3. Switch to `Force Text` in `Edit → Project Settings → Editor → Asset Serialization Mode`
4. Save scene and project from `File` menu

More information about keeping Unity Project under source control you can find in this post.
> 3 votes

---
Tags: unity, git
---


title: One InputProcessor for two controllers

text:
# Question
Title: One InputProcessor for two controllers
On my screen I want to display two controllers, one to turn around the character (We'll call it`Look`) and one to move the character (We'll call it `Move`).
I have a line registering a `ControllerListener` Which implements `InputProccessor`.
My question is if I can use the ControllerListener to receive input from both `Move` and `Look` at the same time.
In case that wasn't clear, I mean I want the player to maneuver the map using both controllers, not just one.

# Answer
> 0 votes
On Desktop, for example, in your `keyDown()` method, you should check for all the expected input events at the same time, not just one per method call. So, if you want both move and look to be triggered, you should do something like this:

```
@Override
public void keyDown(int keycode) {
    if (keycode == Keys.A) inputController.moveLeft();
    if (keycode == Keys.W) inputController.moveForward();
    if (keycode == Keys.D) inputController.moveRight();
    if (keycode == Keys.S) inputController.moveBackward();

    if (keycode == Keys.LEFT) inputController.lookLeft();
    if (keycode == Keys.UP) inputController.lookUp();
    if (keycode == Keys.RIGHT) inputController.lookRight();
    if (keycode == Keys.DOWN) inputController.lookDown();
}

```

If you check your input event with `else`s, the first triggered event will be processed, all the others will be ignored, I guess you can see the difference.

Of course, you can play with your code to split this into two different input controllers, or even two different input processors. If you choose to use two different input processors at a time, you will have to set them both using an `InputMutiplexer` when setting the input processing handler on the game screen, like this:

```
final InputMultiplexer inputMultiplexer = new InputMultiplexer();
inputMultiplexer.add(new MovementInputProcessor());
inputMultiplexer.add(new LookInputProcessor());
Gdx.input.setInputProcessor(inputMultiplexer);

```

This is to be implemented in a similar fashion for Android.

Hope this helps.

---
Tags: java, libgdx
---


# Question
Title: Strange behaviour using VAO (OpenGL 4.0)
I want to display a simple textured Monkey mesh using VAO. Here's the code in the render part first without VAO to see what is the result I'm looking for.

```
Texture *pTexture = meshList[idx]->GetSubMaterial()->getTexture();
VertexBuffer *pVBO = meshList[idx]->GetVertexBuffer();

pVBO->Lock();

glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(0));

if (pTexture)
{
    glEnableVertexAttribArray(1);
    glActiveTexture(GL_TEXTURE0);
    pTexture->Lock();
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(pVBO->GetVerticesByteSize(VERTEX_POSITION)));
}
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(
    (pVBO->GetVerticesByteSize(VERTEX_POSITION) +
         pVBO->GetVerticesByteSize(VERTEX_TEXTURE))));

pVBO->Unlock();

glDrawArrays(GL_TRIANGLES, 0, meshList[idx]->GetVertexBuffer()->GetBufferSize());

```

And here's the output :

As you can see, the texture mapping is correct.

Now I want to implement the code above into a VAO. So I displace it before the main loop (so out of my rendering system) and copy it in the initialization of my Mesh class (the model class).

Here's the header of the Mesh class (it's just to see the composition of this class, the attributes, etc.) :

```
class Mesh : public Resource
    {
        public:
            Mesh(void);
            Mesh(std::string const &other);
            Mesh(Mesh const &mesh);
            virtual ~Mesh(void);

        public:
            Mesh &operator=(Mesh const &other);
            void Create(std::string const &filename);
            void Create(OBJVertexImage *pVertexImg, OBJFaceImage *pFaceImg);
            void AttachVertexBuffer(VertexBuffer *pVertexBuffer);
            void AttachSubMaterial(SubMaterial *pSubMaterial);
            std::string const &GetUseMtlName(void) const;
            virtual std::string const &GetName(void) const;
            VertexBuffer *GetVertexBuffer(void);
            SubMaterial *GetSubMaterial(void) const;
            VertexArray *GetVertexArray(void) const;
            void prepareMeshRendering(void); //The VAO initialization is here !!!
            virtual void Release(void);

        private:
            VertexArray *m_pVertexArray;
            VertexBuffer *m_pVertexBuffer;
            SubMaterial *m_pMaterial;
            std::string m_UseMtlName;
            std::string m_Name;
    };

```

The VAO initialization is written in 'prepareMeshRendering' method. Of course I call this method when my mesh is already loaded (texture and vertex buffer loaded). The vertex buffer respect the following pattern:

```
[[all_position_vertices][all_texture_vertices][all_normal_vertices]].

```

Here's the content of this function :

```
this->m_pVertexArray->Lock();
    {
        this->m_pVertexBuffer->Lock();
        {
            glEnableVertexAttribArray(0);
            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(0));

            if (this->m_pMaterial->getTexture())
            {
                glEnableVertexAttribArray(1);
                glActiveTexture(GL_TEXTURE0);
                this->m_pMaterial->getTexture()->Lock();
                glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0,
                    OFFSET_BUFFER(this->m_pVertexBuffer->GetVerticesByteSize(VERTEX_POSITION)));
            }
            glEnableVertexAttribArray(2);
            glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, OFFSET_BUFFER(
                this->m_pVertexBuffer->GetVerticesByteSize(VERTEX_POSITION) +
                    this->m_pVertexBuffer->GetVerticesByteSize(VERTEX_TEXTURE)));
        }
        this->m_pVertexBuffer->Unlock();
    }
    this->m_pVertexArray->Unlock();

```

The texture binding code is encapsulated in the Texture class as follow :

```
void Texture::Lock(void) const
{
    glBindTexture(GL_TEXTURE_2D, &this->m_Handle);
}

```

This is the same concept for the binding of the VAO but this time in the VertexArray class.

The rendering part (more simple now than before):

```
VertexArray *pVertexArray = meshList[idx]->GetVertexArray();

pVertexArray->Lock();

glDrawArrays(GL_TRIANGLES, 0, meshList[idx]->GetVertexBuffer()->GetBufferSize());

pVertexArray->Unlock();

```

And the output :

I checked. In those 2 versions :

* The byte size of the 3 buffers (position, texture and normal) is the same (so the offsets are corrects).
* The texture handle is the same (here aqual to 1)

So I don't know what's happening. This kind of display usually appears when the texture is not bound or the channel is not correct. But here, in those 2 cases I precise the channel and the texture handle is the same. I'm going to be crazy! I think I forget something but can't find the error.

Does anyone can help me, please ?

Thanks a lot in advance for your help !

# Answer
I don't see any glActiveTexture or glBindTexture calls in your drawing code. As far as I know, VAOs handle vertex attributes only. You have to make sure the right texture unit is active and your texture is bound in your drawing routine.
> 2 votes

---
Tags: opengl, shaders, vbo, vao
---


# Question
Title: libGDX map transition via try & catch exeption
I have a simple question. Some explination first, however:

I am using libGDX and making a Legend of Zelda-type top-down game and I'm having an issue with map transitions. When I made the tilemap and added the (currently crappy) collision detection to it, I noticed that the IDE threw an error when the character walks off the map (where there are no tiles to test the collision possibility against). I thought, cool, I can use that.

Knowing that the program would throw an exception when the player left the screen, I caught that exception and used it to decide to which map the player was trying to transition and switch accordingly. I played a little transition from the scene2d actions and to the next map we went.

BUT, I got to thinking that while catching that exception is a great thing, I probably shouldn't rely on it for map transitions. I'm betting you all will agree: handle the exception just in case, but don't rely on it.

SO, this means that I need to handle a transition before the user gets off the map. I tried using transition tiles from within the collision detection:

If the tile had the transition property, figure out where the user is attempting to transfer and then play the transition effect and on to the next map. The only problem with this system is that it doesn't look right. The user transitions just as collision is made while there is still room left in the tile to transverse.

My question to you all, then, is this: Is there a middle ground between the two? Is there a way to tell end of map or last tile, allow the user to transverse the tile just prior to transitioning? Or are my two ways the only ones?

# Answer
> 2 votes
Yikes. Don't use exception handling as part of the normal flow of code. Exceptions are called exceptions because they're anomalous or exceptional events, they shouldn't be part of the standard flow of things.

Simply do a check to see if the tile the character is moving to is going to be outside the bounds of the map. It could be as simple as something like:

```
if((newPosition.x < worldBoundsMin.x || newPosition.x > worldBoundsMax.x) ||
   (newPosition.y < worldBoundsMin.y || newPosition.y > worldBoundsMax.y))
      //newPosition is out of bounds

```

# Answer
> 0 votes
I completely agree with the above answer.

However, it's not always possible to know the new position of the player after a movement has been made (For example, Box2D).

If this is the case, I'd use the edge tiles as the transition hotspot.

```
if(
   (player.x <= 0 || player.x >= map.getWidth() ) || //Are we on the left or right edge tile?
   (player.y <= 0 || player.y >= map.getHeight()) //Are we on the top or bottom edge tile?
)

```

---
Tags: libgdx, maps
---


# Question
Title: How can I keep two racing players synchronised?
I am working on a Unity mobile game, much like a multiplayer version of *Temple Run*. I'm seeing a fluctuating network latency (generally 200-500ms) because of the mobile platform.

The two player characters are shown as running along the same path and must do simple actions (jump, slide, powerup, etc.) to pass obstacles.

When a message comes late, the game assumes the remote player *passed* an obstacle. This usually works well, but in case a player is killed by an obstacle, I want the remote player to appear to die on the same obstacle/position as local player. Due to latency, the remote player appears to have crossed the obstacle before the message announcing their death even arrives.

How can I keep the players synchronised?

---

I tried moving the remote player back to the local players death position immediately as the death message arrives, it looks awkward visually and might raise other syncing issues.

# Answer
# Problem analysis

Real-time communication over a high-latency connection is obviously impossible.

You *can* of course attempt an illusion (as you're doing by making the remote player appear to have passed an obstacle when it's not yet known). When that illusion fails (as yours does when the remote player *didn't actually pass* the obstacle, but *died* instead) nothing can be done anymore.

In a case (such as here) where the illusion's failure looks *really bad*, it might be easier to accept the facts and just do your best to represent the situation as it actually is.

# Potential solution

How about *literally slowing down the other player* if their decision is taking time to propagate?

Each player sees an image of the other, but that image slows down when approaching obstacles for which the decision message is still in the air. Only once the message is received do they appear to pass or fail the obstacle. After the obstacle, the image then speeds up again to catch up, slowing down again for the next one, if necessary.

On a low-latency connection, the decision arrives soon and the slowing down and speeding up will be negligible. On a high-latency connection, this *will* make the other player appear to be lagging behind, but ensures that the *more important* game state of "who has passed this obstacle" is consistent for both players.
> 10 votes

# Answer
To complement Anko's answer, you can change a bit your game design by adding the consequence of the failed obstacle *after* the failure, for instance, a failed jump results in landing in a puddle of mud which disqualifies the player. This way the other player notices the failure by seeing the other fall in the mud, while the player who fails sees it right away.

Here is a nice blog post about this issue (it's not that recent but it's quite interesting): Darrin West's *Time Management and Synchronization*.
> 4 votes

# Answer
Is it that important for the local player to know the exact position of the remote player's death? Let's say the remote player couldn't jump over one of your obstacles, and thus died.

The dead player would see their death immediately, and would continue from the location of the accident. Nothing magical here.

The local player (the one still alive and kicking) would see the remote player pass the obstacle successfully. A death notification would come in. The remote player would stumble on their feet, fall, and slowly fade away. The next time you know the remote player's position, the player would fade in to that exact position, running normally again. In such a setup, players would be aware of latency, but latency would be represented as a game element (stumbling down) rather than jerkily appearing and disappearing players.

If speed of the two players is constant, running trajectory is predefined, and the time it takes to recover from a fall is known, you could eliminate the fading/disappearing part completely. Imagine a remote player dying at one of the obstacles. Its local representation is still running when a notification comes in. The player is shown stumbling immediately. It takes time for them to get up and start running again. Actually, it takes as much time as if they were shown dying at the obstacle. Thus, when they are up and running again, both local and remote positions are synchronized.
> 1 votes

---
Tags: unity, multiplayer, mobile, synchronization, latency
---


# Question
Title: How can I estimate the difficulty of user-generated content in my puzzle game?
I'm making a puzzle game where one player makes a puzzle, and other players attempt to solve the puzzle the first player made. The puzzles are a grid of squares that may contain different kinds of traps. There's a wide variety including the following:

* Traps that do initial damage, but don't fire again when you step on them again
* Traps that do initial damage, and continue to fire every time you step on them again
* Traps that do initial damage, and then do damage over time, but who's effect can be stopped with an antidote
* Traps that do initial damage, and damage over time, but who's effects can not be stopped

In addition to all these traps, I have walls, keys, locks, and blank tiles as well.

I'm currently showing the players attempting to solve the puzzle a "difficulty" rating that I got by taking all traps that deal damage divided by all tiles total. It seems accurate with small puzzles (4x4, 5x5), but when you scale it up (20x20, 25x25), you get deceptively low ratings for extremely difficult puzzles because of the sheer size of the puzzle.

This has led me to try to find a better solution for a difficulty rating. Things I've considered:

* Figuring out a "damage per tile" average by taking the damage all the tiles do divided by all eligible tiles a player can walk on (factor out walls), but with this approach, I can't figure out how to factor DoT (Damage over Time) tiles into it. For instance, after 10 tiles, I can give an average amount of damage a player will take with regular traps, but how do I give them an average with a DoT trap? They could activate it on the first tile or the last, and the damage numbers are significantly different.
* Figuring out a "difficulty score per tile" and trying to factor that into a rating. All tiles are currently given a "cost" (the amount it costs the player to use them when creating the puzzle), and that number roughly correlates to how much difficulty the tile adds. I was thinking about using that number to get a difficulty rating, but I'm unsure how I'd use it correctly.
* Trying random solutions and seeing how long it takes a bot to solve it. I don't think this is a good solution for a number of reasons. It could be solved on the first try by sheer luck, and hide how difficult the puzzle is. Plus, with keys and locks, backtracking is required, and I think the computing time to run these simulations would be cost prohibitive.
* Ditch difficulty ratings all together. If I can't figure out an intuitive way to show the player how difficult a puzzle is at a glance, I might just have to remove it.

I realize some of this might be hard to visualize, so here are some pictures of a puzzle and it will hopefully help you see what I mean:

The user starts at the star and makes their way to the exit. This is a view with all the tiles visible, and when the user attempted to solve it, a lot of the tiles you see in that picture would be hidden from them until they were "activated" (by the user stepping on them).

# Answer
> 3 votes
I would write a puzzle solver using Dijkstra's algorithm, which would find the optimal solution for the puzzle. This algorithm trivially returns two measures for the difficulty:

* How many steps are in the optimal solution
* How many iterations did the algorithm take to solve the puzzle

The higher the numbers, the harder the puzzle is. You need to experiment how to combine these values when calculating the difficulty.

In Djikstra's algorithm you need to implement a check to ensure that a node is not visited twice. Because of powerups and keys this check needs to be a little more complex. You need to record the state of the player (health and possessed keys) for each visited node and compare that as well. If the state of the player is *better* than previously, a node can be visited again.

This algorithm will take some time to run on more complex puzzles, but I believe it would be fast enough to be practical, as it only needs to run once.

If this is not sufficient, you could try optimizing it with A\* or D\* Lite. Neither of those would be very easy though in your situation because of the dynamic nature of the level.

# Answer
> 2 votes
Assuming that you have an online game with a non-trivial number of players.

Do note that the difficulty rating doesn't need to be fixed and unchangeable.

First, make any heuristic to roughly estimate the initial difficulty - any of your own simpler suggestions would work, don't put much time in it, anything that's somewhat sane would be enough.

Second, measure how your players behave on the existing levels (where you're sure of the difficulty rating) - what is the % of failures, time spent on the level.

Third, as soon as real, live players have played the new user-created puzzle a few times, ditch the initial estimate and update the difficulty according to how they behaved on that new puzzle - if the time/failure%/whatever is similar to the existing 4-star puzzles, label it with 4 stars, etc.

---
Tags: puzzle, difficulty
---


# Question
Title: pre-rendering light on texture based on bump map
Using a gray-scale bump-map and N sources of colored light, what is the algorithm to render the light on the textured surface, assuming I have the angle(s) and distance of each light source? (I am pre-rendering in software).

I have the part where it renders light based on the position and angle of light source. My question is twofold:

1. How do I decide on an RGB color based on multiple different light sources? Is it simply additive by nature?
2. What do I do about cases where the angle is not a sufficient way to determine intensity? For instance when there is a deep caveat in the surface and a higher elevated area is blocking the light to that lower shaded area? How do you handle something like that?

# Answer
1. Yes, you simply add them. Stupid explanation: x photons from source 1 go in, y photons from source 2 in, so x+y photons go out. Normally, these processes are independent of each other.
2. You can handle something like that by encoding visibility information into Spherical Harmonics. For a good explanation google for "Spherical harmonics gritty details". You would need to precalculate the visibility for each element of your bumpmap via raycasting\* and store it in coefficients for spherical harmonic base functions. This might not to fast, but  used it for real-time shadowing in volume rendering.

You would do this raycasting in the 2D bumpmap with Bresenhams algorithm:

Starting at the green pixel, you would traverse along the red line in direction of your lightsource until you would find a value that would indicate a collision (yellow). If you end outside the image, you have no collision and your light source is visible.

Kronander J, Jonsson D, Low J, Ljung P, Ynnerman A, Unger J. Efficient Visibility Encoding for Dynamic Illumination in Direct Volume Rendering. IEEE Trans. Vis. Comput. Graph. \[Internet\]. 2011 Feb 3;18(3):447–62. Available from:http://www.computer.org/csdl/trans/tg/2012/03/ttg2012030447-abs.html
> 2 votes

# Answer
The technique I think you are looking for to achieve this is known as Parallax Occlusion Mapping and is an extension of Parallax Mapping.

Parralax Occlusion Mapping is a technique to interpret which texel to pick based on the viewing angle relative to the surface normal while taking into account the surface displacement provided by the bump map. Keep in mind that when you know which texel to pick you also know which (u,v) point on the triangle surface is being viewed.

What you should interpret using this technique is the texture coordinate for the given triangle that is illuminated by a given light source projecting a ray in a specific direction. So from here you should be able to calculate the per-pixel lighting incident on a fixed surface for the purpose of light baking similar to how you would without the bump-map (whatever technique you are using for this).

This should suffice for baking your diffuse illumination for that surface into some data source (added on top of the standard colour texture maybe?). However, handling specular illumination may prove more of a challenge and possibly can only be done in real-time as it is dependant on the viewing angle/position as well as light and geometry information.

This technique is often used in real-time and isn't so expensive that it necessitates baking. Consider adding it as a real-time extension to your system first as you will probably need this long term for dynamic objects to fit well with the rest of the scene.
> 1 votes

---
Tags: textures, rendering, lighting, bump-map
---


# Question
Title: Switch character to play animation() in Unity3D using c#
I have two or more 2D character (Character A, B, n..). I made an animation on the character using the Animator class "AnimCharacter.cs". if i press the 'PgUp' character 'A' can call the function AnimCharacter.cs, when i press 'PgUp' again, character 'B' can call that function so the character A is in idle. I've tried to make the class "aktifChar" but still error. Everybody can help me ? Thanks

**"AnimCharacter.cs"**

```
using UnityEngine;
using System.Collections;

public class AnimCharacter : MonoBehaviour {
    public float maxSpeed = 10f;
    bool facingRight = true;
    Animator anim;
    bool grounded = false;
    public Transform groundCheck;
    float groundRadius = 0.2f;
    public LayerMask whatisGround;
    public float jumpForce = 700f;
    bool doubleJump = false;

    void Start () {
        anim = GetComponent<Animator> ();
    }

    void FixedUpdate () {
        try{
            grounded = Physics2D.OverlapCircle (groundCheck.position, groundRadius, whatisGround);
            anim.SetBool ("Ground", grounded);

            if (grounded)
                doubleJump = false;

            anim.SetFloat ("vSpeed", rigidbody2D.velocity.y);

            //if(!grounded) return;

            float move = Input.GetAxis ("Horizontal");
            anim.SetFloat ("Speed", Mathf.Abs(move));
            rigidbody2D.velocity = new Vector2 (move * maxSpeed, rigidbody2D.velocity.y);
            if (move > 0 && !facingRight)
                Flip ();
            else if (move < 0 && facingRight)
                Flip ();
        }catch{

        }
    }

    void Update(){
        if ((grounded || !doubleJump) && Input.GetKeyDown (KeyCode.UpArrow)) {
            anim.SetBool ("Ground", false);
            rigidbody2D.AddForce(new Vector2(0,jumpForce));

            if (!doubleJump && !grounded)
                doubleJump = true;
        }
    }

    void Flip(){
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;

    }
}

```

**aktifChar .cs**

```
using UnityEngine;
using System.Collections;

public class aktifChar : AnimCharacter {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Input.GetKeyDown (KeyCode.PageUp)) {
                 animation.Play("Running", PlayMode.StopAll);
        }
         }
}

```

*there is a image of the Animator :*

*the error is saying :* MissingComponentException: There is no 'Animation' attached to the "CharacterLamp" game object, but a script is trying to access it. You probably need to add a Animation to the game object "CharacterLamp". Or your script needs to check if the component is attached before using it. aktifChar.Update () (at Assets/Script/aktifChar.cs:14)

# Answer
Your script `aktifChar` is attached to an object that doesn't have an Animation component. That's why you're getting a `MissingComponentException` when you try to run this line: `animation.Play("Running", PlayMode.StopAll);`

You probably need to add a Animation to the game object "CharacterLamp". Or your script needs to check if the component is attached before using it.

You can check to see if the component exists with:

```
void Update () {
    if (Input.GetKeyDown (KeyCode.PageUp)) {
        if(this.gameObject.GetComponent<Animation>() != null) {
            animation.Play("Running", PlayMode.StopAll);
        }
    }
}

```
> 1 votes

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


# Question
Title: How can I programatically determine if I can create a hardware D3D device?
I have a D3D 11 application to which I would like to add support for software rendering. This is because in some circumstances it will be run on over remote desktop or on machines without GPUs. From the research I have done, it seems like my best bet is WARP.

It was surprisingly simple to change the app to use WARP:

```
hr = D3D11CreateDevice(
    NULL,
    D3D_DRIVER_TYPE_WARP, // was D3D_DRIVER_TYPE_HARDWARE
    NULL,
    creationFlag,
    featureLevels,
    ARRAYSIZE(featureLevels),
    D3D11_SDK_VERSION,
    &mDevice,
    &mFeatureLevel,
    &mDeviceContext
    );

```

It runs nicely. Where I'm struggling is determining *when* to set the driver type to WARP instead of hardware. Is there a function I can call that will tell me if hardware support is available on the system?

I'm using D3D 11 with the `9_1` feature level.

# Answer
> 3 votes
The proper way to determine if you can create a device of a particular type (hardware / software) with particular feature levels is to *attempt* to create a device with the options you want, and if that fails, fall back to a less-featured device. The documentation demonstrates this technique for feature level fallbacks, and you can apply a similar one for trying hardware versus WARP devices.

Note that this is *not* an "abuse of exceptions as flow control," per your comment, because D3D does not throw (C++) exceptions (being a COM API, which needs to run in C, it cannot). Failure to construct a device just returns a result code indicating that failure, and this is mechanically no different than checking the result of a "do I support hardware devices?" function.

Further, this technique is actually better since it eliminates a potential (although rare in practice in D3D's case) race condition: if you have a pair of functions, one for querying the available functionality and another for initializing said functionality, there is a period of time between the query call and the initialize call when the functionality could, for some reason, become unavailable. So you need to be checking the result of the initialize call anyway, therefore the first call is just redundant.

---
Tags: directx, software-rendering
---


title: Get GameObject to bounce of colliders

text:
# Question
Title: Get GameObject to bounce of colliders
I am making a Atari Breakout game with unitys 2d tools and I need to get the ball to bounce of colliders in the scene. If you havent played the game before how it works is if the ball hits the wall at 45 degrees it will bounce of the wall at the same angle (diagram bellow)

How can I get the ball to move at a continues speed and when it hits a collider to bounce back the way the image shows?

# Answer
What you need to do is two things: One, the ball has to have a rigidbody2d attached (the walls don't) and then create a PhysicsMaterial2d and experiment with the two values (I think you want friction: 0, bounciness: 1).
> 2 votes

# Answer
It depends if you want realistic physics or not. If realistic then like Garan said.

If not, and you want it to bounce exactly as it was and in the same speed:

Give the ball a 2D collider, and the wall a 2D collider. Make them both triggers. In OnTriggerEnter2D(Collider2D collider) inside the ball script, bounce the ball manually. Reverse the horizontal speed, and give it the same vertical speed (or the other way around depending on your orientation).
> 2 votes

# Answer
What you are looking to do here is reflect the velocity vector in the normal of the surface the ball has collided with. See here.

The equation is as follows;

Vnew = -2\*(V dot N)\*N + V

As pat mentioned you will need to make the wall and the ball a 2D collider and do this reflection in the OnTriggerEnter2D method. The normal of the collision will be defined as the direction from the ball center to the collision point.

Somethign like;

N = collider.contacts\[0\] - ballPosition.
> 1 votes

# Answer
Since all the surfaces are parallel/perpendicular, you just invert the x-direction when hitting a vertical surface *(or y-direction when hitting a horizontal surface)*

However, note that **this is not the way bouncing off the paddle works in Breakout** \- the outgoing angle is determined by where on the paddle the ball hits, not what the incoming angle was.
> 1 votes

---
Tags: 2d, unity, physics, unityscript
---


# Question
Title: How can I avoid texture stretching when adding high-resolution support via a mod?
I am currently working on recreating the game engine for an old game (Sacred) using the original game assets I reversed-engineered the formats of.

The game had a fixed 1024x720 resolution, and I'm planning to support higher resolutions. How can I support them without having to stretch textures? I am hoping for results like D2MultiRes mod (Diablo 2) or G3 widescreen mod (Infinity Engine games) achieved.

# Answer
I think the best approach would be to modify not just the resolution that the game runs at, but also the viewport and projection / field of view used by the game such that you effectively *increase the viewable area* beyond what was originally possible.

This could be a potential concern in games with competitive multiplayer modes. However, I don't recall Sacred having one of those.

I can't really tell you how to accomplish this specifically, since it will depend heavily on how Sacred itself was built. In general you are going to want to find where the resolution is set and modify that, and also where the viewport / projection matrices are defined and adjust those. You will likely need to adjust the positioning of various UI elements, and so on.

This appears to be the approach taken by the widescreen mod you linked, at least, and possible the D2 one as well (I didn't look at that one in as much detail).

However, while the above could be quiet a lot of work it's probably better than your other options, which are:

* Allow the textures to stretch, use a better-quality filtering method to hide the artifacts as much as possible (probably not what you want at all).
* Re-author the textures are a correspondingly-higher resolution. Not only is this a lot of artistic effort, I have strong reservations about suggesting it because of the potential increased risk of IP law complications.
> 1 votes

---
Tags: resolution, modding
---


title: iOS UDK Kismet Compare Vectors?

text:
# Question
Title: iOS UDK Kismet Compare Vectors?
I have created a control scheme identical to the UDK Jazz Jackrabbit tutorial.

Everything works as it should except I would like the Left Stick to control the character rotation when the Right Stick is not being pressed.

I'm terribly stumped here as don't know whether I should be comparing the vector output or the active/inactive input... nor do I honestly know how do this in Kismet :)

Any help would be greatly appreciated!

EDIT: I want the left stick to do both the movement and rotation... until the right stick is pressed. In Kismet, how do I override the left stick's input with the right stick when it is pressed? (for the rotation that is)

# Answer
> 1 votes
It's dirty... but it works. Hopefully in the future I'll find a better solution. IE build everything in UnrealScript.

---
Tags: ios, udk
---


title: Rotating a GameObject around its center

text:
# Question
Title: Rotating a GameObject around its center
I'm trying to rotate a `GameObject` that consists of several cubes around its center of gravity on an axis.

When using `transform.Rotate()`, it rotates around its pivot point (as shown in picture 1) and not its center of gravity as I want (picture 2). How can I achieve this rotation?

**Picture 1:**

**Picture 2:**

# Answer
Move your sub-components from the centre of mass to the pivot point:

1. Find the centre of mass of your object.
2. Compute the vector between your centre of mass and the pivot point of your object.
3. Use that vector to move your cubes so that the centre of mass of your object is at the same place of the pivot point of your object.
4. Perform your rotation. (Also rotate your computed delta vector.)
5. Replace the cubes with the negative delta vector you computed earlier.
> 2 votes

---
Tags: unity, rotation
---


# Question
Title: Rotate to a set degree then reverse and repeat in Unity
I'm making my first project in Unity, a simple game where touching objects adds points to the player's score.

I'd like the objects to have a pleasant back and forth swaying animation on the Z axis. Nodding to the right 30 degrees, then to the left 30 degrees, on and on.

Here's what I've got...

```
public class Rotator : MonoBehaviour
{
    void Update ()
    {
        transform.Rotate(new Vector3(0,0,12)*Time.deltaTime);
    }
}

```

This gives me a nice slow rotation. But I am clueless how to tell Unity to stop at +30 degrees, reverse to -30 degrees, rotate again to +30, stop and repeat, etc, etc.

I'd really appreciate any help. Maybe there is a thread like this that I was not able to find? I assume it will involve some kind of 'if then' function?

# Answer
> 2 votes
> This gives me a nice slow rotation. But I am clueless how to tell Unity to stop at +30 degrees, reverse to -30 degrees, rotate again to +30, stop and repeat, etc, etc.

I suggest you to use coroutines for that. There are several ways of course of doing that. The code could look more or less the following:

```
IEnumerator LoopRotation(float angle)
{
  float rot = 0f;
  float dir = 1f;
  while(true)
  {
    while(rot < angle)
    {
      float step = Time.deltaTime * rotSpeed;
      transform.Rotate(new Vector3(0,0,12)*step * dir);
      yield return null;
    }
    rot= 0f;
    dir *= -1f;
  }
}

void Awake()
{
  StartCoroutine(LoopRotation(30f))
}

```

# Answer
> 1 votes
Use a sine wave.

During the update method, get the elapsed total time and store that as a float. Feed it to a sine function and you'll end up with a value between -1 and 1 that oscillates between the two values; multiply it by thirty and you can rotate an object from -30 degrees to +30 degrees.

`float elapsed = Time.deltaTime;
float degrees = Mathf.Sin(elapsed) * 30.0f;`

That might move a little too quickly, however, so you could always create a new floating-point variable and just increment that slightly each frame. Then feed that to the sine function.

`Mathf.Sin(0) == 0.0;
Mathf.Sin(90) == 1.0f;
Mathf.Sin(180) == 0.0f;
Mathf.Sin(270) == -1.0f;`

I'm unfamiliar with how rotations are defined in unity, but I'll give it a go.

`float sineTime = Mathf.Sin(Time.deltaTime);
transform.Rotate(new Vector3(0, 0, 1) * sineTime * 30);`

I hope this is useful for you.

---
Tags: c#, unity, animation, rotation
---


# Question
Title: Why does rendering a gradiented shape leave gaps?
Sometimes when I am drawing objects that aren't 'linear' (e.g. rounded edges, circles, ellipses, diagonal lines, etc) I this weird effect of some pixels at certain points not getting drawn.

It's easier to show than explain: This image is created by the code below it. It's a block fading from blue to black. The same effect appears when only using one color. (Though it's otherwise obviously equivalent to just drawing a filled rectangle.)

```
float b = 100;
int steps = 100;
int thickness = 1;
int basex = 10;
int basey = 10;
int lenx = 200;
int leny = 200;
for(int idx = 0; idx < steps; idx++) {
    al_draw_rounded_rectangle(
            basex + thickness * (steps - idx), basey + thickness * (steps - idx),
            basex + lenx - thickness * (steps - idx), basey + leny - thickness * (steps - idx),
            RII, RII,
            al_map_rgba(0, 0, b - idx * (b / steps), alpha(0.0)),
            thickness);
}

```

Is there a term for this phenomenon? How do I prevent it from happening?

# Answer
> 0 votes
The cause of this "effect" is that I believe you are drawing the outline of a rounded rectangle, one rectangle inside the other. Is that correct? If so, what you are seeing is simply how Allegro I presume is handling round corners, specifically, it does not draw a thick pixelated line and leaves some pixels "missing" in the corners. When you draw multiple repetitions like you just have, the missinh pixels become more prominent than they would be if you only drew one outline (which is what I presume the function was intended for) and create the missing lines effect.

To put it in visual form:

This is what it's doing:

This is the behavior you are relying on / expecting:

If you stack many iterations of the former round corner you will/might get (a) missing line(s).

---
Tags: c++, 2d, rendering, allegro
---


title: What defines a minigame?

text:
# Question
Title: What defines a minigame?
A "minigame" (sometimes mini-game) is a rather common term used in game design and the general game industry. Therefore it has a definable scope, that is not opinion based, but rather established and tangible. However, I'm at a loss to define its scope. The wikipedia page says:

> "A minigame (also spelled mini-game or mini game and sometimes called a subgame) is a short video game often contained within another video game and sometimes in application software or on a display of any form of hardware. A minigame is always smaller or more simplistic than the game in which it is contained. Minigames are sometimes also offered separately for free to promote the main game. For instance, the Pokémon Stadium minigames involve merely pressing a few buttons at specific intervals, with little complexity."

When asked to define it, I guess loosely I'd consider a minigame any game that:

1. could easily be a self-contained game within another one
2. that *usually* shows all the information on the screen
3. could have been produced in the "dawning of gaming" (At least its mechanics)
4. that the average (perhaps even non-gamer) can sit down and instantly understand nearly all the game rules without having to "learn" them via play.

Some things to think about:

1. Is `Game_B` that has been included in another game, `Game_A`, still a minigame if it is later played or released independently from `Game_A`?
2. What if `Game_B` was originally independent, but `Game_B` (or clones) are now almost exclusively found as minigames within other games? Will `Game_B` always be a minigame after that?
3. Is pong a minigame - it most certainly has *been* a minigame?
4. Likewise, is chess a minigame (it matches my personal definition despite being incredibly complex logically)?

(I don't know if I can link pictures here, otherwise I would add some examples.)

***Answers should please be constructive and professional. Good answers should also give reasoning and cite sources when possible.***

# Answer
Here is how I would define a minigame:

> A minigame is a part of a bigger game that could be independent from it, but is not. Its gameplay mechanics are simple, mastering them doesn't require extended practice. The term is also sometimes used to present a regular game of limited scope.

It's true that some entire games are called minigames (for instance here), but the most common usage I've encountered in the context of game development is for games that are contained within *another* game. Calling an entire game a minigame is only a way of advertising it to potential players that are looking for a short session of gameplay (e.g. people googling "free flash mini game" are directed to freeflashminigames.com). This is why I'm putting this usage of the term in second position: here, we're talking about game *development*.

So according to my definition, and using only the strict game-developer-oriented part of it, the answers to your questions 1, 2, 3 and 4 are respectively no, no, no, and no.

The original Pong is a *game* (it was released standalone), a pong clone contained in MarioMare 2014 is a *minigame* (it's part of a collection sold as a whole, with some meta game mechanics gluing everything together).

Chess is not a minigame. It took centuries to develop, and takes a lifetime to master, so that clearly disqualifies it for the *mini* prefix, even if it comes included in another game.
> 2 votes

# Answer
IMO this is a really opinion based question and there is no exact definition of the term. To me, it's a bit similar to how different companies or individuals define "Alpha", "Beta", etc. You can't really nail down "what is an alpha version?". Same is true here...

Personally, I consider a mini game (as in: small game within another game) fulfilling the following conditions:

* **The game isn't a significant part of the product it is contained within, no matter whether it's another game, a TV, a mobile phone, etc.** For example, it's not the reason you bought the product itself. A standalone *Pong* clone you've bought wouldn't be a mini game. A *Pong* clone you can play as part of a loading screen would be considered a mini game.
* **The mini game significantly differs from the main product's gameplay (if both are games).** For example, in *Mass Effect 3* there are a few missions where you've got to steer a battle mech. While these sections differ from the more common third person shooter gameplay, it's still integral part of the game and very closely related (different abilities/perspect). A similar example would be classic "rail shooter passages" in first person shooters, such as the *Battlefield* series. *Final Fantasy VIII* included an optional card game called *Triple Triad*. While you could spend a significant amount of time with it, it offered completely different gameplay (trading card game over turn based rpg).

Some might disagree, but I consider the following points optional, although being *pro* mini game:

* **The game may be played at almost any time, but not necessarily standalone.** The mini game doesn't have to be available from the get-go. It also doesn't have to be repeatable indefinitely, although it's quite characteristic for some games, for example bonus games found in several Nintendo games.
* **The game can be disconnected from the main game, but doesn't have to** (i.e. they may interact in some way or anothers).

As for your questions:

* **Question 1:** No, I don't consider future iterations of **Game\_B** to be mini games if they're standalone (even if their complexity is rather low).
* **Question 2:** No. To me it always depends on whether the game is the actual product or just some part of it. You can call it a "mini game" if it's rather simple or minimalistic, but it's not a typical "mini game" for me.
* **Question 3:** No. It's been used as a mini game in some other games, but it's still a standalone concept (although minimalistic).
* **Question 4:** No, not at all. Especially considering chess to be more complicated and time consuming than like 90%+ of all mobile games that aren't considered "mini games" in any case. ;)

So what makes a mini game a mini game? Personal opinion. IMO even the term itself isn't fixed. A mini game can be some sub game being embedded in some other product, but it can as well be just a very simple and minimalistic game.
> 1 votes

# Answer
The term *mini* in *minigame* implies that there is something tightly coupled to the minigame itself that makes it *mini* (i.e. you have to compare it to something directly). Therefore, a minigame can only exist while coupled to another, bigger game. Normally, this coupling is present in the form of the minigame being part of the bigger game (the bigger game depends on the minigame, not the other way around).

The term *game* in *minigame* implies that the minigame has its own standalone rules that do not depend on the bigger game's rules. Therefore, you could always take it out of its context, and still have a playable game. Note, that at this point, the minigame becomes a game, since it loses its coupling with the original, bigger game.

In short, a minigame is a game with well defined rules, that is part of a bigger game, but does not depend on the rules of the bigger game to allow itself to be played.
> 1 votes

# Answer
**mini (ˈmɪnɪ)**
*Something that is distinctively smaller than other members of its type or class.*

A mini game is a game that is very small.

---

It doesn't matter whether it is part of another game or not, but due to the small size it is usually not worth to release it stand-alone and very well suited to be used as such.
> -1 votes

---
Tags: terminology
---


# Question
Title: Destroying non-monobehaviour derived classes
I'm building an inventory system with different items classes deriving from a 'Item' base class.

When an inventory slot runs out of the item it holds I want the item to be destroyed. I cannot null the inventory slots reference to it, and I cannot destroy it. How are non-monobehaviour classes supposed to be handled in Unity? Any tips on how I can get rid of the used up item?

# Answer
> 1 votes
If you do not wish to subclass MonoBehavior and still wish to Destroy the objects, you should use ScriptableObjects:

http://docs.unity3d.com/Documentation/ScriptReference/ScriptableObject.html

> **ScriptableObject**
>
> A class you can derive from if you want to create objects that don't need to be attached to game objects.
>
> This is most useful for assets which are only meant to store data.

You can call Destroy on them.

If you do not do this, then anything else gets managed by the GC in the same way as any other object in a non-Unity project. Just remove all references to that particular object.

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


title: Infinite / Treadmilling Hexagonal Grid

text:
# Question
Title: Infinite / Treadmilling Hexagonal Grid
So, I can happily render an infinite square grid by moving said grid whenever the camera moves out of a grid square,

```
auto diff = (cameraTranslation - gridTranslation);
bool moveGrid = false;

if (diff.x > cellSize.x / 2)
{
    gridTranslation.x += cellSize.x;
    moveGrid = true;
}
else if (diff.x < -cellSize.x / 2)
{
    gridTranslation.x -= cellSize.x;
    moveGrid = true;
}

if (diff.z > cellSize.z / 2)
{
    gridTranslation.z += cellSize.z;
    moveGrid = true;
}
else if (diff.z < -cellSize.z / 2)
{
    gridTranslation.z -= cellSize.z;
    moveGrid = true;
}

if (moveGrid)
    gridTransform.Translate(gridTranslation);

```

However, when working with a hexagonal grid, things get a bit more complicated. (For that matter, if the grid was textured, I'd have to adjust the grid translation based on the tessellation distance... ouch.)

In this case, I'm dealing with a wireframe hex grid:

And I'm a little unsure how to treadmill in this case.

The first thing that comes to mind is that, given that the camera starts in the center of a hexagon, determine if the camera has exited the cell in which it started. If so, adjust grid position by

```
float angle_from_center = atan2(camera.z-grid.z,camera.x-grid.x);
grid.x += cell_size.x * cos(angle_from_center);
grid.z += cell_size.z * sin(angle_from_center);

```

Which will probably work, but the issue gets more complicated when considering that I'm not only checking if the camera has moved a certain distance from the cell center, but if it has crossed a border.

I could clamp the angle of the camera relative to the cell origin to 1/12 of a circle, which would make hex boundary calculation easier, but this seems like a hack.

Any suggestions? I'm 75% sure I'm over thinking this one.

# Answer
Thanks to everyone for the advice.

I spent a few minutes with a notebook and found a suitable tessellation cell for a hex grid:

or, in context:

Note: It doesn't really matter if this is centered on a cell - if your grid is composed of regular hexagons, you can slice it into cells this size starting anywhere you want. Hooray for tessellations. My example below adjusts the grid every time the camera leaves a single cell, but as long as your using an integer multiple of the cell size, it should work fine.

The cell dimensions are:

```
   width = 2 * radius * sqrt(3)
   height = 3 * radius

```

If there's anything special - textures, etc. - on your grid, you'll want to track how far the grid has moved and offset your texture coordinates accordingly.
> 5 votes

---
Tags: opengl, tessellation
---


# Question
Title: Vertexquads are not being drawn in 2D space
I started teaching myself DirectX a short time ago and have come across a problem which I can't figure out by myself unfortunately. I'm trying to build my own font system, so I can draw strings in 2D screenspace. Until now Until now I have managed to create a function to which I just have to pass the string and the screenspace-positions., and it generates all vertices for / sets up the buffers etc (quads that i draw a certain portion of the font texture on). When I draw these vertices in 3D space, everything looks like it works like it should be.

(Forgot to hide the cube) As soon as I try to switch to 2D, I just get a window filled with the blue backgroundcolor. To switch to 2D I do the following things:

```
graphics.context->ClearDepthStencilView(graphics.depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0);
context->OMSetDepthStencilState(depthDisabledStencilState, 1);

WVP = XMMatrixOrthographicLH((float)mWidth, (float)mHeight, 0.0f, 1.0f);
cbPerVert.WVP = XMMatrixTranspose(WVP);
cbPerVert.World = XMMatrixTranspose(World);

context->UpdateSubresource( cbPerVertexBuffer, 0, NULL, &cbPerVert, 0, 0 );
context->VSSetConstantBuffers( 0, 1, &cbPerVertexBuffer );

```

My Question is now what I am doing wrong here. If the vertices are being genrated and drawn correctly, afaik all I have to do is project them into screenspace and disable the depth buffer, which I did here.. BTW: I randomly tried drawing the cube with my 2D settings and it was properly drawn.. Help is much appreciated :)

# Answer
So the problem was the culling, I recommend to debug your code while turning off the culling with D3D11\_CULL\_NONE flag in the rasterizer if your geometry does not get displayed, this is quite a common problem for beginners. And be sure to cull the backfaces in a release application wherever you can.
> 0 votes

---
Tags: c++, 2d, graphics, directx11
---


# Question
Title: How do I create a World Healing Wave effect?
I want to change my *dark and depressing background* to a *happy grassy background*, in real-time, such that the happy background is shown in a radius around a game character.

A **forcefield of happiness**, if you will.

How can this be done as performantly as possible when rendering to a canvas in a custom view?

---

**UPDATE:** Here's how it works in my head:

```
    private int hModeX, hModeY;
    private float hModeRadius = 0.1f;
    private float hModeStart = 0;
    happyModeBg = Bitmap.createScaledBitmap(happyModeBg, getWidth(),getHeight(), true);
    hModeX = getWidth()/2;
    hModeY = getHeight()/2;

private void initHappyMode(Canvas canvas){
    hModeRadius = 75 * thread.getDelta();

    if(hModeRadius > 500) {
        hModeStart = timestep; //What is timestep?
    }

    //context.arc(x, y, radius, 0, 2 * Math.PI, false); <- your version
    canvas.save();
    canvas.drawArc(oval, startAngle, sweepAngle, useCenter, paint) // <- my version
    //context.clip(); <- dont know what this does or if there is an equivilant
    canvas.drawBitmap(happyModeBg, 0, 0, null);
    canvas.restore();
    //requestAnimationFrame(step); <- dont know what this does since I cant seem to find it for android

}

```

I'm using `canvas.drawArc()` to make a circle, but I'm definitely missing something.

# Answer
# Demo

<sup>*GameDev Meta: Henshin Main!!* :D</sup>

The code uses a `canvas` `clip` region and `requestAnimationFrame` for maximum quality and efficiency. (It's better live.)

I assumed you meant HTML `canvas`! Even if you didn't, other rendering engines (such as Android's 2D rendering pipeline, which you might have meant) also support hardware-accelerated clip regions. The code will likely look similar.

Requesting animation frames with `requestAnimationFrame` (or another platform's provided solution) results in higher-quality animation by letting the engine determine render timing.

This renders smoothly on a low-range netbook and on my Android phone.

# Explanation

To make this more generally useful, let's really understand *clipping*.

Let's say we have these two rectangles:

Clipping works just as well on lines, points, images or anything else you might want to render. I'm just sticking to rectangles for simplicity.

We don't want the red rectangle to be visible here (black circle) at all.

So we can instruct the renderer to *clip* the red rectangle by that circle.

In other words, when the red rectangle is drawn, it is drawn everywhere except where that black circle would have been.

Different renderers have different ways of specifying what region to clip by. In JavaScript, with the HTML `<canvas>`, I did essentially

```
// Draw the blue rectangle

context.save(); // Save the current state of the graphics context,
                // so we can go back to it.

// Draw the black circle
context.clip(); // Tell the renderer that was our clip region,
                // since the last `context.save()`.

// Draw the red rectangle.
// It will appear clipped by the black circle.

context.restore(); // Tell the renderer we should restore all
                   // the clipping settings back to what they were
                   // `context.save`d as.

// From here on, nothing is clipped anymore.

```

Now, in an Android `Canvas`, you'll want to be doing a similar thing, but the renderer expects slightly different code:

```
// Draw the blue rectangle

canvas.save(); // Same idea as above -- just setting a point we can
               // restore to later.

// Now, `canvas.clipPath` expects a `Path` object.
// Let's create one that contains a circle.
Path path = new Path();
path.addCircle(100, 100, 100, Direction.CW);
canvas.clipPath(path);

// Draw the red rectangle
// It will be clipped by the circle defined in the `path` that we
// used as the `clipPath`.

canvas.restore(); // Aaaand restore the state.

// Things drawn here won't be clipped anymore.

```

Android documentation on the matter might be handy. There are good questions like this one on StackOverflow about more things you might want to try with it.
> 20 votes

# Answer
Working implementation using Ankos method:

```
canvas.drawBitmap(depressingBg, 0, 0, null);
canvas.save();
radius += 400*thread.getDelta(); // expansion speed
Path path = new Path();
// draw around player position
path.addCircle(player.x, player.y, radius, Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(happyBg, 0, 0, null);
canvas.restore();

```

Thanks to Anko for all the help!
> 3 votes

---
Tags: java, 2d, android, special-effects, clipping
---


# Question
Title: Why does this code to filter events with SDL not function properly?
According to the SDL2 wiki,

> SDL\_SetEventFilter : Use this function to set up a filter to process all events before they change internal state and are posted to the internal event queue.
>
> void SDL\_SetEventFilter(SDL\_EventFilter filter, void\* userdata)
>
> The function prototype for filter is: int YourEventFilter(void\* userdata, SDL\_Event\* event)

And so, my code as follows is:

\`

```
#include <SDL.h>
#include <stdio.h>
#include <memory>

//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int isMouseEvent(SDL_Event* ev);

int main(int argc, char* args[])
{

    SDL_Event ev;

    //The window we'll be rendering to
    SDL_Window* window = NULL;

    //The surface contained by the window
    SDL_Surface* screenSurface = NULL;

    //Initialize SDL
    if (SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
    }
    else
    {

        //Create window
        window = SDL_CreateWindow("SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (window == NULL)
        {
            printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
        }
        else
        {

            bool black = false;

            //Get window surface
            screenSurface = SDL_GetWindowSurface(window);
            SDL_SetEventFilter(isMouseEvent);
            bool isOn = true;
            while (isOn)
            {
                //Pump events
                SDL_PumpEvents();

                SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));

                //Update the surface
                SDL_UpdateWindowSurface(window);
            }
        }
    }
    //Destroy window
    SDL_DestroyWindow(window);

    //Quit SDL subsystems
    SDL_Quit();

    return 0;
}

int isMouseEvent(SDL_Event* ev)
{
    if(ev!=NULL) {
        if (ev->type == SDL_MOUSEMOTION)
            return 0;
    }
    return 1;
}

```

However, when the code is ran no events are filtered, every event passed to isMouseEvent() is null. The SDL2 Wiki is very bare, and the examples on using SDL\_SetEventFilter are very basic and do not work properly. Any ideas as to where I should go from here, seeing as the events are constantly null when checked from the isMouseEvent() function?

# Answer
void pointers cannot simply be omitted. Feel free to pass NULL, though.
> 1 votes

---
Tags: c++, sdl, events
---


# Question
Title: Where to put my entity component messaging functionality?
I've done my research and read as many articles and posts on messaging and ECS's as I could find to help me get mine working. However, I'm at a roadblock on how to get my messag functionality to be handled correctly.

A little information on my ECS system.

Pieces:

**Entities** \- Generic objects that only contains a list of attached components, has a few methods to ask if it has certain components and to retrieve them.

**Components** \- Only holds data specific to their nature and all have a bitMask denoting the component type.

**Systems** \- Functionality code specific to their nature and keeps a list of components it will process.

**Messages** \- Messages are currently created via the MessageInfo class. A message can be created easily using this line of code:

```
MessageInfo* msg = new MessageInfo(MESSAGE_TYPE, LISTENER_ENTITY, boost::ANY PARAMS);

```

I am trying to keep things decoupled as possible and have thought about adding a static MessageCenter that I can push messages to which will then either dispatch them immediately or throw them into a queue (depending on the push function call).

Example being that a message is created and pushed to the message center. The message center then immediately looks through its map of systems that care about X message and dispatches the message to a "RecieveMessage" method that's inherent to all systems. This approach sounded really good to me, so I started to develop it on paper and ended up running into a wall.

Let me put forth one of the scenario's I ran up against.

**Scenario:**

I have a text label entity being used as a % indicator with the position (x/y coords) component and text component (string, font size, etc). I want to alter some data properties of this entity, such as the text displayed and its color.

Since I know that all systems have a recieveMessage method I am quickly able to encapsulate functionality specific to those types of requests as shown below.

```
void SOMESYSTEM::RecieveMessage(MessageInfo* messageInfo)
{
    switch(messageInfo->GetMessageType())
    {
    case MessageType::CHANGE_TEXT:
        {
            boost::any params = messageInfo->GetParams();
            if(params.type() == typeid(std::tuple<BaseComponent*,std::string>))
            {
            auto param = boost::any_cast<std::tuple<BaseComponent*,std::string>>(params);
            TextComponent* textComponent = static_cast<TextComponent*>(std::get<0>(param));
            textComponent->SetTextString(std::get<1>(param));
        }
    }break;
case MessageType::CHANGE_TEXT_COLOR:
    {
        boost::any params = messageInfo->GetParams();
        if(params.type() == typeid(std::tuple<BaseComponent*,sf::Color>))
        {
            auto param = boost::any_cast<std::tuple<BaseComponent*,sf::Color>>(params);
            TextComponent* textComponent = static_cast<TextComponent*>(std::get<0>(param));
            textComponent->SetCurrentColor(std::get<1>(param));
            }
        }break;
    }
}

```

The wall I run into is where do I put this functionality? Currently the only system that touches text components is my RenderTextSystem. It wouldn't seem proper to implement that RecieveMessage function wanting those specific messages. That system just draws the text to the screen. I could be over-engineering here though.

I have other scenarios similar to this and figured if I could solve this one, I could end up solving 99% of the others.

# Answer
> 2 votes
Put this functionality wherever you want. Sure strict and "pure" ECS says don't put things in your components in order to avoid OOP. This usually just hinders everyone still learning from thinking about how to write useful code.

You clearly understand how to implement a form of messaging, so just use it and don't waste time trying to adhere to some arbitrary design pattern. This functionality can be placed into components, the game object itself, engine systems, or anywhere else.

Messaging is just a generic way to send data from one place to another. Usually a great benefit for first implementations of messaging is to try and cut down on file inclusions and inter-file dependencies.

---
Tags: c++, component-based, messaging, entity
---


# Question
Title: Efficient way of loading wavefront models in openGL game
In my game, a RTS game, the units are all wavefront obj. all their animation frames are each seperate wavefront obj file. ie. without any skeletal animation; fully rigid models. So when many units are loaded before a game starts, it takes too much time. for example, if 20 types of units are loaded, they take approximately 700/800MB in memory, take atleast 3 minutes to load.

*Can it be done in an efficient way somehow?*

**Solutions I have already used:**

* As obj parsing take too much time. I have stored each obj as memory dump and load that dump. This helped a lot atleast reduced to 3min from 10min, for above example.

**Further Possible solution I tried:**

* I tried loading the anination frames on runtime, when they are accesessed. But this is making the game slow at some crucial time. Like when fighting, all units' fighting frames are loaded together. thus making the game slow.
* loading the units in different threads. Makes no improvement

# Answer
> 2 votes
800 MB / 3 minutes = 4.4 MB/sec—a far cry from peak disk bandwidth, which is in the hundreds of MB per second (exact value depends on what kind of disk interface you have). So you're definitely not saturating I/O bandwidth. You should be able to load 800MB into memory in a few seconds.

You mentioned converting from .obj to a binary representation, but it sounds like you still have many small files. A standard solution for I/O issues is to put all the units/frames into one large file and load the whole thing in one go, rather than loading many small files. This will reduce disk seek time and allow disk caching to work better. You should see much higher I/O bandwidth this way.

---
Tags: opengl, models, loading, obj, model-loader
---


# Question
Title: How do I avoid interpolation artefacts when scaling up a heightmap?
I am using a bicubic interpolation algorithm in order to upscale a height map, and I am noticing some artifacts around the pixels boundaries. However, these artifacts don't seem to appear when I use a simple cubic interpolation (spline).

Could it be because the bicubic interpolation doesn't guarantee the second derivative to be continuous, unlike the cubic spline ? If so, is there known algorithms that have a continuous second derivative ? Otherwise, is there a way to deal with these artifacts ?

Linear interpolation (shows the pixels boundaries):

Bicubic interpolation (artifacts visible at pixels boundaries):

Cubic interpolation (no noticeable artifacts):

I tried several bicubic formulas, which gave me the same results. Here are some examples:

# Answer
> 5 votes
In Ken Perlin's paper on improved noise, he mentions a very similar problem. The cubic used in the original noise paper creates discontinuities at the integer boundaries due to the properties of its derivatives. In his revised paper, he proposes an interplant of `6t^5 - 15t^4 + 10t^3` to address those issues.

# Answer
> 4 votes
I made some searches and found that B-Spline have a continuous C2. I implemented it and it looks fine, even if it's an approximation and not an interpolation (it doesn't go through the samples).

B-spline (approximation):

---
Tags: c++, mathematics, interpolation, splines
---


# Question
Title: Inertia Tensor and World Coordinate conversion
I understand that the inertia tensor is basically a 3x3 matrix. I'm modelling a cube, and the inertia tensor for this shape has values for moment of inertia on the main diagonal of the matrix. All the products of inertia are zero.

However, I understand that this matrix only makes sense in body (i.e., local) coordinates. That is if I have a cube and rotate it, its local coordinate axes rotate with it and the inertia tensor remains constant. However, I need to represent the inertia tensor in **world coordinates** as well. How can I do that? Do I need to multiply it by the current orientation? I'm using quaternions for orientation, so I can extract a matrix from the quaternion (a 4x4 matrix, and if I get rid of the fact that a 4x4 matrix represents homogeneous coordinates I could convert it into a 3x3. To do this I would simply get rid of the rightmost column and bottommost row of the 4x4 matrix returned from the quaternion).

I hope this is making some sense. I suspect that the values of the inertia tensor in world coordinates will change as the orientation of the cube changes.

Is my logic correct? Formulas would be helpful.

Cheers,

Mark

# Answer
Yes, you can transform the inertia tensor from one coordinate system to another. This can be done by multiplying the inertia tensor by the inverse of the desired coordinate transformation on the right, and the inverse transpose of the coordinate transformation on the left. (This assumes column-vector math; if using row-vector math, reverse the order.)

In other words,

```
worldInertiaTensor = transpose(inverse(localToWorld)) *
                        localInertiaTensor *
                        inverse(localToWorld);

```

You can see why this is correct as follows. The way the inertia tensor works is that you multiply it on both sides by a unit vector `localAxis` to get the object's moment of inertia about that axis. That is,

```
momentAboutA = transpose(localAxis) * localInertiaTensor * localAxis;

```

(Here I'm treating `localAxis` as a column vector, so transposing it gives a row vector.) If we have the axis in world space instead, we have to transform it to local space before putting it into this equation. That involves the inverse of the local-to-world matrix:

```
momentAboutA = transpose(inverse(localToWorld) * worldAxis) *
                 localInertiaTensor *
                 (inverse(localToWorld) * worldAxis);

```

and rearranging that a little bit gives

```
momentAboutA = transpose(worldAxis) *
                 (transpose(inverse(localToWorld)) *
                  localInertiaTensor *
                  inverse(localToWorld)) *
               worldAxis;

```

and you can see from this that the term in parentheses in the middle is the world-space inertia tensor, since multiplying it on both sides by `worldAxis` gives the correct moment of inertia.
> 5 votes

---
Tags: physics, quaternion
---


# Question
Title: Find out which way to rotate based on current rotation and final rotation
I have one object that I want to rotate to a certain angle with 'smooth' rotation. I looked up on how to solve that and I came up with this:

But how do I know in what way to rotate, positive or negative? According the the picture on ex. 1, I need to rotate positively because it is the closest way for me to rotate. And on the second it is the negative way. But how do I know this? I've tried several solutions but I can't seem to find anything that is correct.

# Answer
There are different ways to represent angles and you didn't mention which you use. So let's assume that you represent the directions of angles measured in Radiants between 0π and 2π and any angles outside of that allowed range are automatically transformed back into it by adding/subtracting 2π until they fit again.

When the difference between this.angle and other.angle is less than 1π, the case is trivial.

```
 if (this.angle > other.angle) {
      this.angle -= TURN_SPEED;
 } else {
      this.angle += TURN_SPEED;
 }

```

But this obviously doesn't work when the two angles are close to each other, but on different sides of the 0-angle, like on 1/4π and 7/4π. But you can detect that case by checking the difference between the angles. When it's the case, it will always be larger than 1π. That means when the difference is \> π, you just need to invert the direction.

```
if ( abs(this.angle - other.angle) < PI) {
     if (this.angle > other.angle) {
        this.angle -= TURN_SPEED;
    } else {
        this.angle += TURN_SPEED;
    }
} else {
     if (this.angle > other.angle) {
        this.angle += TURN_SPEED;
    } else {
        this.angle -= TURN_SPEED;
    }
}

```
> 2 votes

---
Tags: rotation
---