# Question
Title: Why am I seeing unbounded memory usage in my WP8 game?
I recently upgraded to VS2012 and tried my game out on the new WP8 emulators. I was dismayed to find out the emulator now crashes and throws an out of memory exception during my sprite loading procedure (it still works in WP7 emulators and on my WP7).

Regardless of whether the problem is the emulator or not, I want to get a clear understanding of how I should be managing memory in the game.

My game consists of a character that has 4+ different animations. Each animation consists of about 4 to 7 frames. On top of that, the character has up to 8 stackable visualization modifications (eye type, nose type, hair type, clothes type, et cetera). Prior to my memory issue, I preloaded all textures for each animation frame and customization and created animate action out of them. The game then plays animations using the customizations applied to that current character.

I revisited this implementation when I received the out of memory exceptions and have started playing with `RenderTexture` instead, so instead of pre-loading all possible textures, it on loads textures needed for the character, renders them onto a single texture, from which the animation is built. This means the animations use 1/8th of the sprites they were before. I thought this would solve my issue, but it hasn't.

Here's a snippet of my code:

```
var characterTexture = CCRenderTexture.Create((int)width, (int)height);

characterTexture.BeginWithClear(0, 0, 0, 0);
// stamp a body onto my texture
var bodySprite = MethodToCreateSpecificSprite();
bodySprite.Position = centerPoint;
bodySprite.Visit();
bodySprite.Cleanup();
bodySprite = null;
// stamp eyes, nose, mouth, clothes, etc...

characterTexture.End();

```

As you can see, I'm calling `CleanUp` and setting the sprite to `null` in the hope of releasing the memory, though I don't believe this is the right way, nor does it seem to work.

I also tried using `SharedTextureCache` to load textures before stamping my texture out, and then clearing the `SharedTextureCache` with:

```
CCTextureCache.SharedTextureCache.RemoveAllTextures();

```

But this didn't have an effect either.

I used VS to do a memory profile of the emulation causing the crash. Both WP7.1 and WP8 emulators peak at about 150mb of usage. WP8 crashes and throws an out of memory exception.

Each customisation/frame is 15kb at the most. Lets say there are 8 layers of customization (120kb) but I render then onto one texture which I would assume is only 15kb again. Each animation is 8 frames at the most. That's 15kb for 1 texture, or 960kb for 8 textures of customization. There are 4 animation sets. That's 60Kb for 4 sets of 1 texture, or 3.75MB for 4 sets of 8 textures of customisation.

So even if its storing every layer, its 3.75MB. That's nowhere near the 150mb breaking point my profiler seems to suggest.

WP 7.1 Memory Profile (max 150MB)

WP8 Memory Profile (max 150MB and crashes)

Why might I be seeing this behavior?

# Answer
First, try to avoid creating objects on every loop/frame. I hope the statement `var characterTexture = CCRenderTexture.Create((int)width, (int)height);` is in an init, and not in the `visit()` or `draw()` methods of an object which inherits CCObject.

Second... WP8 seems to be unbelievably slow when working with arrays, lists, maps, dictionaries, hash tables etc. If you're not using complex data structures, you should write your own classes for dynamic lists or hash tables. As a general rule (because it seems destructors are weird on WP8), in your dynamic data structures try not to deallocate anything unless you reinitialize something, or shutdown the app. I think you might find some decent implementations online, to quicken the replacement process.
> -1 votes

---
Tags: xna, cocos2d, windows-phone-7, windows-8
---


# Question
Title: Isometric displaying two different images in different positions
I'm creating a simple Isometric game using HTML5 and Javascript, but I can't seem to get the display to work, at the moment i have 9 tiles that have X and Y positions and the player has a X and Y position, the players X and Y properties are set to 100, and the tiles are as shown

```
tiles[0] = new Array(3);
tiles[1] = new Array(3);
tiles[2] = new Array(3);
tiles[0][0] = new point2D( 100, 100);
tiles[0][1] = new point2D( 160, 100);
tiles[0][2] = new point2D( 220, 100);
tiles[1][0] = new point2D( 100, 160);
tiles[1][1] = new point2D( 160, 160);
tiles[1][2] = new point2D( 220, 160);
tiles[2][0] = new point2D( 100, 220);
tiles[2][1] = new point2D( 160, 220);
tiles[2][2] = new point2D( 220, 220);

```

Now I use this method to work out the isometric position

```
function twoDToIso( point )
{
var cords = point2D;
cords.x = point.x - point.y;
cords.y = (point.x + point.y) / 2;
return cords;
}
point2D is

function point2D( x, y)
{
this.x = x;
this.y = y;
}

```

Now this i'm sure does work out the correct positioning, but here is the output Isometric view

I just need to move my player position a tiny bit, but is that the best way to display my player position in the right position?

Canvas

P.S. the tile width is 120 and height is 60 and the player is width 30 by height 15

# Answer
Hrm, I don't know if this would manifest itself as a huge problem given the simplicity of the objects, but shouldn't

```
var cords = point2D;

```

be something like

```
var cords = new point2D();

```

I think you're actually returning the constructor function with the attribute attached each time which is a static thing, rather than an instance thing.

In terms of coordinates and isometric transforms, i'd encourage a read through http://www.wildbunny.co.uk/blog/2011/03/27/isometric-coordinate-systems-the-modern-way/ which has some pretty simple transformation logic (to/from screen space/grid space).
> 1 votes

---
Tags: 2d, javascript, html5, isometric
---


# Question
Title: Obtain rectangle indicating 2D world space camera can see
I have a 2D tile based game in XNA, with a moveable camera that can scroll around and zoom.

I'm trying to obtain a rectangle which indicates the area, in world space, that my camera is looking at, so I can render anything this rectangle intersects with (currently, everything is rendered).

So, I'm drawing the world like this:

```
  _SpriteBatch.Begin(
                SpriteSortMode.FrontToBack,
                null,
                SamplerState.PointClamp,        // Don't smooth
                null, null, null,
                _Camera.GetTransformation());

```

The `GetTransformation()` method on my Camera object does this:

```
    public Matrix GetTransformation()
    {
        _transform =
           Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
           Matrix.CreateRotationZ(Rotation) *
           Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
           Matrix.CreateTranslation(new Vector3(_viewportWidth * 0.5f,
               _viewportHeight * 0.5f, 0));
        return _transform;
    }

```

The camera properties in the method above should be self explanatory.

How can I get a rectangle indicating what the camera is looking at in world space?

# Answer
> 1 votes
Ok, so here's what seemed to do the trick:

```
 Rectangle CameraWorldRect = new Rectangle(
                Convert.ToInt32(_Camera.Pos.X - ((Window.ClientBounds.Width / 2) / _Camera.Zoom)),
                Convert.ToInt32(_Camera.Pos.Y - ((Window.ClientBounds.Height / 2) / _Camera.Zoom)),
                Convert.ToInt32(Window.ClientBounds.Width / _Camera.Zoom),
                Convert.ToInt32(Window.ClientBounds.Height / _Camera.Zoom));

```

Reduced CPU usage 3% by not drawing unnecessary tiles, happy days.

---
Tags: xna, c#, 2d, xna-4.0, camera
---


# Question
Title: Generating and rendering not point-like particles on GPU
Specifically I'm talking about particles as seen (for example) in the UE4 dev video here. They're not just points and seem to have a nice shape to them that seems to follow their movement.

Is it possible to create these kinds of particles (efficiently) completely on the GPU (perhaps through something like motion? Or is the only (or most efficient) way to just create a small particle texture and render small quads for each particle?

# Answer
> 2 votes
It is possible to efficiently create those particles on the GPU, The various effects are all very unique though, and mixed together to form one "effect" at times. Meaning you would have to have multiple different shaders/materials/etc for each effect. You could probably find all you need to recreate it online but it's going to be scattered and split on various websites in tutorials covering one single effect, or possibly just basics of the one effect.

The initial demonstration of one particle effect is when the glowing hammer hit's the ground. The sparks coming off of that resemble the particle-emitting spheres later on as-well. I would guess that would be done by rendering points (maybe short lines), with carefully adjusted colors. Since it's being done on the GPU, having the thousands of particles gives it that realism. They mention Vector Displacement for the physics. Otherwise, a fairly basic particle system, from what I could see.

Then there's also one later, the room filled with a bit fog. Which is used again for the lava pit just after. That's, "Volumetric Particles", as they called it. I personally would refer to it as a, "smoke simulation", or "fluid simulation", if I had to put a term to it. But that would be because I first saw such an effect in Blender3D. Which uses the Wavelet Turbulence for Fluid Simulation. Providing various densitys, and colors, to give a different appearance. Although, Unreal did have some fairly impressive lighting calculations in there.

If your asking if/how you personally can implement it, then the short answer is no. The more realistic answer is, by the time you found all the learning sources, learned the specifics of the advanced material, worked out the program flow, the project timeline, programmed it, debugged, and optimized it, it'll be old technology that someone will have been made free/open-source by that point.

---
Tags: particles
---


# Question
Title: Problem with SAT collision detection overlap checking code
I'm trying to implement a script that detects whether two rotated rectangles collide for my game, using SAT (Separating Axis Theorem). I used the method explained in the following article for my implementation in Google Dart.

2D Rotated Rectangle Collision

I tried to implement this code into my game. Basically from what I understood was that I have two rectangles, these two rectangles can produce four axis (two per rectangle) by subtracting adjacent corner coordinates.

Then all the corners from both rectangles need to be projected onto each axis, then multiplying the coordinates of the projection by the axis coordinates (`point.x*axis.x+point.y*axis.y`) to make a scalar value and checking whether the range of both the rectangle's projections overlap. When all the axis have overlapping projections, there's a collision.

First of all, I'm wondering whether my comprehension about this algorithm is correct. If so I'd like to get some pointers in where my implementation (written in Dart, which is very readable for people comfortable with C-syntax) goes wrong.

Thanks!

**EDIT:** The question has been solved. For those interested in the working implementation: Click here

# Answer
> 2 votes
One of your problems is the overlap checking code;

```
if (aMin <= bMin&& bMin <= aMax)
  return true;
if (aMin <= bMax&& bMax <= aMax)
  return true;

```

it looks like it misses the case where the range of 'a' lies entirely inside the range of 'b' (i.e. bMin \< aMin AND bMax \> aMax). A simpler approach is to check for a gap (non-overlap);

```
if (aMax < bMin || bMax < aMin)
  return false; //no overlap
else
  return true; //yes overlap

```

---

I don't think this is a bug, but your projection code is needlessly complicated. You just need to project p on to v. To do this you just need the dot product of p & v. So replace your code from the projection function below,

```
  //remove this code
  num proj = (p.x*v.x+p.y*v.y)/(Math.pow(p.x,2)+Math.pow(p.y,2));
  num x = proj*v.x;
  num y = proj*v.y;

  num val = (x*v.x)+(y*v.y);
  //end remove

```

with

```
   num val = (p.x*v.x)+(p.y*v.y); //dot product of p & v

```

There is no need to normalize(divide by length) vector v.

---
Tags: collision-detection, algorithm
---


# Question
Title: How to divide hex grid evenly among n players?
I'm making a simple hex grid based game, and I want the map to be divided evenly among the players. The map is created randomly, and I want the players to have about equal amount of cells, with relatively small areas. For example, if there's four players and 80 cells in the map, each of the players would have about 20 cells (it doesn't have to be spot-on accurate). Also, each player should have no more than four adjacent cells. That is to say, when the map is generated, the biggest "chunks" cannot be more than four cells each.

I know this is not always possible for two or three players (as this resembles the "coloring the map" problem), and I'm OK with doing other solutions for those (like creating maps that solve the problem instead). But, for four to eight players, how could I approach this problem?

# Answer
This is what I would do:

1. Assign all cells to random players. On big maps this should be very likely to produce pretty even numbers of tiles for all players, on smaller maps you'll probably need to do some corrections.
2. Break up chunks that are too large. The easiest thing to do would be take all tiles in chunks and again assign each tile randomly.
3. In case of unbalanced numbers of cells (e.g. player A has 24 cells, player B has 16), reassign a couple of the cells from overrepresented players to underrepresented players.
4. Check again for chunks. If step 3 introduced new chunks, go back to step 2. If not, nice map!
> 3 votes

# Answer
Assuming you have a hexmap of `n` cells in total, and `p` players, where `p <= n`, the best way to to tackle this is through *round-robin distribution* via *cellular automata* (CA).

***Initialisation***

Randomly (and/or using some or other heuristic, such as distance from map centre) pick a starting cell for each player. Since `p <= n`, this shouldn't be a problem.

***Cellular automata***

You require full connectivity between your hex cells. I would suggest a 6-neighbor array per cell:

```
class Cell
{
   //... other members...
   Cell[6] neighbours = new Cell[6];
}

```

Use of fixed size arrays allows the concept of topographical directions between cells to exist, which a list or vector would not. I recommend this, as it may make certain navigation ops easier.

You can also store your hexmap in a 2D array, with offsets per row. This may however be slightly less intuitive than storing a neighbour array per cell, only because of the geometric offset on every other row.

Make sure every cell is connected to everything that is a neighbour. You can do this row by row, cell by cell as you generate the full hexmap. P.S. If you ultimately want a non-rectangularly bounded hexmap, you can then simply remove individual cells and references to those cells, to form negative spaces, allowing you to create an organic map outline.

***Round-robin distribution***

Pseudocode:

```
count number of neutral cells in entire map, minus those starting cells taken by players
while neutral cells remain (or while true)
   for each player
      if player has not yet reached expected territory size in cells
         for each cell already constituting this player's territory
           if territory can grow by one cell into a neutral neighbour
              grow into neighbour
              reduce neutral cell count for entire map by one
              if no more neutral cells remain in map
                 break out of outermost while loop immediately
              else
                 continue to next player immediately
begin game

```

This algorithm will give each player a chance to grow its territory by one, in a round robin fashion, provided that player's territory *still has* valid growing space. If certain players are blocked from growing further, the algorithm will in spite of this continue to grow the territories of players who *do* still have valid growing space. You could easily restrict every player to the same number of cells as soon as one of them hits a limit, but that should be easy enough for you to figure out, if desired.

This will provide maximally-sized "home territories" for each player. If you want to have "island" territories in addition, in order to fulfill the cell count quota for that player, then once a player runs out of local space to grow, you can then pick a new start cell from the neutral cells list and proceed with the same "growth" process, from there. This way, you will end up with nicely-sized, coherent sets of islands for each player, rather than random noise.
> 1 votes

# Answer
Another approach would be to start with a distribution that's 'fair' but regular, and then use an appraoch similar to Simulated Annealing to break up the regularity without losing the fairness:

* Start by assign colors to all the cells of your grid in a regular pattern (e.g., have a repeating '123412341234' pattern on the first row, followed by '341234123412' on the next, etc.). This may lead to a non-uniform distribution of colors if your map is particularly poorly shaped, but I'm presuming that you're starting with a fixed map, so you should be able to find *some* equidistributed regular coloring of it.
* Then repeat the following for as many steps as you feel like (there is no real 'doneness' criterion, so experimentation will tell you what a minimum reasonable number of steps is):
    + Pick two elements of the grid at random
    + If they have the same color, try again (there's no point otherwise, since then swapping will be a no-op. You only have a 1/4 chance of hitting the same color, and a 1/16 chance of hitting the same color twice in a row, so you should never have to retry too much)
    + Provisionally swap the colors of those two elements
    + Test the sizes of the newly-formed regions in the elements' locations after the swap:
        - do a simple flood-fill outwards from each element's new spot to determine how large a region of that color the swap would make.
    + If either of these two regions is larger than your threshold, undo the provisional swap; otherwise, 'finalize' the swap of the two elements' colors.

The keys here are that the fact you're swapping two spots means that you never unbalance the colors, and likewise the test that you do before finalizing your swap ensures that you never create regions that are too large. If you have some means of displaying your grid, you could even visualize this process to watch how it 'builds' its regions through the repeated swaps.

If you can't start with an equidistributed regular coloring, incidentally, then you should still be able to do something similar to equidistribute the coloring: while your coloring isn't equidistributed, pick an element at random; then, if it's one of the over-represented colors, provisionally set its color to one of the under-represented colors and then check to make sure that doesn't create too large a region of the new color.
> 0 votes

---
Tags: algorithm, procedural-generation, maps, random, hexagonal-grid
---


# Question
Title: Automatically zoom out the camera to show all players
I am building a game in XNA that takes place in a rectangular arena. The game is multiplayer and each player may go where they like within the arena. The camera is a perspective camera that looks directly downwards.

The camera should be automatically repositioned based on the game state. Currently, the xy position is a weighted sum of the xy positions of important entities.

I would like the camera's z position to be calculated from the xy coordinates so that it zooms out to the point where all important entities are visible.

My current approach is to:

1. hw = the greatest x distance from the camera to an important entity
2. hh = the greatest y distance from the camera to an important entity
3. Calculate z = max(hw / tan(FoVx), hh / tan(FoVy))

My code seems to *almost* work as it should, but the resulting z values are always too low by a factor of about 4.

Any ideas?

# Answer
> 2 votes
I would divide FoVx/FoVy by 2.

```
z = max(hw / tan(FoVx/2), hh / tan(FoVy/2))

```

---
Tags: xna, 3d, mathematics, camera
---


title: Entity system and rendering types

text:
# Question
Title: Entity system and rendering types
I would like to implement entity system in my game and I've got some question about entity system and rendering.

Currently, my renderer got two types of elements:

**Current design**

* Mesh : A default renderable with a Material, a Geometry and a Transformable
* Sprite : A type of mesh with some methods like "flip" and "setRect" methods and a rect member (With an imposed geometry, a quad)

This objects inherit from "Spacial" class.

**Questions:**

* How can I handle this two types in an entity system?
* I'm thinking about using "MeshComponent" and "SpriteComponent", but if I do that, an entity could have a Mesh and a Sprite at the same type, it's look stupid, right?

I thought the idea to have a parent "rendering" component : "RenderableComponent" for "MeshComponent" and "SpriteComponent" but it will be difficult to handle "cast" in the game (ex: did I need to ask entity-\>getComponent or SpineComponent, …)

Thanks a lot for reading me!

**My entity system work like that:**

```
---------------------------------------------------------------------------
Entity* entity = world->createEntity();

MeshComponent* mesh = entity->addComponent<MeshComponent>(material);
mesh->loadFromFile("monkey.obj");

PhysicComponent* physic = entity->addComponent<PhysicComponent>();
physic->setMass(5.4f);
physic->setVelocity( 0.5f, 2.f );
---------------------------------------------------------------------------
class RenderingSystem
{
    private:
        Scene scene;
    public:
        void onEntityAdded( Entity* entity )
        {
            scene.addMesh( entity->getComponent<MeshComponent>() );
        }
}

class PhysicSystem
{
    private:
        World world;
    public:
        void onEntityAdded( Entity* entity )
        {
            world.addBody( entity->getComponent<PhysicComponent>()->getBody() );
        }

        void process( Entity* entity )
        {
            PhysicComponent* physic = entity->getComponent<PhysicComponent>();
        }
}

---------------------------------------------------------------------------

```

# Answer
> 2 votes
Different types of renderables are different components. They have different interfaces. They are processed by the rendering system differently.

You don't need to have a strict 1-1 mapping between components and systems. A single system may be responsible for multiple components. Some components may need to register themselves into multiple systems (albeit not usually). Some components may be just data and their "system" might really just be an object factory/allocator.

Consider:

```
 class RenderSystem {
 public:
     void RegisterComponent(MeshComponent* mesh);
     void RegisterComponent(SpriteComponent* sprite);
     void RegisterComponent(ParticleSystemComponent* particles);
 };

 class MeshComponent : public Component<RenderSystem> { ... };
 class SpriteComponent : public Component<RenderSystem> { ... };
 class ParticleSystemComponent : public Component<RenderSystem> { ... };

```

Each component has nothing in common. The render system keeps the three different components in three different lists. Optimally rendering a bunch of sprites is different than optimally rendering a bunch of (potentially animated) meshes, but the render system does want to be aware of both and potentially interleave them in some cases.

So far as an entity having a mesh and a sprite at the same time looking stupid, sure it would. That's a data problem, not a C++ problem nor a problem with your architecture. Components allow designers to make all kinds of stupid combinations or leave off components necessary for gameplay. That's a downside to components - your designers need to be vaguely aware of what components are, which components do what, and what combinations make sense for viable gameplay.

---
Tags: c++, rendering, entity-system
---


# Question
Title: Why aren't tangent space normal maps completely blue?
Why aren't normal maps just blue? I would think that normal maps should be predominantly blue in color because the Z component of the normal is represented by blue. Normals point out of the surface in the Z direction so we should see blue as the predominant colour since the Z component is dominant.

By definition tangent space is perpendicular to the surface. At any point we should have the normal always pointing in the Z (blue direction) with no X (red direction) or Y (green direction). Thus the normal map (since it is a "normal map") should have the colour of the normals which is just blue (R = x = 0, G = y = 0, B = z = 1) with no shades in between.

But normal maps are not so, and they have gradients of shades in them. Why is this so?

# Answer
Tangent space is perpendicular to the *geometric* normals - the interpolated vertex normals of the polygons. The normal map provides the *shading* normals, relative to the tangent space defined by the geometric normals. When the shading normals are not the same as the geometric ones - i.e. because you have a detailed surface texture with features that are not modeled in the geometry - the normal map deviates from "flat blue" (RGB 128, 128, 255).

That's kind of the whole point of normal maps - they're the way you get the detailed, small-scale shape of a surface to be represented by lighting and shading even though you haven't modeled out all those tiny details with polygons.
> 20 votes

# Answer
The simple answer is that it's because of range biasing.

Normals have a range -1,0 to 1.0, for each component (x,y,z). The normal map, stored as a 24 bit RGB image, on the other hand, has a range of 0 to 255 for each component.

This means that any components that were zero become 127.5 (the exact middle) in the normal map (which rounds to 128).

The normal vector (0,0,1) becomes (128,128,255) in the normal map image, which is a purplish color, rather than pure blue (0,0,255).
> 7 votes

---
Tags: normal-mapping
---


# Question
Title: Why does my goblin only choose a walk direction once?
I'm working on a simpe 2d canvas game that has a small goblin sprite who I want to get pathing around the screen.

What I originally tried was a random roll that would choose a direction, the goblin would walk that direction. It didnt work effectively, he sort of wobbled in one spot.

Here's my current apporach but he only runs in a rundom direction and doesnt change. What am I doing wrong?

Here's all the relevant code to the goblin object and movement.

```
    var goblin = {
            speed: 100,
            pos: [0, 0],
            dir: 1,
            changeDir: true,
            stepCount: 0,
            stepTotal: 0,
            sprite: new Sprite(
                                goblinImage,
                                [0,0],
                                [30,45],
                                6,
                                [0,1,2,3,2,1],
                                true)
    };

    function getNewDir(){
            goblin.dir = Math.floor(Math.random()*4)+1;
    };

    function checkGoblinMovement(){
        if(goblin.changeDir){
            goblin.changeDir = false;
            goblin.stepCount = 0;
            goblin.stepTotal = Math.floor(Math.random*650)+1;
            getNewDir();
        }
        else
         {
           if(goblin.stepCount === goblin.stepTotal){
                 goblin.changeDir = true;
         }
       }
    };

    function update(delta){

        healthCheck();

        if(isGameOver){
            gameOver();
        }
        if(!isGameOver){
        updateCharLevel();
        keyboardInput(delta);

        moveGoblin(delta);
        checkGoblinMovement();

        goblin.sprite.update(delta);

        //update sprites
        if(mainChar.kills!=0 && bloodReady){
            for(var i=0; i<bloodArray.length; i++){
                    bloodArray[i].sprite.update(delta);
         }
        }

        //collision detection
        if(collision(mainChar, goblin))
            {
               combatOutcome(combatEvent());
               combatCleanup();
            }
            }
        };

    function main(){
        var now = Date.now();
        var delta = (now - then)/1000;
        if(!isGameOver){
        update(delta);
        }
        draw();
        then = now;
    };

function moveGoblin(delta){

    goblin.stepCount++;

    if(goblin.dir === 1){
      goblin.pos[1]  -= goblin.speed * delta* 2;
        if(goblin.pos[1] <= 85){
            goblin.pos[1] = 86;
          }
    }

    if(goblin.dir === 2){
        goblin.pos[1]  += goblin.speed * delta;
        if(goblin.pos[1] > 530){
            goblin.pos[1] = 531;
          }
    }

    if(goblin.dir === 3){
      goblin.pos[0]  -= goblin.speed * delta;
        if(goblin.pos[0] < 0){
            goblin.pos[0] = 1;
          }
    }

    if(goblin.dir === 4){
      goblin.pos[0]  += goblin.speed * delta* 2;
        if(goblin.pos[0] > 570){
            goblin.pos[0] = 571;
          }
    }

};

```

# Answer
> 1 votes
Your goblin is initialized in a state such that `changeDir` is true. Thus, the first time you call `checkGoblinMovement` you will assign a new direction and step total to the goblin.

The next time the goblin will change direction is when the current step count equals the step total. This will never occur, because you do not appear to ever increment `stepCount` anywhere. You probably want to do this once per loop.

Note that this is a problem you could easily solve yourself by mastering your debugger and stepping through the code line by line. You'd see that every time you check for the step count to equal the step total, you have the same step count as last time.

You could also achieve a solution by analyzing your logic backwards: you know the problem state is that the goblin doesn't ever change direction after the first time. So look at the conditions in your code that cause the goblin to change direction, and work backwards from there figuring out what causes each of those bits of code to execute and why they might not.

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


# Question
Title: OpenGL 2D Rasterization Sub-Pixel Translations
I have a tile based 2D engine where the projection matrix is an orthographic view of the world without any scaling applied. Thus: one pixel texture is drawn on the screen in the same size.

That all works well and looks nice but if the camera makes a sub-pixel movement small lines appear between the tiles. I can tell you in advance what does not fix the problem:

* `GL_NEAREST` texture interpolation
* `GL_CLAMP_TO_EDGE`

What does “fix” the problem is anchoring the camera to the nearest pixel instead of doing a sub-pixel translation. I can live with that, but the camera movement becomes jerky. Any ideas how to fix that problem without resorting to the rounding trick I do currently?

# Answer
To avoid the camera jerkiness, you should keep the floating-point coordinates camera, but clamp the OpenGL *projection* to the nearest pixel.
> 1 votes

# Answer
You can see this blog post about using `double` instead of `float` for OpenGL matrices. I've had similar issues on PC using OpenGL, so it's not iPhone/OpenGL ES-specific, although the blog post mention OpenGL ES on the iPhone.
> 0 votes

# Answer
It may be that when calculating the coordinates of each tile's corners, you are losing some precision. So, for example, you think the bottom right vertex of tile 0 is in exactly the same place as the bottom left vertex of tile 1, but actually it is not. One idea to fix it would be to calculate a temporary grid of coordinates at the beginning, and then copy the appropriate position when constructing the tile geometry. Does that make sense?
> 0 votes

---
Tags: opengl, 2d
---


# Question
Title: How to define data for an input sequence game?
I'm starting to program my very first game, it's a clone of DDR/Stepmania done for research purposes and learning.

I (at this early stage) get most of the UI/Music/input work that should be done, but what i still can't grasp is scripting, i've read about Lua and that you shouldn't use it with XNA/Monogame as C# is capable enough, but i cannot get the utility of it.

Assuming the needs of my game, What would be the ideal way to implement the input sequences it needs?, i thought of XML/Json, let's say **Stage 1**

```
<game>
 <level id="1">
  <step id="1" key="up" time="00:00:01"/>
  <step id="2" key="left" time="00:00:02"/>
 </level>
</game>

```

Is that a correct implementation? or are there better ways with more benefits?

# Answer
There's no reason to use a script if you're just storing time-based data.

There's many different ways you can design a file format for your data. As long as you can load it into the game, whether you used XML, binary, plain-text, etc, is not very relevant.

As long as your format allows you to add new information without breaking the previous format (during development this doesn't really matter) or rewriting your parsing,

What I'd do is store each song in a folder, containing an mp3, background image and/or video (if applicable), and my level files. Having a new level file for each difficulty, and having each one have it's own reference to the mp3 and other assets, allows users to easily share any difficulties that they've created by sending each other just the level file.

As for the levels themselves, you'll want to store data such as the offset for the song (the amount of silence before the song starts. It's rare to find a song that doesn't have this) and other metadata. You'd probably also want to store the speed of the arrows, and allow the BPM to be changed at any point in time during the song.

Also, it's more crucial to have a good, functional level editor in rhythm games than it is in most other types.
> 2 votes

---
Tags: scripting, file-format
---


# Question
Title: Easy Method to Change Color on UI Elements
This isn't a language-specific thing as far as I'm concerned. I was wondering what may be a quick way to change the COLOR of a certain on-screen element such as a button and its associated text.

I would assume there is a trick to making a graphics engine so maybe individuals pixels or groups of sprites can have their colors easily shifted. A lot of game interface buttons and such have this so you know when an event like a click has occurred.

Any pseudo code would be helpful and I am working in Android (not XML fluff), but again, this probably is not a very specific question, just an inquiry on how to go about this.

# Answer
So after searching with the question more clearly stated, I found the following link:

https://stackoverflow.com/questions/4251027/faster-way-to-set-a-png-bitmap-color-instead-of-pixel-by-pixel

Basically, I wanted to be able to change the text color, button colors, etc. and it looks like there are methods in the bitmap class to accomplish that (bitmap.extractAlpha() looks promising).

Thanks again for your help everyone.
> 0 votes

# Answer
When i want to do something like this, I use **white** pixels form my images on the texture (usually flat shapes, and also for text). Then I use `gl.glColor4f()` to the color I want the item to appear in. When rendering, this color is blended with the color of the texture and because the texture items are white, the result is that the items are rendered with the color set by `gl.glColor4f()`.

This is a very basic way to do that, but it has served me well in many cases. Just make sure to reset the color back to **pure white** with `gl.glColor4f()` once you are done, otherwise the last color will be applied to all textures.

Of course I am assuming that you are using OpenGL ES, since you did not specify.
> 0 votes

---
Tags: java, android, color, pixel
---


# Question
Title: How to create a magic orb like in Skyrim?
How would I go about creating magic orb that looks like from magic menu in Skyrim in Unity3D?

Here is what I have in mind: Orb Image

And a video of that effect from 0:09-0:13: Orb Video

# Answer
> 1 votes
It is likely a combination of different particle effects.

A particle effect is a graphic effect which consists of many tiny objects which move according to specific rules. In this case it looks like they combined some particles which orbit around the center with some which are created at the center and move out of it while becomming more transparent and others which ares spawned outside and move towards the center while becomming less transparent.

For the rendering of the particles themself they likely used lots of shader effects like blur, bloom and different transformations.

# Answer
> 0 votes
My guess is it was a pre-rendered. But I could be mistaking.

If it wasn't pre-rendered (and still likely if it was), I would guess that it's done with a series of steps:

* A basic, white, particle billboard for the glow in the center.
* A billboard, with animated texture, for the beams coming off of the core.
* An Irregular sphere, with a texture that is spotted with bright lights for the small white lights circling the sphere (possibly deformed in real-time)
* Triangle strips, with a few different possible textures, moving and twisting around the surface of a larger, likely irregular, sphere for the beams circling the form.
* A "Bloom" effect, to give it a bit of a glow.
* Maybe a slight motion blur, as the beam's seem to leave a slight trail.

---
Tags: unity, particles, graphic-effects
---


# Question
Title: What is the most efficient way to blur in a shader?
I'm currently working on screen space reflections. I have perfectly reflective mirror-like surfaces working, and I now need to use a blur to make the reflection on surfaces with a low specular gloss value look more diffuse. I'm having difficulty deciding how to apply the blur, though.

My first idea was to just sample a lower mip level of the screen rendertarget. However, the rendertarget uses SurfaceFormat.HalfVector4 (for HDR effects), which means XNA won't allow linear filtering. Point filtering looks horrible and really doesn't give the visual cue that I want.

I've thought about using some kind of Box/Gaussian blur, but this would not be ideal. I've already thrashed the texture cache in the raymarching phase before the blur even occurs (a worst case reflection could be 32 samples per pixel), and the blur kernel to make the reflections look sufficiently diffuse would be fairly large.

Does anyone have any suggestions? I know it's doable, as Photon Workshop achieved the effect in Unity.

# Answer
I Guess what you are perusing are more of a physical correct rendering when having more dirtier surfaces.

A Good approach is to reflect multiple rays in a hemisphere around the original reflection vector. from there you can blur them or just sum them for a easy but fast effect.

Of course you could blur the original image, but if you want different materials to have different "Roughness" you should think about blurring the original crisp image instead.
> 0 votes

---
Tags: xna, shaders, blur, reflection-rendering
---


# Question
Title: view if GL_CULL_FACE is enabled/disabled
Im using GL\_CULL\_FACE, an i'm trying to map a key for enable/disable the gl\_cull\_face. Is there any posibility of viewing if it's enabled or not? Thanks

# Answer
> 3 votes
glIsEnabled

```
if (glIsEnabled (GL_CULL_FACE))
{
    // culling is enabled
}

```

Alternatively you can track state yourself in your own variable, using something like this:

```
glEnable (GL_CULL_FACE);
glState.CullEnabled = TRUE;

```

# Answer
> 0 votes
There are two ways to do it.
One way is to store it's state in a variable in your program and whether you change the state, you will update that variable.
Or you can call glIsEnabled(GL\_CULL\_FACE) which return a GLboolean indicating if GL\_CULL\_FACE is enabled or not.

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


title: Java hashmap access without exception

text:
# Question
Title: Java hashmap access without exception
I'm using a hashmap as an infinite map for a tile based game. I'm trying to access all values in a hashmap from another thread and changing the content at the same time. But I'm getting a java.util.ConcurrentModificationException. How can I do this without getting an exception? I'm getting the exception in this line:

`Object[] objects = hashMap.values().toArray();`

# Answer
> 1 votes
instead of using `Collections.synchronizedMap` you can use a `java.util.ConcurrentMap` implementation

I suggest using the hashmap implementation

```
ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>();

```

exposing the ConcurrentMap interface allows use of the test and update style atomic operation

# Answer
> 0 votes
You get java.util.ConcurrentModificationException when you try to access the HashMap from more than one threads and at least one thread tries to modify it.

> If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) Java HashMap

One way to solve it, is to wrap the Map using the Collections.synchronizedMap method. This way you will restrict the access to the HashMap only to one thread at a time ( call to a HashMap function) . Keep in mind that synchronizing the access to the map will make the calls a lot slower.

(e.x. of Collections.synchronizedMap)

```
Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());

```

---
Tags: java, exceptions
---


title: What is a game development portfolio?

text:
# Question
Title: What is a game development portfolio?
What is a portfolio in game development? Does it include programming or modelling and animation too? Can somebody explain it to me?

# Answer
> 4 votes
Basically, you want something that can show to an employer what you've done in your industry.

If you're an artist, you'd want to showcase art you've done. Things like sketches, college projects, work from previous jobs (assuming they allow you to post them.)

If you're a programmer it's usually links to personal (game) projects you've worked on and details about how you contributed to any published titles you may have contributed to. With programming it's less realistic to show actual code but if you've worked on something yourself and/or you've worked on something OpenSource, it's certainly something you should show if you're able.

The point is, you want something an employer can look through and see the kind of work you do, your quality, and get a feel for how you are in your field.

# Answer
> 1 votes
Portfolios are not unique to game development. Commonly called portfolios, or more technically "career portfolio", see this definition from wikipedia:

> Career portfolios are used to plan, organize and document education, work samples and skills. People use career portfolios to apply to jobs, apply to college or training programs, get a higher salary, show transferable skills, and to track personal development. They are more in-depth than a resume, which is used to summarize the above in one or two pages. Career portfolios serve as proof of one's skills, abilities, and potential in the future.

Basically, it's a collection of things you've done. This collection has the purpose of making you look good to potential employers. So you want to put everything in there that shows off your skills and talents.

In many cases this is a digital portfolio. This allows you to put in code and digital art assets. Some people make a game to represent their portfolio, others will just have a collection of things they've worked on.

It's not required to have one. In fields where it's hard to convey in words what your talents are, it's very nice to have something like this.

---
Tags: game-industry, career, education
---


title: Fast lighting with multiple lights

text:
# Question
Title: Fast lighting with multiple lights
How can I implement fast lighting with multiple lights?

I don't want to restrain the player, he can place an unlimited number and possibly overlapping (point) lights into the level.

The problem is that shaders which contain dynamic loops which would be necessary to calculate the lighting tend to be very slow.

I had the idea that if it could be possible at compiletime to compile a shader n times where n is the number of lights. If the number n is known at compiletime, the loops can be unrolled automatically. Is this possible to generate n versions of the same shader with just a different number of lights?

At runtime I could then decide which shader to use for which part of the level.

# Answer
I believe what you are looking for is called Deferred Rendering. It is a rendering technique that scales extremely well with a lot of lights, so well that it can used for dynamic indirect illumination. That means 1000s of lights on the screen.

It is basically a technique in which you first render all your geometry data(position, normal, depth) into an intermediate pixel buffer(called the G-Buffer). Then in a second pass you render a light shape along with its parameters. The shader of this second pass takes the information from the G-Buffer, applies light calculation, then blends it into the final image.

You can find implementation details here
> 8 votes

---
Tags: xna, shaders, performance, hlsl, lighting
---


# Question
Title: Multi-Threaded Pipelined Game Engine Data Synchronization Questions
Let's say I'm setting up a worker pool based game engine with pipelining. Let's say I have 4 stages in my pipeline as such:

* Stage 1: Physics
* Stage 2: AI/Input
* Stage 3: Game Logic
* Stage 4: Rendering

Now let's say that the physics detects a collision between a bullet and a character in stage 1. Two frames later the game logic may choose to remove that bullet from the simulation, however none of the other copies of the data for the other pipeline stages will get this information. How is this sort of thing and other things like it get handled? Do you generally make changes like this to every pipeline stage's data at the end of a frame?

# Answer
> 3 votes
Yes, one way to deal with this is to buffer up the events generated by each stage and then subsequent stages can iterate over those event queues. So the physics stage can iterate over the events generated by the AI stage and apply their results, which the game logic and rendering stages would also do.

Another option is to simply not use multiple copies of data but rather to use a fork-and-join worker system where each system works in series but the systems themselves divide their work between the available cores, though that is obviously not an answer to your question.

Update: forgot to link the usual blog post for event systems in data-oriented-driven architectures: http://bitsquid.blogspot.com/2009/12/events.html

---
Tags: architecture, multithreading
---


title: Coroutines in series

text:
# Question
Title: Coroutines in series
How would i go about stacking up a series of Coroutine calls that should be executed one after the other?

I have tried getting a flashing color effect looping a series of color lerps in a coroutine but its not working.

# Answer
> 7 votes
```
public static IEnumerator Sequence(params IEnumerator[] sequence)
{
  for(int i = 0 ; i < sequence.Length; ++i)
  {
    while(sequence[i].MoveNext())
      yield return sequence[i].Current;
  }
}

```

usage example:

```
IEnumerator PrintCoroutine(string arg)
{
  yield return new WaitForSeconds(0.3f);
}

StartCoroutine(Sequence(PrintCoroutine("foo"), PrintCoroutine("bar")));

```

# Answer
> 7 votes
In addition to what Heisenbug described, something that the Unity manual doesn't make obvious is that you can `yield return` a `Coroutine` object, which you receive from a `StartCoroutine` call.

```
public IEnumerator RunColorCoroutineLoop()
{
    while (true) {
        yield return StartCoroutine(FirstColorCoroutine());
        yield return StartCoroutine(SecondColorCoroutine());
        yield return StartCoroutine(ThirdColorCoroutine());
        yield return StartCoroutine(FourthColorCoroutine());
    }
}

public IEnumerator FirstColorCoroutine()
{
    SetColor("color1");
    yield return new WaitForSeconds(1f);
}

public IEnumerator SecondColorCoroutine()
{
    SetColor("color2");
    yield return new WaitForSeconds(1f);
}

public IEnumerator ThirdColorCoroutine()
{
    SetColor("color3");
    yield return new WaitForSeconds(1f);
}

public IEnumerator FourthColorCoroutine()
{
    SetColor("color4");
    yield return new WaitForSeconds(1f);
}

```

This sometimes makes for better reading than a MoveNext loop, but has the disadvantage that you can't prevent the child coroutine from running via logic within the topmost coroutine loop, which could be useful for constructing more sophisticated flow control techniques on top of IEnumerator.

For more on this, you should look at this Unite video which covers getting more out of your coroutines without building your own coroutine scheduler.

---
Tags: unity
---


# Question
Title: Figuring out what object is closer to a certain point?
I'm trying to create fog of war, I have the visual effect created but I'm not sure how to deal with the hiding of other players if they're within the fog of war.

So right now the thing I'm trying to do is if another player is hiding behind a wall then not to render that player. I was thinking of doing it by sending a ray in the direction of all the players, and then creating a list of all the obstacles that ray collides with and then trying to figure out if an obstacle was closer than the player in order to predict the distance.

But then I realized I'm not really sure how to figure out if the obstacle is infact closer or not because I have to account for all the dimensions, so I'm kind of stuck. First of all is this approach the correct way to go about it and secondly how would I calculate if the obstacle was infact closer taking into account the X Y and Z.

Thanks

# Answer
If your problem is only calculating the distance between two objects (while accounting for all dimensions) what you need is a simple formula for calculating vector's length.

First of all you need a position vector for each object/player, to get the distance between two vectors you subtract position B from position A and then calculate the length using the following formula

> Vector3 Length = sqrt(X\*X + Y\*Y + Z\*Z);

this formula is implemented in XNA using the Length function.

```
Vector3 vec = positionB - positionA; // subtract positions
float distance = vec.length();       // calculate distance

```

In fact you don't need to calculate the length, you can simply get away by calculating the length squared as far as you only test it with other length sqaured.

In case your objects have large widths/length calculating distance by using positions only might not be that accurate so you may want to substract the radius/width depending on the shape, even this might not be good enough, worst case might be sending a ray from the object's position to another object, getting the intersection point, and then using the new intersection point to calculate the distance.
> 1 votes

---
Tags: xna
---


title: Camera for 2.5D Game

text:
# Question
Title: Camera for 2.5D Game
I'm hoping someone can explain this to me like I'm 5, because I've been struggling with this for hours and simply cannot understand what I'm doing wrong.

I've written a `Camera` class for my 2.5D game. The intention is to support world and screen spaces like this:

The camera is the black thing on the right. The +Z axis is upwards in that image, with -Z heading downwards. As you can see, both world space and screen space have (0, 0) at their top-left.

I started writing some unit tests to prove that my camera was working as expected, and that's where things started getting...strange. My tests plot coordinates in world, view, and screen spaces. Eventually I will use image comparison to assert that they are correct, but for now my test just displays the result.

The render logic uses `Camera.ViewMatrix` to transform world space to view space, and `Camera.WorldPointToScreen` to transform world space to screen space.

Here is an example test:

```
[Fact]
public void foo()
{
    var camera = new Camera(new Viewport(0, 0, 250, 100));
    DrawingVisual worldRender;
    DrawingVisual viewRender;
    DrawingVisual screenRender;

    this.Render(camera, out worldRender, out viewRender, out screenRender, new Vector3(30, 0, 0), new Vector3(30, 40, 0));
    this.ShowRenders(camera, worldRender, viewRender, screenRender);
}

```

And here's what pops up when I run this test:

World space looks OK, although I suspect the z axis is going into the screen instead of towards the viewer.

View space has me completely baffled. I was expecting the camera to be sitting above (0, 0) and looking towards the center of the scene. Instead, the z axis seems to be the wrong way around, and the camera is positioned in the opposite corner to what I expect!

I suspect screen space will be another thing altogether, but can anyone explain what I'm doing wrong in my `Camera` class?

---

# UPDATE

I made some progress in terms of getting things to look visually as I expect, but only through intuition: not an actual understanding of what I'm doing. Any enlightenment would be greatly appreciated.

I realized that my view space was flipped both vertically and horizontally compared to what I expected, so I changed my view matrix to scale accordingly:

```
this.viewMatrix = Matrix.CreateLookAt(this.location, this.target, this.up) *
    Matrix.CreateScale(this.zoom, this.zoom, 1) *
    Matrix.CreateScale(-1, -1, 1);

```

I could combine the two `CreateScale` calls, but have left them separate for clarity. Again, I have no idea why this is necessary, but it fixed my view space:

But now my screen space needs to be flipped vertically, so I modified my projection matrix accordingly:

```
this.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(0.7853982f, viewport.AspectRatio, 1, 2)
    * Matrix.CreateScale(1, -1, 1);

```

And this results in what I was expecting from my first attempt:

I have also just tried using `Camera` to render sprites via a `SpriteBatch` to make sure everything works there too, and it does.

But the question remains: **why do I need to do all this flipping of axes to get the space coordinates the way I expect?**

---

# UPDATE 2

I've since improved my rendering logic in my test suite so that it supports geometries and so that lines get lighter the further away they are from the camera. I wanted to do this to avoid optical illusions and to further prove to myself that I'm looking at what I think I am.

Here is an example:

In this case, I have 3 geometries: a cube, a sphere, and a polyline on the top face of the cube. Notice how the darkening and lightening of the lines correctly identifies those portions of the geometries closer to the camera.

If I remove the negative scaling I had to put in, I see:

So you can see I'm still in the same boat - I still need those vertical and horizontal flips in my matrices to get things to appear correctly.

In the interests of giving people a repro to play with, here is the complete code needed to generate the above. If you want to run via the test harness, just install the xunit package:

**Camera.cs**:

```
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Diagnostics;

public sealed class Camera
{
    private readonly Viewport viewport;
    private readonly Matrix projectionMatrix;
    private Matrix? viewMatrix;
    private Vector3 location;
    private Vector3 target;
    private Vector3 up;
    private float zoom;

    public Camera(Viewport viewport)
    {
        this.viewport = viewport;

        // for an explanation of the negative scaling, see: http://gamedev.stackexchange.com/questions/63409/
        this.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(0.7853982f, viewport.AspectRatio, 1, 2)
            * Matrix.CreateScale(1, -1, 1);

        // defaults
        this.location = new Vector3(this.viewport.Width / 2, this.viewport.Height, 100);
        this.target = new Vector3(this.viewport.Width / 2, this.viewport.Height / 2, 0);
        this.up = new Vector3(0, 0, 1);
        this.zoom = 1;
    }

    public Viewport Viewport
    {
        get { return this.viewport; }
    }

    public Vector3 Location
    {
        get { return this.location; }
        set
        {
            this.location = value;
            this.viewMatrix = null;
        }
    }

    public Vector3 Target
    {
        get { return this.target; }
        set
        {
            this.target = value;
            this.viewMatrix = null;
        }
    }

    public Vector3 Up
    {
        get { return this.up; }
        set
        {
            this.up = value;
            this.viewMatrix = null;
        }
    }

    public float Zoom
    {
        get { return this.zoom; }
        set
        {
            this.zoom = value;
            this.viewMatrix = null;
        }
    }

    public Matrix ProjectionMatrix
    {
        get { return this.projectionMatrix; }
    }

    public Matrix ViewMatrix
    {
        get
        {
            if (this.viewMatrix == null)
            {
                // for an explanation of the negative scaling, see: http://gamedev.stackexchange.com/questions/63409/
                this.viewMatrix = Matrix.CreateLookAt(this.location, this.target, this.up) *
                    Matrix.CreateScale(this.zoom) *
                    Matrix.CreateScale(-1, -1, 1);
            }

            return this.viewMatrix.Value;
        }
    }

    public Vector2 WorldPointToScreen(Vector3 point)
    {
        var result = viewport.Project(point, this.ProjectionMatrix, this.ViewMatrix, Matrix.Identity);
        return new Vector2(result.X, result.Y);
    }

    public void WorldPointsToScreen(Vector3[] points, Vector2[] destination)
    {
        Debug.Assert(points != null);
        Debug.Assert(destination != null);
        Debug.Assert(points.Length == destination.Length);

        for (var i = 0; i < points.Length; ++i)
        {
            destination[i] = this.WorldPointToScreen(points[i]);
        }
    }
}

```

**CameraFixture.cs**:

```
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Xunit;
using XNA = Microsoft.Xna.Framework;

public sealed class CameraFixture
{
    [Fact]
    public void foo()
    {
        var camera = new Camera(new Viewport(0, 0, 250, 100));
        DrawingVisual worldRender;
        DrawingVisual viewRender;
        DrawingVisual screenRender;

        this.Render(
            camera,
            out worldRender,
            out viewRender,
            out screenRender,
            new Sphere(30, 15) { WorldMatrix = XNA.Matrix.CreateTranslation(155, 50, 0) },
            new Cube(30) { WorldMatrix = XNA.Matrix.CreateTranslation(75, 60, 15) },
            new PolyLine(new XNA.Vector3(0, 0, 0), new XNA.Vector3(10, 10, 0), new XNA.Vector3(20, 0, 0), new XNA.Vector3(0, 0, 0)) { WorldMatrix = XNA.Matrix.CreateTranslation(65, 55, 30) });

        this.ShowRenders(worldRender, viewRender, screenRender);
    }

    #region Supporting Fields

    private static readonly Pen xAxisPen = new Pen(Brushes.Red, 2);
    private static readonly Pen yAxisPen = new Pen(Brushes.Green, 2);
    private static readonly Pen zAxisPen = new Pen(Brushes.Blue, 2);
    private static readonly Pen viewportPen = new Pen(Brushes.Gray, 1);
    private static readonly Pen nonScreenSpacePen = new Pen(Brushes.Black, 0.5);
    private static readonly Color geometryBaseColor = Colors.Black;

    #endregion

    #region Supporting Methods

    private void Render(Camera camera, out DrawingVisual worldRender, out DrawingVisual viewRender, out DrawingVisual screenRender, params Geometry[] geometries)
    {
        var worldDrawingVisual = new DrawingVisual();
        var viewDrawingVisual = new DrawingVisual();
        var screenDrawingVisual = new DrawingVisual();
        const int axisLength = 15;

        using (var worldDrawingContext = worldDrawingVisual.RenderOpen())
        using (var viewDrawingContext = viewDrawingVisual.RenderOpen())
        using (var screenDrawingContext = screenDrawingVisual.RenderOpen())
        {
            // draw lines around the camera's viewport
            var viewportBounds = camera.Viewport.Bounds;
            var viewportLines = new Tuple<int, int, int, int>[]
            {
                Tuple.Create(viewportBounds.Left, viewportBounds.Bottom, viewportBounds.Left, viewportBounds.Top),
                Tuple.Create(viewportBounds.Left, viewportBounds.Top, viewportBounds.Right, viewportBounds.Top),
                Tuple.Create(viewportBounds.Right, viewportBounds.Top, viewportBounds.Right, viewportBounds.Bottom),
                Tuple.Create(viewportBounds.Right, viewportBounds.Bottom, viewportBounds.Left, viewportBounds.Bottom)
            };

            foreach (var viewportLine in viewportLines)
            {
                var viewStart = XNA.Vector3.Transform(new XNA.Vector3(viewportLine.Item1, viewportLine.Item2, 0), camera.ViewMatrix);
                var viewEnd = XNA.Vector3.Transform(new XNA.Vector3(viewportLine.Item3, viewportLine.Item4, 0), camera.ViewMatrix);
                var screenStart = camera.WorldPointToScreen(new XNA.Vector3(viewportLine.Item1, viewportLine.Item2, 0));
                var screenEnd = camera.WorldPointToScreen(new XNA.Vector3(viewportLine.Item3, viewportLine.Item4, 0));

                worldDrawingContext.DrawLine(viewportPen, new Point(viewportLine.Item1, viewportLine.Item2), new Point(viewportLine.Item3, viewportLine.Item4));
                viewDrawingContext.DrawLine(viewportPen, new Point(viewStart.X, viewStart.Y), new Point(viewEnd.X, viewEnd.Y));
                screenDrawingContext.DrawLine(viewportPen, new Point(screenStart.X, screenStart.Y), new Point(screenEnd.X, screenEnd.Y));
            }

            // draw axes
            var axisLines = new Tuple<int, int, int, int, int, int, Pen>[]
            {
                Tuple.Create(0, 0, 0, axisLength, 0, 0, xAxisPen),
                Tuple.Create(0, 0, 0, 0, axisLength, 0, yAxisPen),
                Tuple.Create(0, 0, 0, 0, 0, axisLength, zAxisPen)
            };

            foreach (var axisLine in axisLines)
            {
                var viewStart = XNA.Vector3.Transform(new XNA.Vector3(axisLine.Item1, axisLine.Item2, axisLine.Item3), camera.ViewMatrix);
                var viewEnd = XNA.Vector3.Transform(new XNA.Vector3(axisLine.Item4, axisLine.Item5, axisLine.Item6), camera.ViewMatrix);
                var screenStart = camera.WorldPointToScreen(new XNA.Vector3(axisLine.Item1, axisLine.Item2, axisLine.Item3));
                var screenEnd = camera.WorldPointToScreen(new XNA.Vector3(axisLine.Item4, axisLine.Item5, axisLine.Item6));

                worldDrawingContext.DrawLine(axisLine.Item7, new Point(axisLine.Item1, axisLine.Item2), new Point(axisLine.Item4, axisLine.Item5));
                viewDrawingContext.DrawLine(axisLine.Item7, new Point(viewStart.X, viewStart.Y), new Point(viewEnd.X, viewEnd.Y));
                screenDrawingContext.DrawLine(axisLine.Item7, new Point(screenStart.X, screenStart.Y), new Point(screenEnd.X, screenEnd.Y));
            }

            // for all points in all geometries to be rendered, find the closest and furthest away from the camera so we can lighten lines that are further away
            var distancesToAllGeometrySections = from geometry in geometries
                                                 let geometryViewMatrix = geometry.WorldMatrix * camera.ViewMatrix
                                                 from section in geometry.Sections
                                                 from point in new XNA.Vector3[] { section.Item1, section.Item2 }
                                                 let viewPoint = XNA.Vector3.Transform(point, geometryViewMatrix)
                                                 select viewPoint.Length();
            var furthestDistance = distancesToAllGeometrySections.Max();
            var closestDistance = distancesToAllGeometrySections.Min();
            var deltaDistance = Math.Max(0.000001f, furthestDistance - closestDistance);

            // draw each geometry
            for (var i = 0; i < geometries.Length; ++i)
            {
                var geometry = geometries[i];

                // there's probably a more correct name for this, but basically this gets the geometry relative to the camera so we can check how far away each point is from the camera
                var geometryViewMatrix = geometry.WorldMatrix * camera.ViewMatrix;

                // we order roughly by those sections furthest from the camera to those closest, so that the closer ones "overwrite" the ones further away
                var orderedSections = from section in geometry.Sections
                                      let startPointRelativeToCamera = XNA.Vector3.Transform(section.Item1, geometryViewMatrix)
                                      let endPointRelativeToCamera = XNA.Vector3.Transform(section.Item2, geometryViewMatrix)
                                      let startPointDistance = startPointRelativeToCamera.Length()
                                      let endPointDistance = endPointRelativeToCamera.Length()
                                      orderby (startPointDistance + endPointDistance) descending
                                      select new { Section = section, DistanceToStart = startPointDistance, DistanceToEnd = endPointDistance };

                foreach (var orderedSection in orderedSections)
                {
                    var start = XNA.Vector3.Transform(orderedSection.Section.Item1, geometry.WorldMatrix);
                    var end = XNA.Vector3.Transform(orderedSection.Section.Item2, geometry.WorldMatrix);
                    var viewStart = XNA.Vector3.Transform(start, camera.ViewMatrix);
                    var viewEnd = XNA.Vector3.Transform(end, camera.ViewMatrix);

                    worldDrawingContext.DrawLine(nonScreenSpacePen, new Point(start.X, start.Y), new Point(end.X, end.Y));
                    viewDrawingContext.DrawLine(nonScreenSpacePen, new Point(viewStart.X, viewStart.Y), new Point(viewEnd.X, viewEnd.Y));

                    // screen rendering is more complicated purely because I wanted geometry to fade the further away it is from the camera
                    // otherwise, it's very hard to tell whether the rendering is actually correct or not
                    var startDistanceRatio = (orderedSection.DistanceToStart - closestDistance) / deltaDistance;
                    var endDistanceRatio = (orderedSection.DistanceToEnd - closestDistance) / deltaDistance;

                    // lerp towards white based on distance from camera, but only to a maximum of 90%
                    var startColor = Lerp(geometryBaseColor, Colors.White, startDistanceRatio * 0.9f);
                    var endColor = Lerp(geometryBaseColor, Colors.White, endDistanceRatio * 0.9f);

                    var screenStart = camera.WorldPointToScreen(start);
                    var screenEnd = camera.WorldPointToScreen(end);

                    var brush = new LinearGradientBrush
                    {
                        StartPoint = new Point(screenStart.X, screenStart.Y),
                        EndPoint = new Point(screenEnd.X, screenEnd.Y),
                        MappingMode = BrushMappingMode.Absolute
                    };
                    brush.GradientStops.Add(new GradientStop(startColor, 0));
                    brush.GradientStops.Add(new GradientStop(endColor, 1));
                    var pen = new Pen(brush, 1);
                    brush.Freeze();
                    pen.Freeze();

                    screenDrawingContext.DrawLine(pen, new Point(screenStart.X, screenStart.Y), new Point(screenEnd.X, screenEnd.Y));
                }
            }
        }

        worldRender = worldDrawingVisual;
        viewRender = viewDrawingVisual;
        screenRender = screenDrawingVisual;
    }

    private static float Lerp(float start, float end, float amount)
    {
        var difference = end - start;
        var adjusted = difference * amount;
        return start + adjusted;
    }

    private static Color Lerp(Color color, Color to, float amount)
    {
        var sr = color.R;
        var sg = color.G;
        var sb = color.B;
        var er = to.R;
        var eg = to.G;
        var eb = to.B;
        var r = (byte)Lerp(sr, er, amount);
        var g = (byte)Lerp(sg, eg, amount);
        var b = (byte)Lerp(sb, eb, amount);

        return Color.FromArgb(255, r, g, b);
    }

    private void ShowRenders(DrawingVisual worldRender, DrawingVisual viewRender, DrawingVisual screenRender)
    {
        var itemsControl = new ItemsControl();
        itemsControl.Items.Add(new HeaderedContentControl { Header = "World", Content = new DrawingVisualHost(worldRender)});
        itemsControl.Items.Add(new HeaderedContentControl { Header = "View", Content = new DrawingVisualHost(viewRender) });
        itemsControl.Items.Add(new HeaderedContentControl { Header = "Screen", Content = new DrawingVisualHost(screenRender) });

        var window = new Window
        {
            Title = "Renders",
            Content = itemsControl,
            ShowInTaskbar = true,
            SizeToContent = SizeToContent.WidthAndHeight
        };

        window.ShowDialog();
    }

    #endregion

    #region Supporting Types

    // stupidly simple 3D geometry class, consisting of a series of sections that will be connected by lines
    private abstract class Geometry
    {
        public abstract IEnumerable<Tuple<XNA.Vector3, XNA.Vector3>> Sections
        {
            get;
        }

        public XNA.Matrix WorldMatrix
        {
            get;
            set;
        }
    }

    private sealed class Line : Geometry
    {
        private readonly XNA.Vector3 magnitude;

        public Line(XNA.Vector3 magnitude)
        {
            this.magnitude = magnitude;
        }

        public override IEnumerable<Tuple<XNA.Vector3, XNA.Vector3>> Sections
        {
            get
            {
                yield return Tuple.Create(XNA.Vector3.Zero, this.magnitude);
            }
        }
    }

    private sealed class PolyLine : Geometry
    {
        private readonly XNA.Vector3[] points;

        public PolyLine(params XNA.Vector3[] points)
        {
            this.points = points;
        }

        public override IEnumerable<Tuple<XNA.Vector3, XNA.Vector3>> Sections
        {
            get
            {
                if (this.points.Length < 2)
                {
                    yield break;
                }

                var end = this.points[0];

                for (var i = 1; i < this.points.Length; ++i)
                {
                    var start = end;
                    end = this.points[i];

                    yield return Tuple.Create(start, end);
                }
            }
        }
    }

    private sealed class Cube : Geometry
    {
        private readonly float size;

        public Cube(float size)
        {
            this.size = size;
        }

        public override IEnumerable<Tuple<XNA.Vector3, XNA.Vector3>> Sections
        {
            get
            {
                var halfSize = this.size / 2;
                var frontBottomLeft = new XNA.Vector3(-halfSize, halfSize, -halfSize);
                var frontBottomRight = new XNA.Vector3(halfSize, halfSize, -halfSize);
                var frontTopLeft = new XNA.Vector3(-halfSize, halfSize, halfSize);
                var frontTopRight = new XNA.Vector3(halfSize, halfSize, halfSize);
                var backBottomLeft = new XNA.Vector3(-halfSize, -halfSize, -halfSize);
                var backBottomRight = new XNA.Vector3(halfSize, -halfSize, -halfSize);
                var backTopLeft = new XNA.Vector3(-halfSize, -halfSize, halfSize);
                var backTopRight = new XNA.Vector3(halfSize, -halfSize, halfSize);

                // front face
                yield return Tuple.Create(frontBottomLeft, frontBottomRight);
                yield return Tuple.Create(frontBottomLeft, frontTopLeft);
                yield return Tuple.Create(frontTopLeft, frontTopRight);
                yield return Tuple.Create(frontTopRight, frontBottomRight);

                // left face
                yield return Tuple.Create(frontTopLeft, backTopLeft);
                yield return Tuple.Create(backTopLeft, backBottomLeft);
                yield return Tuple.Create(backBottomLeft, frontBottomLeft);

                // right face
                yield return Tuple.Create(frontTopRight, backTopRight);
                yield return Tuple.Create(backTopRight, backBottomRight);
                yield return Tuple.Create(backBottomRight, frontBottomRight);

                // back face
                yield return Tuple.Create(backBottomLeft, backBottomRight);
                yield return Tuple.Create(backTopLeft, backTopRight);
            }
        }
    }

    private sealed class Sphere : Geometry
    {
        private readonly float radius;
        private readonly int subsections;

        public Sphere(float radius, int subsections)
        {
            this.radius = radius;
            this.subsections = subsections;
        }

        public override IEnumerable<Tuple<XNA.Vector3, XNA.Vector3>> Sections
        {
            get
            {
                var latitudeLines = this.subsections;
                var longitudeLines = this.subsections;

                // see http://stackoverflow.com/a/4082020/5380
                var results = from latitudeLine in Enumerable.Range(0, latitudeLines)
                              from longitudeLine in Enumerable.Range(0, longitudeLines)
                              let latitudeRatio = latitudeLine / (float)latitudeLines
                              let longitudeRatio = longitudeLine / (float)longitudeLines
                              let nextLatitudeRatio = (latitudeLine + 1) / (float)latitudeLines
                              let nextLongitudeRatio = (longitudeLine + 1) / (float)longitudeLines
                              let z1 = Math.Cos(Math.PI * latitudeRatio)
                              let z2 = Math.Cos(Math.PI * nextLatitudeRatio)
                              let x1 = Math.Sin(Math.PI * latitudeRatio) * Math.Cos(Math.PI * 2 * longitudeRatio)
                              let y1 = Math.Sin(Math.PI * latitudeRatio) * Math.Sin(Math.PI * 2 * longitudeRatio)
                              let x2 = Math.Sin(Math.PI * nextLatitudeRatio) * Math.Cos(Math.PI * 2 * longitudeRatio)
                              let y2 = Math.Sin(Math.PI * nextLatitudeRatio) * Math.Sin(Math.PI * 2 * longitudeRatio)
                              let x3 = Math.Sin(Math.PI * latitudeRatio) * Math.Cos(Math.PI * 2 * nextLongitudeRatio)
                              let y3 = Math.Sin(Math.PI * latitudeRatio) * Math.Sin(Math.PI * 2 * nextLongitudeRatio)
                              let start = new XNA.Vector3((float)x1 * radius, (float)y1 * radius, (float)z1 * radius)
                              let firstEnd = new XNA.Vector3((float)x2 * radius, (float)y2 * radius, (float)z2 * radius)
                              let secondEnd = new XNA.Vector3((float)x3 * radius, (float)y3 * radius, (float)z1 * radius)
                              select new { First = Tuple.Create(start, firstEnd), Second = Tuple.Create(start, secondEnd) };

                foreach (var result in results)
                {
                    yield return result.First;
                    yield return result.Second;
                }
            }
        }
    }

    #endregion
}

```

# Answer
Your diagrams can be interpreted in one of two ways. It is an optical illusion called the Necker cube. Here is the wikipedia article. Because of this, when you think you are looking at the top, I suspect you may actually be seeing the bottom.

If you can, in your original code, negate the z-value of your camera position.
> 1 votes

# Answer
Given that this is 2.5D, two things here I find strange is this:

```
this.projectionMatrix = Matrix.CreatePerspectiveFieldOfView(0.7853982f, viewport.AspectRatio, 1, 2)
* Matrix.CreateScale(1, -1, 1);

```
1. Try changing your FOV to `Math.PiOver4().`
2. From your Near/Far values, your **Far** is set to 2. Try setting that value bigger (start with 1000).
> 1 votes

# Answer
Applying blind transform like negative scale is not a good idea to understand the problem.

On the original screen capture and the update 1, if you look at the RGB frame, it will match a right handed coordinate system as it should because negate two axis of the view matrix keep the determinant sign unchanged.

On the update 2 capture, you invert only one axis of the projection matrix, by doing this, you are moving from a right handed to a left handed system. Use your thumb, forefinger and middle finger as X, Y and Z.

Because XNA is using right handed coordinates with ( +X right, +Y up, -Z forward ), it means there is really a problem in what you are showing.

You decide your Z coordinate is the up ( as seen in the world space part of the capture ). It means that you needs a transformation to move from our world space ( +X right, +Z up and +Y forward ) to the XNA one.

If you look at your hand, it will reveal a `PI/2` rotation around the X axis. You should insert it before the projection.

Without it, because of the two different systems, your plane is not a floor but a wall.
> 0 votes

---
Tags: xna, matrix, projection
---


# Question
Title: libgdx intersection problem between rectangle and circle
My collision detection in libgdx is somehow buggy. player.png is 20\*80px and ball.png 25\*25px.

Code:

```
@Override
public void create() {
    // ...
    batch = new SpriteBatch();
    playerTex = new Texture(Gdx.files.internal("data/player.png"));
    ballTex = new Texture(Gdx.files.internal("data/ball.png"));

    player = new Rectangle();
    player.width = 20;
    player.height = 80;
    player.x =  Gdx.graphics.getWidth() - player.width - 10;
    player.y = 300;

    ball = new Circle();
    ball.x = Gdx.graphics.getWidth() / 2;
    ball.y = Gdx.graphics.getHeight() / 2;
    ball.radius = ballTex.getWidth() / 2;
}

@Override
public void render() {
    Gdx.gl.glClearColor(1, 1, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

    // draw player, ball
    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    batch.draw(ballTex, ball.x, ball.y);
    batch.draw(playerTex, player.x, player.y);

    batch.end();

    // update player position
    if(Gdx.input.isKeyPressed(Keys.DOWN)) player.y -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.UP)) player.y += 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.LEFT)) player.x -= 250 * Gdx.graphics.getDeltaTime();
    if(Gdx.input.isKeyPressed(Keys.RIGHT)) player.x += 250 * Gdx.graphics.getDeltaTime();

     // don't let the player leave the field
     if(player.y < 0) player.y = 0;
     if(player.y > 600 - 80) player.y = 600 - 80;

     // check collision
     if (Intersector.overlaps(ball, player))
         Gdx.app.log("overlaps", "yes");
}

```

# Answer
> 2 votes
Found the problem:

Replace

```
batch.draw(ballTex, ball.x, ball.y);

```

with

```
batch.draw(ballTex, ball.x-ball.radius, ball.y-ball.radius);

```

That's because `batch.draw` draws with the lower left corner at x/y.

---
Tags: libgdx
---


title: Game with changing logic

text:
# Question
Title: Game with changing logic
I'm planing to develop a puzzle like mobile game (android/ios) with a different logic for each puzzle. Say, for example one puzzle could be a Rubik's cube and another one a ball maze. Many more new puzzles will appear during the life of the game, and I want the users to be able to play those new puzzles.

The standard way for managing this would be through application updates. Each time a new puzzle or bunch of puzzles appear, create a new update for the app that the user can download. However, I would like to do it in a more transparent way. When a new puzzle appears, the basic info of the puzzle would be displayed in the app menu, and the user would be able to play it by just clicking it.

What comes to my mind is that the app would automatically download a .dll or .jar and inject it in the application at runtime. Is that even possible? Are there any restrictions from the OS? Is there a better way for solving it?

Thanks alot

# Answer
Make the main app like a service or OS with a enough API to support "puzzle stuff" and a script interface.

Then script all the puzzles. This way you can embed the universal scripts into the download without having to worry about building binaries for each platform.

This does mean that you have to adopt a data driven style for the main program, menus and options created on the fly from discovered puzzle modules the user has, etc...

I may be wrong, but I'm fairly sure that mobile platforms frown on applications randomly and secretly downloading executable binaries and even your new puzzles will have to become something the user requests.

Unless, of course, this is run as HTML5 with an external web site/app supplying your puzzles, which would be option #2.
> 0 votes

---
Tags: android, ios, mobile
---


title: What makes game sound effects "good"?

text:
# Question
Title: What makes game sound effects "good"?
I'm making a small game, and I've found some free sound effects that I'd like to use.

The issue is that I can't get the sound effects to sound like they "belong" in my game. I don't know what to look for that can make sound effects match the rest of my game style.

I have some ideas on what affects the meshing of audio with graphics. For example, I have a feeling that the current SFX I may be too "realistic" for my graphical style, which is pretty cartoon-like. Also, is there a golden standard for what volume various SFX should be at? (for example, I am thinking that footsteps or other common sounds should be at barely audible volumes, while enemy deaths or something that is a "big deal" should be louder).

I found a similar question about graphics, I'm looking for a similar response with sound effects.

# Answer
I would like to add my bit of experience here as my major degree and expertise is in sound design. The best decision you could clearly have is to hire someone with experience in sound designing (and will probably have a portfolio with sounds made for games with the same graphics aesthetics as yours).

The other way around will be for you to record and edit your sounds which I definitely recommend. It is a very funny and rewarding experience creating your own sounds! And there are countless tutorials online on how to record them and edit them.

The basic rule is this "the best sound design is the one that gets unnoticed by the viewer / player in this case" this quote comes from films but there is a huge logic behind it.

If a sound is absolutely fitting with the character / aesthetics and feel of the game then it should not get noticed but instead be part of the atmosphere of the game and help create the feeling.
> 6 votes

# Answer
One thing I've realized since I asked this question is that including multiple sounds for the same effect goes a long way toward making SFX more pleasant.

For example, making 3 or more "Ouch" sounds for the same character, since in the real world no one will ever sound the exact same, even if they are saying the same thing.
> 3 votes

# Answer
If you're not making your own sounds (analogous to drawing your own sprites), then you're going to have to test many sounds from different sources, and see which ones work best for you.

If you really want good sounds, you might want to consider purchasing some royalty free sound packs. They usually come in bunches that sound pretty good together.

If you want the best sounds, then you're going to have to make them, or have them custom made to your requirements.

Just like with graphics, if you go for free, you're going to have to adapt to what's available. Not that it's a bad strategy though.
> 1 votes

# Answer
In addition to Panda Pajama's answer, I'd like to point out that audio in games is often neglected in literature. A "game engine" book will rarely have a good chapter on this, and resources on the internet are scarce.

But what is out there is a great starting point.

Studying what other games have done with audio is more difficult than with graphics. The subtleties are not as obvious.

One thing that will come up is needing to cut down on what sounds are being output at any given time, because if you don't do this, the player will get overwhelmed and the game will just sound bad.

EA/DICE's publications page has a section on Audio. Check that out. Game Engine Architecture book takes some time to discuss various intricacies as well.
> 1 votes

---
Tags: audio, sound-effects, graphics-design
---


title: Android Live Testing

text:
# Question
Title: Android Live Testing
I am making a game for android and in it I am using sensors which are not available in the emulator. At the moment I am connecting my device and transferring the apk, then installing to test but that is a pain to do, and I have gotten to the stage where I need to start logging values for debugging. I have gone into the run configs of my app and set it to prompt me to pick a device, but my device is never in the list when it is connected to my PC and I try to run it. How am I supposed to set it up to work properly?

Thanks for the help.

# Answer
This depends on what engine you are using. Are you using a custom engine? You could easily create a method when building your apk to upload it to your phone as well.

If you are using an already made engine then its dependent on that. Unity supports building to the phone, LibGDX does as well.

What are you creating this in?

EDIT: After reading your problem again. If your phone doesn't show up in ADT. You need to make sure you have the USB drivers for your phone installed. Make sure USP debugging is on. And if it's a Nexus device change the connected mode to camera and not media.
> 0 votes

---
Tags: android, testing, debugging
---


title: OpenGL slower than Canvas

text:
# Question
Title: OpenGL slower than Canvas
Up to 3 days ago I used a **Canvas** in a **SurfaceView** to do all the graphics operations but now I switched to **OpenGL** because my game went from **60FPS** to 30/45 with the increase of the sprites in some levels. However, I find myself disappointed because **OpenGL** now reaches around 40/50 FPS at all levels. Surely (I hope) I'm doing something wrong. How can I increase the performance at stable **60FPS**? My game is pretty simple and I can not believe that it is impossible to reach them.

I use 2D sprite texture applied to a square for all the objects. I use a transparent GLSurfaceView, the real background is applied in a ImageView behind the GLSurfaceView.

Some code

```
    public MyGLSurfaceView(Context context, AttributeSet attrs) {
        super(context);
        setZOrderOnTop(true);
        setEGLConfigChooser(8, 8, 8, 8, 0, 0);
        getHolder().setFormat(PixelFormat.RGBA_8888);
        mRenderer = new ClearRenderer(getContext());
        setRenderer(mRenderer);
        setLongClickable(true);
        setFocusable(true);
    }

    public void onSurfaceCreated(final GL10 gl, EGLConfig config) {
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glShadeModel(GL10.GL_SMOOTH);

        gl.glDisable(GL10.GL_DEPTH_TEST);

        gl.glDepthMask(false);

        gl.glEnable(GL10.GL_ALPHA_TEST);
        gl.glAlphaFunc(GL10.GL_GREATER, 0);

        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA);

        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glLoadIdentity();

        gl.glOrthof(0, width, height, 0, -1f, 1f);

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();
    }

    public void onDrawFrame(GL10 gl) {
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        gl.glMatrixMode(GL10.GL_MODELVIEW);
        gl.glLoadIdentity();

        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);

        // Draw all the graphic object.
        for (byte i = 0; i < mGame.numberOfObjects(); i++){
            mGame.getObject(i).draw(gl);
        }

        // Disable the client state before leaving
        gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
        gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
    }

```

mGame.getObject(i).draw(gl) is for all the objects like this:

```
    /* HERE there is always a translatef and scalef transformation and sometimes rotatef */

    gl.glBindTexture(GL10.GL_TEXTURE_2D, mTexPointer[0]);

    // Point to our vertex buffer
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTextureBuffer);

    // Draw the vertices as triangle strip
    gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVertices.length / 3);

```

**EDIT:**

After some test it seems to be due to the transparent GLSurfaceView. If I delete this line of code:

```
    setEGLConfigChooser(8, 8, 8, 8, 0, 0);

```

the background becomes all black but I reach 60 fps. What can I do?

# Answer
> 6 votes
Instead of using an ImageView and transparent GLSurfaceView you should instead render your background using a fullscreen quad (just like you do with your sprites, but sized to fit the entire screen).

Render this fullscreen background **first** (very important) and then also **remove** the `gl.glClear(GL10.GL_COLOR_BUFFER_BIT);` call in from `onDrawFrame`. You no longer need to clear the color buffer because your "full screen" background image will overwrite the entire surface (essentially doing the exact same thing as clearing) - this will also provide some performance increase.

Also, make sure that you disable **ALPHA BLENDING** before rendering your background image; you can enable it **after** the background image is rendered.

---
Tags: opengl, android, opengl-es, html-canvas
---


# Question
Title: Vector normalization gives very imprecise results
When I normalize vectors I receive very strange results. The lengths of the normalized vectors range from 1.0 to almost 1.5. The functions are all written by me, but I just can't find a mistake in my algorithm. When I normalize I just divide all components of the vector by the vector's length.

```
public double length(){
    return Math.sqrt(x*x + y*y);
}

public void normalize(){
    if(length() > 0){
        x /= length();
        y /= length();
    }
}

```

Is this supposed to happen? I mean I can see the length ranging from 0.9 to 1.1 at worst, but this is just overwhelming.

Cheers

# Answer
The third call to `length()` in your function uses the updated `x` value. You really don't want that.

Calculate the length once, then divide `x` and `y`.

```
double len = length();
if (len > 0) {
  x /= len;
  y /= len;
}

```
> 9 votes

---
Tags: java, mathematics, vector
---


# Question
Title: Unity AddExplosionForce not doing anything
Recently I've started learning Unity3D. I'm working on a game as an exercise in which you control a space ship and have to dodge asteroids. If you feel like it's getting a bit too much you can hit the space bar, emitting a blast in all directions that repulses nearby asteroids. To create this blast I have the following code:

```
public class PlayerBlastScript : MonoBehaviour {

public ParticleSystem BlastEffect;

// Update is called once per frame
void Update () {
    if (Input.GetKeyUp(KeyCode.Space)) {
        Fire();
    }
}

public void Fire() {
    ParticleEmitter effect = (ParticleEmitter) Instantiate (BlastEffect, transform.position, Quaternion.identity);
    effect.Emit();

    Vector3 explosionPos = transform.position;
    Collider[] colliders = Physics.OverlapSphere(explosionPos, 25.0f);

    foreach(Collider hit in colliders) {
        if (!hit) {
            continue;
        }

        if (hit.rigidbody) {
            hit.rigidbody.AddExplosionForce(5000.0f, explosionPos, 100.0f);
        }
    }
}
}

```

Even though the blast effect appears, the asteroids are not affected at all. The asteroids are all rigid bodies so what's the problem?

# Answer
> 1 votes
You're checking the colliders like they're boolean variables.

If a collider is inside `colliders`, it should have the explosion effect applied to it, there are no additional collision tests you need to do inside your `foreach` loop. However, you may want to check the type of object if you don't want things like power ups being affected by the blast effect.

You can change your code to be:

```
foreach(Collider hit in colliders) {
    hit.rigidbody.AddExplosionForce(5000.0f, explosionPos, 100.0f);
}

```

---
Tags: android, unity, rigid-body-dynamics
---


title: OnTrigger not firing consistently

text:
# Question
Title: OnTrigger not firing consistently
I have a Prefab called **Player** which has a **Body** and a **Sword**. The game uses 2 instances of **Player**, Player1 and Player2.

I use Player1 to strike Player2. This is code on the sword. My hope is that Sword of Player1 will log on contct with Body of Player2. It happens but only the first hit and then i have to hit several times before another strike is logged. But when i look at log from OnTriggerStay it looks like the TriggerExit is never detected untill long after the sword is gone.

```
    void OnTriggerEnter(Collider other)
{
    //Play sound to confirm collision
var sm = ObjectDirectory.soundManager;
    sm.PlaySoundClip(sm.gui_02);

    Debug.Log(other.name + " - ENTER" );

}

void OnTriggerStay(Collider other)
{
    Debug.Log(other.name + " - collision" );
}

void OnTriggerExit(Collider other)
{
    Debug.Log(other.name + " - HAS LEFT" );
}

```

DEBUG LOG:

> Player2 - ENTER UnityEngine.Debug:Log(Object) SwordControl:OnTriggerEnter(Collider) (at Assets/Scripts/SwordControl.cs:28)
>
> Player2 - collision UnityEngine.Debug:Log(Object) SwordControl:OnTriggerStay(Collider) (at Assets/Scripts/SwordControl.cs:34)
>
> (The last debug log then repeated hundreds of times long after the sword of player 1 had withdrawn and was in no contact with player 2 )

**EDIT:** Further tests shows that if i move player1 backwards away form player2 i trigger the OnTriggerExit. Even if the sword is not touching Player2 since after the blow. However even after OnTriggerExit it takes many tries untill i can get another blow registered.

# Answer
> 1 votes
I believe you have your code backwards. The trigger(on player 2) should be checking if a GameObject with a rigidbody AND a collider entered it, rather than if the sword entered the trigger.

In addition, your animation (or the collision itself) maybe happening to quickly, so the event may never get called.

# Answer
> 1 votes
So here's what's going on. You are calling `OnTriggerEnter()` which responds to ANY collider. You need to only check for the sword's collider. It should be something like this:

```
void OnTriggerEnter(Collider other)
{
if(other.collider.tag == "MeleeWeapon") {
    //Play sound to confirm collision
    var sm = ObjectDirectory.soundManager;
    sm.PlaySoundClip(sm.gui_02);

    Debug.Log(other.name + " - ENTER" );
}

}

void OnTriggerStay(Collider other)
{
   if(other.collider.tag == "MeleeWeapon")
   {
        Debug.Log(other.name + " - collision" );
   } else {
        Debug.Log("Another collider is hitting this object." )
   }
}

void OnTriggerExit(Collider other)
{
    if(other.collider.tag == "MeleeWeapon") Debug.Log(other.name + " - HAS LEFT" );
}

```

Just make sure to add the MeleeWeapon tag to the sword (and any other melee weapons). I don't know how you have your combat setup so I can't give you an accurate way of handling this. But this will fix the problem you are having.

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


# Question
Title: Getting and playing AudioClips by string name
Is there anyway I can get an audioclip by the name it has in the assets folder? Or will I always have to make a reference to it by dragging and dropping the clip on a SoundClip in the inspector?

# Answer
> 0 votes
There is no way to achieve this out of the box. Unity requires an AudioClip reference for the PlayOneShot method.

You'll need to write a simple audio manager to achieve this, or simply include a reference to the clip in your script.

---
Tags: unity, assets
---