# Question
Title: When does a game need an official age-rating?
When is it required for a game to receive a rating by an official or quasi-official rating board like the PEGI or the ESRB? I know that almost every game which is sold in a brick-and-mortar store almost anywhere in the world must have an age label. But what about games which are distributed globally as download or browser-based games? Is there a reason to get a content-rating for such a game? When yes, which rating board(s) need to rate it, considering that anyone in the world can play it and each country has its own local rating system with different criteria?

# Answer
Game ratings are not enforced by any country for any kind of game. They'll just ban your game, if they found it objectionable enough. The rating is more of a de-facto standard used to make the end-user aware about the content of the game, so that kids do not play games containing extreme violence.

You'll be required to submit ratings only if you're making games for major consoles, such as PlayStation, XBox or Wii. Microsoft accepts ESRB and few other ratings for games in Windows Phone and Windows RT platform too, although it's optional.

Sony, Nintendo and Microsoft will fail your game unless you have a proper age rating, as this is a major compliance criteria for any game submission. The compliance is known as TCR for XBox, TRC for PlayStation and LotCheck for Nintendo Wii/DS/DSi.

**Update:-**
There're few countries which requires explicit rating by one of the approved rating agency to be eligible for distribution. As found at WP game rating guidelines `Brazil`, `Russia` and `South Korea` requires game rating from one of their approved rating agency, while in `Taiwan` you need to self declare the age rating yourself. If you don't put any rating while submitting your game, Microsoft will not distribute your game to these countries. Apple in this case asks developers to rate their own game and checks thoroughly if they put it correct as part of their submission process.

India on the other hand use their own Govt. agency CBFC to rate a game. However CBFC is primarily for movie ratings and they generally don't enforce any publisher to make a rating submission, although they can use their own discretion to ban a game. Also as mentioned by Andon M. Coleman in the comments below, Australia doesn't enforce you to make a rating submission, however that's only if your game doesn't have any adult content. If it does, then you'll have to submit it for rating analysis or else it'll be banned till you do.

In short the the ratings are enforced mostly by the distribution channel you're using, since they don't want to lose their credibility and would like to keep their customers happy. Govt. doesn't have anything in that(except for few countries such as Brazil, Russia and South Korea). So to answer your question, when does a game need an official age rating, it's when your distribution channel requires it and that's too dependent on the region where you want to distribute your game.

More info about the rating system being used in various countries can be studied from this wikipedia link.

PS: I've tried to put as much info as I could get for the countries which I got to know about. This answer might not be true for few other countries which actually requires the game to be rated. Feel free to let me know if you know something which I've not mentioned here.
> 9 votes

---
Tags: content-rating, esrb, pegi
---


title: Converting Doom maps to JSON

text:
# Question
Title: Converting Doom maps to JSON
This is a really cool demo of a Canvas Doom Engine made back in 2006:

http://canvex.lazyilluminati.com/84/play.xhtml

Here is the e1m1 map in JSON format:

http://canvex.lazyilluminati.com/84/map1.js

Does anyone know of the tool used to convert Doom maps into JSON? I can't imagine this was done by hand :)

# Answer
I've found a Python script that converts MAP data from a WAD to JSON: https://github.com/nicokruger/py-wad2json

Combine that with Unwad, a utility that extracts all other data from a WAD: https://code.google.com/p/unwad
> 1 votes

# Answer
It probably was not done by hand, but as the WAD file format is pretty well documented it was probably relatively easy to write a one-off tool to perform the conversion. It's possible one of the WAD editors floating around have the functionality buried away, but I suspect that the author used a tool he wrote himself (and has not released) in this case.

The JSON structures and arrays used in the linked JSON file don't seem to correspond directly to the lump types in the WAD file, which suggests a custom tool to me. It looks like some of his maps aren't direct ports of DOOM maps either (at least none I recognize) so it's possible he's using an internal map building tool instead of just an internal JSON conversion tool.

The author's email is at the bottom of his homepage. You'd probably get a better response if you ask him directly.
> 6 votes

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


# Question
Title: How to display consistent background image
Drawing a large background is relatively slow in PyGame. In order to avoid drawing BG every frame, you could draw it once, then do nothing.

However, if something is overdrawn onto the surface and keeps moving, you will need to redraw the background in order to "erase" the color pixels left by moving object; otherwise, you will have "traces" of the moving object.

I have a moving object in my PyGame. However, I do not want to "clear the color buffer" by redrawing the background image. Redrawing the background image every frame is slow.

My solution :

I will "clear" only required portions (where the "traces" of moving object are left) of the "buffer" by redrawing portions of background.

Is there any other better way to have a consistent background?

# Answer
If I understand you correctly, you don't want to have to redraw the entire screen when a single object changes position. You've basically hit upon the solution; only redraw the portion of the screen that you need to. One method to do this is dirty rectangles. Roughly, the algorithm is:

1. Get the objects that will be moving this frame.
2. Get their bounding boxes, before they move. Call this list of boxes `B`.
3. For each box `b` in `B`, check if `b` is intersecting bounding boxes of objects that aren't moving. If it is, union those the boxes (including `b`) and replace `b` with this new rectangle.
4. Redraw all the portions of the background defined by the rectangles in `B`, as well as all the entities to which those rectangles belong.

However, clearing the screen and redrawing everything should be fast enough nowadays. If you have already tried redrawing everything every frame and it is slow, you may want to ensure there's not something else suspicious going on.
> 1 votes

---
Tags: python, pygame
---


title: Rendering shadow sprites in cocos2d-x

text:
# Question
Title: Rendering shadow sprites in cocos2d-x
I am writing a 2D game with cocos2d-x. I want to put a "shadow" sprite on a background sprite using the equation:

> MAX(0, Cd * 1 - Cs * S)

where `Cd` is the destination color (that is, a background pixel), `Cs` is the source color (the shadow pixel), and `S` is the scale factor (between 0 and 1). The `MAX()` function is used to avoid negative results. This is a lighting effect: when the shadow sprite pixel is 0, there is no effect on the background pixel, otherwise, the background pixel becomes darker.

Now, the only way that comes to my mind is to change the blending equation to `GL_FUNC_SUBTRACT`, but it doesn't compile with cocos2d-x (can't found it).

I would subclass the `CCSprite` class in order to implement the `draw()` method in order to change, when needed, the blending equation, call the original `draw()` method and restore the blending equation to its previous state at the end of the method.

So my questions are two:

1. How to use `glBlendEquation()` with cocos2d-x? Keep in mind that I am writing a game for iPhone/Android/Windows.
2. Are shadows handled this way in 2D games?

# Answer
> 1 votes
cocos2d is not much different than a normal opengl app. there are some basic states that is set while you are running a cocos2d app, but other than that every thing is just the same as a normal opengl application. I guess the normal way of using `glBlendEquation` or `glBlendFunc` is to inherit some class from `CCSprite` class (or any other class that you want it to drop shadow) and then override `draw` method. it will look something like this :

```
-(void) draw
{
    // create a backup from glBlendEquation
    // do somthing with glBlendEquation
    [super draw];
    // restore glBlendEquation options
}

```

I'm not familiar with either obj-c nor opengl (I'm using cocos2d-x in c++ and occasionally needed to add some basic opengl function), but from what I know the code above should work.

# Answer
> 0 votes
Answer 1:

You can use shaders if you want to go for *glBlendEquation*. Have a look here;

Please note that, using more amount of shaders can effect the performance of some devices.

Answer 2:

And if light direction is constant in your game, than you can attach shadow with graphics only (i.e in PNG only). Or you can use separate dark shadow image with some transparency. There are the lightweight solutions.

---
Tags: sprites, cocos2d, shadows
---


# Question
Title: How do I scale a rectangle image while retaining its border thickness?
I want to create a *programmatically* scalable image like this: scales to .

Both have a one pixel border. If I scaled from the first to the second in Paint.NET, there would be a two pixel horizontal border, but I want it to keep it single-pixel.

# Answer
You need to slice the image up in 9 parts. Four corners, four sides and the inner content.

In this image, you can see how each different slice can be resized to produce the result you desire. Do not scale corners, leave them be as they are. Then you need to scale the top and bottom side along x-axis, but not in y. And then left and right sides you need to scale in y axis, but not in x. Then obviously you need to scale the inner slice along both axis.

This can be done in multiple ways. I'm most familiar with OpenGL, so I'd just define the texture coordinates for the 9 different quads' vertices. You could also slice the image up in photoshop and use different parts of it as different textures (which is very slow, to be noted).
> 3 votes

# Answer
If your blocks really are as simple as a fill colour with a 1-pixel outline, you could just generate each image from scratch as you need it.

Here's a `bash` script using ImageMagick's `convert` program:

```
#!/bin/bash
declare -i width
declare -i height
width=$1
height=$2

convert \
    -size "$width x $height" \
    canvas:#ffd \
    -fill none \
    -stroke red \
    -strokewidth 1 \
    -draw "rectangle 0,0 `expr $width - 1`,`expr $height - 1`" \
    block.png

```

Running the script with arguments `50 50` produces , while `50 25` makes and `100 10` .

You can of course do this with any other graphical toolkit if you want the images at run-time.
> 0 votes

---
Tags: java, graphics, scale, content-generation
---


# Question
Title: What's the best way to move cars along roads
I am implementing car movement game (sort-of like Locomotion). So 60 times a second I have to advance the movement of each car. The problem is I have to look ahead to see if there is a slower car, stop sign, or red light ahead. And then slow down appropiately.

I also want to have the cars take time to go from stopped to full speed and again to slow down. I'm not implementing full-blown physics, but just a tick by tick speed up/slow down as that provides most of the realism to match what people expect to see.

The best I've come up with is to walk out the full distance the car would travel of it was slowing to a stop and see if anywhere along that path it needed to slow down or stop. And then move it forward appropiately.

I am moving the cars 60 times a second so I need this to be fast. And walking out that whole path each tick strikes me as processor intensive.

What's the best way to do this?

# Answer
First of all I would look into making computational intensive chunks less frequent. 60 updates per second sounds like way too many.

See if you can employ future planning - checking every obstacle returns for how many ticks it will be safe to ignore. E.g. when car checks its path ahead redlight "says" it wont switch for 240 ticks and slower car "says" it will not brake in next 157 ticks. So u safe to skip next equivalent of 157 ticks with regard to cars acceleration and etc - e.g. 124 ticks.

Another idea is to make it event-driven, so redlight would notify all cars in radius that they are required to stop. Same with traffic cars.

P.S. You did not mentioned how complex is your maps topology. Is it like freeways or tight streets with many intersections.
> 1 votes

# Answer
Real-life systems like these usually use a form of fuzzy logic along with other control systems. Scan the surroundings to give the fuzzy logic system inputs regarding how close obstacles are, grade of turn, etc., as well as current speed, turning angle, and other vehicle state. Those inputs are used to calculate steering, breaking, gas, and so on. The obstacle detection can also take into account obstacles that aren't just in front of the vehicle but also around it, consider their relative velocities to the AI vehicle, accelerations, etc. The systems get complex but they're built off the same foundation.

Additional reading:

More game-y applications (racing games) still use similar approaches. Some are using neural networks and human players to teach the AI about how to respond rather than a manually-designed fuzzy system. Sometimes they even bake the neural net independently for each course letting the AI learn tricks specific to that course, e.g. when best to start turning to pull off a particularly tricky drift in a racing game.
> 1 votes

---
Tags: path-finding, movement, vehicle
---


title: How to export textures with JarSplice?

text:
# Question
Title: How to export textures with JarSplice?
I have another game that uses rectangles instead of textures which works fine. When I run it I get this error:

```
C:\Users\Owner>cd desktop

C:\Users\Owner\Desktop>java -jar FLIPPERFLAP1.0.jar
java.io.FileNotFoundException: res\FlubberFlap.png (The system cannot find the path specified)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:131)
        at FSMain.MainFS.main(MainFS.java:68)

C:\Users\Owner\Desktop>

```

In line 68 where I load the texture, I do this :

```
wood = TextureLoader.getTexture("PNG", new FileInputStream(new File("res/SuperGuy.png")));

```

It works when I use the IDE (eclipse) but not after exported. The images are in a source folder called res. When I use JarSplice do I have to export the textures in natives or jars?

# Answer
> -1 votes
First step is make sure you have the resources bundled with the JAR you create. Try to move the `res/` folder inside the `src/` folder. And export the jar like this.

And create the fat jar as you did. This gets rid of the Eclipse's JAR in JAR loader.

---
Tags: java, textures, lwjgl, jarsplice
---


# Question
Title: How to properly handle top down 2D collision?
I can never seem to get this right, well polished at least. I'm creating a top down game in XNA, and collision has always been an issue for me to do properly. Detecting collision is fine, but resolving it is where I get messed up.

My approach so far:

* Loop through rectangles polled by a quad tree
* check if these rectangles intersect with the player
* if yes then undo the velocity that we just applied to the player
* if no then do nothing

This approach is less than ideal but it's close, I'm trying to allow players to move along the wall even if they're applying the force on the wall.

For example: if the player collides against a vertical wall, they should be able to move up and down even if they are still trying to move left/right.

I can't seem to find a good way to do this. Maybe I'm overthinking, but I tried doing vector subtraction on the centre's of the player and tile and seeing where the vector pointed. But that didn't give me much helpful information. I tried seeing if it was the x-axis or y-axis that was colliding but that didn't work as the player is bigger than the tiles.

Is there a way to find which axis is colliding so I can undo velocity on that specific axis?

# Answer
> 2 votes
Take a look at the SAT Tutorial that Anko linked in comments. The tutorial explains everything you need to know.

Specifically, what you want to find is the "minimum penetration vector" (that tutorial calls it the "projection vector" and shows it as a purple arrow).

Your collision response, right now, is to cancel out all movement - which is obviously not working. What you need to be doing, as collision response, instead, is "separation" (not the same thing as the "separating axis" in SAT).

As the tutorial says, you take the minimum penetration vector and move your player backwards by that vector to separate them from the world geometry.

Because you've now "stopped" in that direction, you need to clear the velocity in that direction. Do this by projecting your velocity vector onto the tangent of the minimum penetration vector. (You could also add in further response such as bouncing and friction.)

---
Tags: xna, c#, 2d, collision-resolution
---


# Question
Title: determine collision angle on a rotating body
update: new diagram and updated description

I have a contact listener set up to try and determine the side that a collision happened at relative to the a bodies rotation. One way to solve this is to find the value of the yellow angle between the red and blue vectors drawn above. The angle can be found by taking the arc cosine of the dot product of the two vectors (Evan pointed this out). One of my points of confusion is the difference in domain of the atan2 function *html* *canvas* *coordinates* and the Box2d rotation information. I know I have to account for this somehow... SS below

questions:

* Does Box2D provide these angles more directly in the collision information?
* Am I even on the right track? If so, any hints?

I have the following javascript so far:

```
Ship.prototype.onCollide = function (other_ent,cx,cy) {

  var pos = this.body.GetPosition();

  //collision position relative to body
  var d_cx = pos.x - cx;
  var d_cy = pos.y - cy;

  //length of initial vector
  var len = Math.sqrt(Math.pow(pos.x -cx,2) + Math.pow(pos.y-cy,2));

  //body angle - can over rotate hence mod 2*Pi
  var ang = this.body.GetAngle() % (Math.PI * 2);

  //vector representing body's angle - same magnitude as the first
  var b_vx = len * Math.cos(ang);
  var b_vy = len * Math.sin(ang);

  //dot product of the two vectors
  var dot_prod = d_cx * b_vx + d_cy * b_vy;

  //new calculation of difference in angle - NOT WORKING!
  var d_ang = Math.acos(dot_prod);

  var side;
  if (Math.abs(d_ang) < Math.PI/2 )
    side = "front";
  else
    side = "back";

  console.log("length",len);
  console.log("pos:",pos.x,pos.y);
  console.log("offs:",d_cx,d_cy);
  console.log("body vec",b_vx,b_vy);
  console.log("body angle:",ang);
  console.log("dot product",dot_prod);
  console.log("result:",d_ang);
  console.log("side",side);
  console.log("------------------------");

}

```

# Answer
> 2 votes
I have a result that works. Some things that I didn't get right initially..

* efficient formula (thx user Evan)
* possible negative body rotation
* extra 90° where Box2D and html canvas rotation begins

---

```
Ship.prototype.onCollide = function (other_ent,cx,cy) {

  var pos = this.body.GetPosition();

  //collision position relative to body
  var d_cx = pos.x - cx;
  var d_cy = pos.y - cy;

  //length of initial vector
  var len = Math.sqrt(Math.pow(pos.x -cx,2) + Math.pow(pos.y-cy,2));

  //body angle - can over rotate hence mod 2*Pi
  var ang = this.body.GetAngle() % (Math.PI * 2);

  //adjust negative rotation
  if (ang < 0) { ang = (Math.PI * 2) + ang; }

  //vector representing body's angle - same magnitude as the first
  var b_vx = Math.cos(ang- Math.PI/2);
  var b_vy = Math.sin(ang- Math.PI/2);

  //dot product of the two vectors
  var dot_prod = d_cx * b_vx + d_cy * b_vy;
  dot_prod /= len;

  //resulting angle
  var d_ang = Math.acos(dot_prod);

  var side;
  if (Math.abs(d_ang) > Math.PI/2 )
    side = "front";
  else
    side = "back";

}

```

---
Tags: javascript, box2d, trigonometry
---


title: Effective content manager on AS3 Flash

text:
# Question
Title: Effective content manager on AS3 Flash
In my game more than 600 images and 200 sounds. I'm try organize effective images and sounds manager for fast access. This is a good approach?

```
public class Images
{
    public static var image_1:BitmapData;
    public static const image_1_class:Class;

    public static var items_icons:Vector<BitmapData>;
    public static const item_1_class:Class;
    public static const item_2_class:Class;

    ...
}

// initialization
Images.image_1 = new Images.image_1_class().bitmapData;
Images.items_icons[0] = new Images.item_1_class().bitmapData;
Images.items_icons[1] = new Images.item_2_class().bitmapData;

// using
new Button().setTexture(Images.button_close);
sounds.playRandom(Sounds.gnome_hit);

```

# Answer
Obviously it isn't a good approach to inline ~800 assets because it really is a chore to set up. You could pack your images into an atlas, so that you only have to load one or a few large files.

It also depends whether or not you want your resulting swf file to include all the assets or if you can load them from external sources. If the latter is the case, you could load all files from a folder (when it's an AIR application) or load the files from a webserver.

You could also write a shell-script that writes your "Asset-Classes" automatically. Eg. some script that lists all files from your asset folders and creates the actionscript for them automatically. That way you can do something more productive than referencing 800 assets manually.

If you're looking for ideas how to write an asset/resource manager, I suggest you have a look at the implementation of the `AssetManager` inside the Starling Framework.
> 0 votes

---
Tags: flash, actionscript-3, resource-management, asset-management
---


# Question
Title: Incomplete mesh using DrawIndexedPrimitives after rotating mesh
Through help on this site I was able to draw the triangles of an unrotated, nonscaled nontransformed mesh created in Blender and exported to OBJ, accurately imported through Assimp and rendered in XNA Graphics. However after applying rotation on a single axis in Blender(Z) and adding materials(I wanted to test loading of materials through Assimp) the same mesh appears incomplete. Is something wrong with my view matrix or is it something else?

This is what the unrotated mesh looks like:

Here is the rotated mesh:

Camera, View and Projection are defined as follows:

```
cameraPos = new Vector3(0, 5, 9);
viewMatrix = Matrix.CreateLookAt(cameraPos, new Vector3(0, 0, 1), new Vector3(0, 1, 0));
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 1.0f, 200.0f);

```

Rendering is done through this code:

```
device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
effect = new BasicEffect(GraphicsDevice);
effect.VertexColorEnabled = true;

effect.View = viewMatrix;
effect.Projection = projectionMatrix;
effect.World = Matrix.Identity;

foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
    pass.Apply();
    device.SetVertexBuffer(vertexBuffer);
    device.Indices = indexBuffer;
    device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, oScene.Meshes[0].VertexCount, 0, mMesh.FaceCount);
}
base.Draw(gameTime);

```

# Answer
Without being able to see the contents of the .OBJ file, I can't tell what the problem might be. Given only 1 face is showing I suspect the application of materials has split your model up into 6 meshes, and if the rest of your code is the same as your previous question, you are only loading the first mesh in your scene.

Try exporting 2 version of your cube, 1 with a rotation applied, and the other with materials applied. If the rotated version works properly, but the version with materials doesn't, then it may be the problem described above. In that case, try the code below (or just try it anyway)

```
VertexBuffer[] vertexBuffers;
IndexBuffer[] indexBuffers;

private void SetUpVertices()
{
    int count = oScene.MeshCount;
    vertexBuffers = new VertexBuffer[count]
    indexBuffers = new IndexBuffer[count]

    Mesh mMesh;
    for (int m = 0; m < count;m++)
    {
         mMesh = oScene.Meshes[m];
        vertices = new VertexPositionColor[mMesh.VertexCount];
        indices = new  short[mMesh.FaceCount*3];

        int i=0;
        foreach (Vector3D mVec in mMesh.Vertices)
        {
            vertices[i] = new VertexPositionColor(new Vector3(mVec.X, mVec.Y, mVec.Z), Color.Red);
            i++;
        }

        int f = 0;
        Face mFace;
        for (i = 0 ; i < mMesh.FaceCount*3 ; i=i+3)
        {
            mFace = mMesh.Faces[f];
            f++;
            indices[i] = (short)mFace.Indices[0];
            indices[i + 1] = (short)mFace.Indices[1];
            indices[i + 2] = (short)mFace.Indices[2];
        }

        vertexBuffer = new VertexBuffer(device, VertexPositionColor.VertexDeclaration, vertices.Length, BufferUsage.WriteOnly);
        vertexBuffer.SetData(vertices);

        indexBuffer = new IndexBuffer(device, typeof(short), indices.Length, BufferUsage.None);
        indexBuffer.SetData(indices);

        vertexBuffers[m] = vertexBuffer;
        indexBuffers[m] = indexBuffer;
    }
}

protected override void Draw(GameTime gameTime)
{
    device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.DarkSlateBlue, 1.0f, 0);
    effect = new BasicEffect(GraphicsDevice);
    effect.VertexColorEnabled = true;

    effect.View = viewMatrix;
    effect.Projection = projectionMatrix;
    effect.World = Matrix.Identity;

    for (int i = 0; i < vertexBuffers.Length; i++)
    {
        device.SetVertexBuffer(vertexBuffers[i]);
        device.Indices = indexBuffers[i];

        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Apply();
            device.DrawIndexedPrimitives(Microsoft.Xna.Framework.Graphics.PrimitiveType.TriangleList, 0, 0, vertexBuffers[i].VertexCount, 0, indexBuffers[i].IndexCount);
        }
    }
    base.Draw(gameTime);
}

```

With this code, you might want to define your own custom scene class that takes a Assimp Scene object, calls the SetUpVertices function, and defines a public Draw method if you plan on having multiple scenes in your game.
> 1 votes

---
Tags: xna, camera, rotation, mesh
---


# Question
Title: Do I have to use new keyword for unity single game object?
I'm using Unity4. Do I have to use new keyword for single game object? look at the following code.

1. `GameObject obj = new GameObject();
obj = Resources.Load("Prefabs/Ball", typeof(GameObject)) as GameObject;`

2. `GameObject obj;
obj = Resources.Load("Prefabs/Ball", typeof(GameObject)) as GameObject;`

is it the same?

# Answer
> 3 votes
These are not the same. `Resources.Load` is going to create a new uninstantiated `GameObject`.

This means your first example is going to create a new game object, then set that object equal to the new game object created by `Resources.Load`. That means two objects are going to be created, an empty game object added to the scene (from the `new GameObject()` call) and an uninstantiated game object from the `Resources.Load` call.

It's worth noting that just using `Resources.Load` for a prefab will not create that prefab in the scene like `new GameObject()` creates a gameobject in the scene. Likely, what you intend to do is:

```
GameObject obj;
obj = GameObject.Instantiate(
         Resources.Load("Prefabs/Ball", typeof(GameObject))) as GameObject;

```

Note the additional use of `Instantiate` to create the loaded prefab into the scene.

# Answer
> 0 votes
In Addition to `Byte56`'s answer, I'd like to mention that Unity forbids using `new` keyword for any MonoBehavior, since they are present in the scene and are already created. You'll most probably get a warning if you do that. You can create new Gameobject if you just want to have an empty GameObject in the scene.
You can't manually create a MonoBehavior using new keyword. You can however use Instantiate() for prefabs and AddComponent for Components. To use one of the already created MonoBehavior or GameObject which is present in the scene, you're encouraged to either make a public variable and drag the GameObject in the script from editor or use GameObject.Find() to use it directly from script without dragging and dropping. First method is faster and thus recommended way.

---
Tags: unity, gameobject
---


# Question
Title: Scaling sprites in a spritesheet without changing the overall size of each image
It might be more of a graphics software question - but, well, it concerns game development.

I'm using some free spritesheets found in the web, and basically one of the characters seems slightly scaled, causing it to poorly fit the others. I'm looking for a quick way to scale the individual images in this particular spritesheet, while keeping the original spritesheet "bounds" (sprites positions, sizes of individual images). In other words, I want to scale a whole bunch of separate image parts, without scaling the image as a whole (and without spending hours on it).

Wouldn't mind a solution using GIMP or a specific spritesheet manager application.

# Answer
OK, I've actually figured it out after looking at some tools available. I guess I can post my solution in case anyone ever encounters a similar problem:
**1.** Scale the whole spritesheet to your preferred size. GIMP is a good tool for that, I guess.
**2.** Cut the spritesheet into separate (smaller than original) sprites. I've done it with http://imagesplitter.net/ \- it's pretty easy and fast to use.
**3.** Using the ImageMagick tool, make another spritesheet from the scaled sprites. The command for this would be something like:

```
montage *.png -tile XxY -geometry WIDTHxHEIGHT+XOFFSET+YOFFSET -background transparent NAME

```

Where: `X` is the number of columns, `Y` is the number of rows, `WIDTH` is the width of a **new** single sprite, `HEIGHT` is the height of a **new** single sprite, `XOFFSET` is half of the amount of pixels needed to make the new sprite match the original width, `YOFFSET` is half of the amount of pixels needed to make the new sprite match the original height and `NAME` is the name of the file of the new spritesheet. You calculate offsets with this formula: `Offset = (OldSize - NewSize) / 2`. For example, if your old size was 128/128px and after scaling it's 110/110px, you'd have to enter `-geometry 110x110+9+9`.
**4.** While you might be already done by this step, sometimes you may want to move the sprites a little (they will be centered and basically they will "start" a little higher, so unless you're making a top-down game, the sprites will probably appear to be floating in the air). Again, GIMP comes in handy: select the whole image and move it down a few pixels - that should do it.
> 0 votes

---
Tags: graphics, spritesheet
---


title: Hide part of the GUITexture in Unity

text:
# Question
Title: Hide part of the GUITexture in Unity
I have a Health Bar in my **Unity** game and it's implemented as a `GUITexture` with gradient image from red to green.

Now I can reduce it's width from max width to 0, but is still scaled gradient.

```
public void UpdateHealthBar(int hitPoints) {
    healthBar.pixelInset = new Rect(
        healthBar.pixelInset.x, healthBar.pixelInset.y,
        3* hitPoints, healthBar.pixelInset.height);
}

```

But I want to hide (make transparent) the right part of this health bar in game progress.

How can I do this? Thanks!

# Answer
> 2 votes
You can do this via script, using GUI.DrawTextureWithTexCoords

This lets you clip-out a rectangle of the texture you want to draw onto the screen.

For instance (within an OnGUI() method)....

```
float healthFraction = ((float)hitPoints)/maxHitPoints;

Rect screenRect = new Rect(xPosition, yPosition, healthFraction * width, height);
Rect textureRect = new Rect(0, 0, healthFraction, 1);

GUI.DrawTextureWithTexCoords(screenRect, texture, textureRect);

```

# Answer
> 0 votes
Or if you're using `NGUI`, you can use `UISlider` for this. It'll automatically handle vertical, horizontal and radial progression using part of the image.

---
Tags: unity, textures, gui
---


# Question
Title: Does calling VSSetShader() twice with the same shader have a performance penalty?
Let's say I render 2 objects that are using the same shader (and the same `ID3D11VertexShader` object). When I call `VSSetShader()` to set the shader for the 1st object `DirectX` has to change previous shader to the new one which takes some `CPU`/`GPU` time. But when I then render the 2nd object and call `VSSetShader()` again with the same argument(s) does it set the shader again (and take as much `CPU`/`GPU` time as before) or is `DirectX` "smart" enough to figure out it's the same shader and it doesn't have to change anything?

Actually, I'd like to ask a broader question - does the same hold true for other analogous state changing function calls? Like setting buffers, sampler states, blending states etc... Pretty much whenever it's a matter of "applying"/"setting as current" objects and states when I actually try to set the same as before.

# Answer
> 2 votes
Looking at the doc on MSDN, it says nothing about having that functionality. It just sets "a vertex shader to the device." So while it might be included as part of the driver-implementation for a specific gpu, there is no requirement that a vender includes that functionality.

It would be best to avoid relying on your driver to check. If you need to, do the check yourself. Should be simple enough. Perhaps:

```
const ID3D11VertexShader* g_SetShader;

void SetShader(ID3D11VertexShader* shader, ...)
{
    if (shader == g_SetShader)
    {
        return; // the shader is already set
    }

    //...

    g_SetShader = shader;
    return;
}

```

And as a result of you being able to implement a check yourself, the programmers for the driver could well have just not included that check (making their implementation a little bit faster than it would be otherwise.)

Even better would be to have a system setup to avoid the need for the check all-together. eg.

```
for each shader
{
    bind shader
    for each object using shader
    {
        render object
    }
}

```

---
Tags: directx, state
---


# Question
Title: How can I find the largest sphere that fits inside a frustum?
How do you find the largest sphere that you can draw in perspective?

Viewed from the top, it'd be this:

Added: on the frustum on the right, I've marked four points I think we know something about. We can unproject all eight corners of the frusum, and the centres of the near and far ends. So we know point 1, 3 and 4. We also know that point 2 is the same distance from 3 as 4 is from 3. So then we can compute the nearest point on the line 1 to 4 to point 2 in order to get the centre? But the actual math and code escapes me.

I want to draw models (which are approximately spherical and which I have a miniball bounding sphere for) as large as possible.

Update: I've tried to implement the incircle-on-two-planes approach as suggested by bobobobo and Nathan Reed:

```
function getFrustumsInsphere(viewport,invMvpMatrix) {
    var midX = viewport[0]+viewport[2]/2,
        midY = viewport[1]+viewport[3]/2,
        centre = unproject(midX,midY,null,null,viewport,invMvpMatrix),
        incircle = function(a,b) {
            var c = ray_ray_closest_point_3(a,b);
            a = a[1]; // far clip plane
            b = b[1]; // far clip plane
            c = c[1]; // camera
            var A = vec3_length(vec3_sub(b,c)),
                B = vec3_length(vec3_sub(a,c)),
                C = vec3_length(vec3_sub(a,b)),
                P = 1/(A+B+C),
                x = ((A*a[0])+(B*a[1])+(C*a[2]))*P,
                y = ((A*b[0])+(B*b[1])+(C*b[2]))*P,
                z = ((A*c[0])+(B*c[1])+(C*c[2]))*P;
            c = [x,y,z]; // now the centre of the incircle
            c.push(vec3_length(vec3_sub(centre[1],c))); // add its radius
            return c;
        },
        left = unproject(viewport[0],midY,null,null,viewport,invMvpMatrix),
        right = unproject(viewport[2],midY,null,null,viewport,invMvpMatrix),
        horiz = incircle(left,right),
        top = unproject(midX,viewport[1],null,null,viewport,invMvpMatrix),
        bottom = unproject(midX,viewport[3],null,null,viewport,invMvpMatrix),
        vert = incircle(top,bottom);
    return horiz[3]<vert[3]? horiz: vert;
}

```

I admit I'm winging it; I'm trying to adapt 2D code by extending it into 3 dimensions. It doesn't compute the insphere correctly; the centre-point of the sphere seems to be on the line between the camera and the top-left each time, and its too big (or too close). Is there any obvious mistakes in my code? Does the approach, if fixed, work?

# Answer
I shall assume that your frustum is symmetrical, since your drawing seems to suggest so. There are three constraints (two if your frustum is 2D):

### A. the sphere cannot be larger than the distance between the near and far planes

If `D` is the near-far distance, the first constraint is simply:

```
R ≤ D / 2

```

### B. the sphere cannot grow wider than the side planes

Now for the other constraint, let’s say `α` is the half-angle of the frustum and `L` is the half-width of the far plane, as shown in this drawing:

The first formula is given by trigonometry in the triangle. The second comes from the sum of a triangle’s angles. Which gives us the second constraint:

```
R ≤ L tan((π - 2α) / 4)

```

If your frustum is 3D, you'll have a third constraint with new `L` and `α` values.

### Final result

The `R` value you are looking for is the `min` of the three bounds.

### How to get the parameters

If you can unproject the frustum in view or world space, you can compute L, D and α in the following way, where the `P` points are from the near plane, and the `Q` points are from the far plane:

Arrows mean vectors, “.” is the dot product, and || indicates the length of a vector. Replace `Q2` with `Q3` and `P2` with `P3` to get L and α in the vertical dimension.
> 12 votes

# Answer
In 2D: consider the frustum as a triangle (2D)

You then want to find the incircle of the triangle.

As a 3D problem, you need to find the insphere of a square based pyramid.

If I had the formula I would print it here, but alas, I do not know the formula.
> 2 votes

# Answer
The Biggest Sphere possible should touch the far-plane (using the terms for view-frustrums here) right in the center. It would also touch the top/bottom or the left/right planes, depending on which FoV-angle is smaller. I have to say that i don´t have an actual mathematical proof for those assumptions, but they should be right. Maybe someone has an idea on how to proof this.

A Sphere can be defined by it´s center point and a radius. Cx and Cy is the same as the center of the farplane.

Cz and the radius can be obtained by solving an equation system based on the assumptions listed above.

T is one of the either bottom/top plane or left/right plane (see above) with t1,t2 and t3 as normalized normal vector and t4 as distance from origin. f is the center of the farplane.

t1\*cx + t2\*cy + t3\*cz - t4 = r

-fz + cz = r

t1\*cx + t2\*cy + t3\*cz - t4 = -fz + cz

t1\*cx + t2\*cy + fz - t2 = +cz - t3\*cz

t1\*cx + t2\*cy - fz - t2 = cz * (1 - t3)

cz = (t1\*cx + t2\*cy - fz - t2) / (1 - t3)

r is then calculated by inserting cz into this: -fz + cz = r

You can obtain all planes from the Projection Matrix youre using. (Not ViewProjection in this case)

afterwards you have to move the sphere to the right space: C' = inverse(View) * C
> 1 votes

# Answer
I'm attempting to do something similar, and in my case, speed is more crucial than accuracy as long as the sphere does not exist outside any of the frustum's bounds.

If you calculate the shortest distance between linesegs (or faces in 3d), the shortest distance found could be used as the diameter of an incircle/insphere which lies fully inside the frustum. The origin of the incircle/insphere could simply the average of all vertices (sum & divide). It would be quite fast and also work for all types of convex polyhedra.

The only drawback is that the circle or sphere won't necessarily be the largest incircle or insphere possible. For a frustum with a lot of volume and one very short edge, the circle/sphere would share much less of the frustums space than possible.

**Another Idea**

If you want the insphere of a 3D view-frustum and you have the perspective matrix used to construct this frustum, then you could simply use that matrix on the insphere of a unit cube, and that should be a perfect insphere for the frustum. (The diameter of the insphere of a cube is the length of one of the cube's edges, the center is the middle of the cube which is the average of the cube's vertices)
> 1 votes

---
Tags: geometry
---


# Question
Title: Should I use different input layout for meshes (vertices) with and without normal maps?
I'm writing an DirectX11 game.

About 60% of my game models (or "of my vertices") have:

1. Position
2. Texture coordinate

Some of them use:

1. Position
2. Texture coordinate
3. Normals

And few of them:

1. Position
2. Texture coordinate
3. Normals
4. Tangents
5. BiTangents

And I have about 10 shaders:

* 3 of them assume that vertices have just position and texture coordinates
* 5 that they also have normals
* 2 make use of tangent/bi-tangent info

The question is: **should I create 3 vertex structures and 3 `D3D11_INPUT_ELEMENT_DESC` arrays for them (option 1)?** Or create only one, universal vertex structure (the last one, 5 members) and 1 `D3D11_INPUT_ELEMENT_DESC` for it **(option 2)**?

What I see:

**Option 1:**

* **No unused data will be transfered to shader** \- e.g. 60% of models will be rendered with simple shader that don't calculate normal maps and we will send to him just position/texture coordinate.

**Option 2:**

* **Only one input structure, no need to switch vertices types** \- simpler code, maybe faster (no switching)?, no need to bother if new shader needs 1st, second or third structure (we can just pass everything to it and it will decide which members to use).

# Answer
> 2 votes
I would say that you should try to keep the size of your data (vertex buffers, arrays) at the minimum, especially if you want to be updating the vertex buffers since that is a slow operation even if you created them with dynamic usage flag. More data will slow down that operation significantly. Also I don't know what big of a program you are developing but wasting space is usually a big luxury. :)
And since you already have different types of shaders for different layouts I see no need to keep empty data in several of your models. I would recommend however to avoid switching layouts and shaders when unnecessary. For this you could draw everything which uses the first layout first, then draw everything which uses the second layout and so on.

# Answer
> 2 votes
János Turánszki is correct. That's quite a luxury to waste memory in any serious game. The memory spaces occupied by the vertices is not the only / major problem. The GPU performance suffers from loading unnecessary data from vertex buffers. That trashes the vertex cache, and bring extra workload to the input assembler. It's always a good practice to keep the data size minimized.

Switching rendering contexts too many is a different problem. If you have many combination of shaders / input layouts / vertex buffers / etc., it would generate a lot of draw calls to waste the driver. However, since you just have around 10 shaders, that might not be an issue to your game. Even low-end PC could easily generates more than 1,000 draw calls per frame. If you combine your vertex buffers and sorting the shaders properly, you should be completely safe.

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


# Question
Title: How can I create a "cracked glass" material?
I'm trying to figure out how the cracked and chipped glass effect in a Bioshock Infinite Burial at Sea Episode 2 works.

My current guess is that it is essentially a transparent shader with gloss. It would have a map defining the direction of reflections from the environment, with the cracks being significantly different from the mesh's normals. It would also include some kind of model of the angular dependence of the amount of refraction/transmission to reflection so that it can roughly approximate Fesnel's equations.

It doesn't appear to be a full refractive model, so I'm wondering how exactly this is implemented? Am I right with what I have said above?

# Answer
> 1 votes
You could achieve a good approximation of this effect with regular environment mapping (to sample the reflective data) and a normal map (to simulate the surface discontinuities in the glass at the cracks), plus a simple decal-like texture modulated in (such as the one glampert linked in the comments:

If you have the artistic talent, you could probably hand-author this yourself. If not, you may be able to generate a reasonable facsimile using procedural generation techniques similar to those used to generate lighting bolts.

Note that the environment map likely need not be an accurate representation of the surrounding area, just enough to suggest similarity. This is basically how the windows in Assassin's Creed 4 were done (or at least, a part of how they were done).

---
Tags: rendering
---


# Question
Title: Creating unfilled circle shapes using Farseer
I have a project idea that I need to create a sphere and use it's interior for collision detection. I can only find information in Farseer that creates a filled circle. Is there a way to do it with CircleShape or do I need to create the sphere using vertices? Or if anyone knows of another physics engine that can do this. Thanks

# Answer
You could use an chain shape which allows for 2 sided collision for the circle, but as far I know there is not a hollowed circle object.

http://www.box2d.org/manual.html
> 1 votes

---
Tags: farseer-physics-engine
---


# Question
Title: How can I create a fade effect between scenes in Libgdx?
I have implemented a screen fade with Scene2D. It currently fades fades out of one screen to black, then then from that black into the next screen. It would be really awesome if I could fade straight from the first screen to the new screen, without the black state between. Is this possible?

I tried using the parallel method but it just did everything all at once. I want it to kind of morph through the screens.

# Answer
While rendering the two scenes, the first one over the target one, you can just make a fade effect on opacity on the first one.

Here is what i suggest :

1. Create a "TransitionScene" wrapper that take the two scene as parameters and have them rendered and updated (override act and render)
2. Apply a color action to have the first scene opacity move from 1 to 0
3. When this action is finished, set your current game scene to the second one.

I have some code here that might help you get the idea, though it's probably not the best example :
> 3 votes

---
Tags: libgdx, graphic-effects
---


# Question
Title: Throwing a ball and estimating its path using a Physics engine
**The problem**: A player entity wishes to throw a ball from a known position with a known initial velocity. The surrounding environment contains physical objects that can alter the trajectory of the ball. How can this trajectory be as accurately as possible be rendered?

**One solution**: perform small steps and simulate throwing the ball. During each small step, a **raycast** is performed against the world to find potential colliding bodies. In case a collision is reported, it must be handled accordingly. The intermediate positions of the ball will then be saved in an array and the trajectory should be described by the succession of these points.

While this solution works (it is tested and doesn't fail almost never :) ), are there any workarounds or possible optimizations that can be done to avoid performing the raycast queries too often? It would be nice if there were such a thing as a parabolic caster instead of a linear ray caster. Do you know of any existing solution that is better of the one I just described (that either avoids those many raycasts or performs a more clever kind of query to reduce the number of intermediate steps and replace the actual line segments with parabola segments)?

# Answer
Well I think it's possible to solve parabola/shape intersection equations. But first the problem is; I think it would be tricky to solve for more complicated shape and the intersection algorithm performance I suspect won't be that good. (Actually this is very obvious in the link @IcyDefiance provided in the comments).

Secondly and the far more important problem is that parabolic casters can't take advantage of spatial data structure, traversing a spatial data structure is far simpler when you assume the ray is going in a straight line, bend that path and most the traversal assumptions don't hold anymore. For example the faster ray octree intersection algorithm actually *does* exploit the ray and octree analytical properties, for example it assumes if a ray was in a certain cell it can only go through some other neighbor cell. Add a parabolic shape and those assumptions will vanish.

### My recommendation

Stick with the ray casting technique with a memory coherent spatial data structure.

It doesn't make sense to test for intersection for every object in the scene anyway, using a spatial data structure is a must. I also suspect that if the data structure was cache friendly then ray casting the scene will be far less demanding.

### Final Note

Something I just thought about but never tested, is to use asynchronous casting. Meaning; instead of doing one step at a time you can do each 4-16 steps together asynchronously, to be honest I never tried this and don't know if the performance will be better or worse. You just need to generate the samples first, and then do asynchronous test, similar to what people do in ray tracing, the difference is that samples will be for a parabola rather than an image.
> 2 votes

# Answer
Unless you are in a situation where you NEED to optimize, don't waste your time on it. Avoid unnecessary premature pessimism, and premature optimization.

For the sake of submitting some ideas I had though, here is what I have come up with.

Depending on how much control you have over your system, a more accurate version would be to simulate an object in a separate "compartment", and trace the path. This would require you to maintain a mirrored subset of objects that it could interact with, as well as simulate at a different time step.

PhysX has (last I knew) native support for compartment based simulation, though I am unaware of whether or not it allows separate timesteps for different compartments. This is definitely the most accurate way you could do this, but the overhead associated with it could be pretty unacceptable.

An alternative method would be to calculate the path that the projected object would take independent of the physics sim. This could get complex if you have forces other than gravity affecting the ball. After plotting this path, a minimal set of tangents could be pulled from the path to represent an efficient set of raycasts. This method would require iteration, and would likely incur a higher calculation penalty, while the previous method has a higher data penalty.
> 2 votes

# Answer
For a game, piecewise linear approximations of the parabolic path are fine, don't waste time going beyond that.

Also, use someone else's well-tested, well-optimized physics and collision engine.
> 1 votes

---
Tags: physics, geometry, simulations
---


# Question
Title: How to convert strict limit in position into gradual slow down?
The player moves a spell object, the spell must stay withing a certain range of the player. The spell is moved using a physics system and it has mass and velocity. Currently when the spell goes out of range of the player it's being moved back into range, this has the effect stopping the spell abruptly at the edge. I want to smooth out this abrupt stop so that it gradually slows down. I tried to apply an easing function but because the time and distance change every frame I couldn't figure out the formula.

Is there some sort of physics or easing formula I can use to gradually slow down the spell before it gets to the edge of its range, while at the same time guaranteeing that it never leaves the range?

Additional Info:

The spells range is a circle. I only care about the center of the spell object. Movement forces are continually being applied to the spell.

# Answer
I ended up doing the following and it works all right. First I use F = m(dv/dt) to calculate the force that would stop the spell moving completely. Then I take the time until the spell exits the range at it's current velocity, if it will exit in under 0.05 seconds then I apply the stopping force, but scale it depending on how soon it will exit (the minimum being 1 game tick worth of time). I.E. if the spell will leave the range in one game tick or less then we apply the full stopping force, if it will take more than 0.05 seconds to leave the range then we do nothing, in-between those two extremes we just scale the force from 100% down to 0%. This creates a nice deceleration effect, while guaranteeing that that spell will not leave the range.

Thanks everybody for your help with this!
> 0 votes

---
Tags: physics, collision-avoidance, easing
---


title: Are VBOs only for OpenGL 3.x?

text:
# Question
Title: Are VBOs only for OpenGL 3.x?
Are VBOs only for OpenGL 3.x?

I'm using immediate mode and I know it's bad, slow, and deprecated. But then I looked at display lists but they are deprecated too. I guess the VBO is the only one left so is it only for OpenGL 3.x?

# Answer
The vertex buffer object APIs were added to OpenGL's core API in version 1.5. At some point, they were available as extensions, such as `ARB_vertex_buffer_object`.

Wikipedia has a good overview of the version history of OpenGL.
> 4 votes

# Answer
*There is a lot of misinformation floating around here. Buffer Objects were introduced into **core** in OpenGL **1.5**. They existed in extension form as far back as OpenGL **1.4**.*

Vertex Buffer Objects are basically an evolution of ATi's original Vertex Array Object extension. That extension has the unfortunate honor of sharing its name with a completely different concept by the same name in modern OpenGL. In fact, Buffer Objects now describe a generic source of dedicated server (GPU) storage. You can use this memory for vertices, indices, textures, uniforms, transform feedback, pixel transfer, and so on in modern GL.

Prior to Vertex Buffer Objects, vertex memory was transferred from client (CPU)-\>server (GPU) everytime you called `glDrawArrays (...)`. That is because GL did not own the memory referenced by vertex array pointers, and the CPU and GPU generally operate asynchronously with potentially many frames queued up in advance. Since the CPU could modify vertex memory at any time without the GPU's knowledge, implementations either had to ***copy*** data *immediately* when `glDraw* (...)` was called or block the CPU until vertex processing finished. Many attempts were made to address this issue over the years, including things like NVIDIA's Vertex Array Range, which allocated special memory for DMA data transfer. However, ultimately VBOs were the only real way to solve it.

VBOs plug that hole by making the only way to access vertex memory by using GL commands. Now GL knows anytime memory is changed and does not have to waste time copying data for every draw command.
> 4 votes

# Answer
VBOs have been available since OpenGL 1.4 as an extension and were added to the core in OpenGL 1.5. You can use either version depending on your needs, if you strictly want to use OpenGL 3.1 with the core profile only, then VBOs are your only option.

If you want to use compatibility profile, you can always use the deprecated functions. Keep in mind that "deprecated" only means that it *might* be removed from the standard, but no major vendors have plans drop support for it.
> 3 votes

# Answer
No, VBOs are not only for `3.x`, they are 3.x+ (including 4.x) and even back to the 2.x specification at least, probably earlier. It's safe to assume that any platform supporting OpenGL will (likely) support at-least 2.1, so you'd be safe to use buffer objects if your worried about gpu support (and maintaining code.)

VAOs are a bit of a different story, they weren't around in 2.1, and are required with 3.x+ core profiles (though not necessarily with a compatibility profile.)

If you feel to bad about using Immediate-Mode, and don't want to switch, you could probably find/create an API that has the Immediate-Mode functions but renders the primitives using the newer API versions. That wouldn't be the suggested rout though.
> -2 votes

---
Tags: opengl, lwjgl, vbo
---


# Question
Title: How do you account for zoom in a top down viewport?
I've been stumped on this for days so please forgive me if this question is in bad-form. I have a generic top-down RPG structure, and I want to create a zoomable Canvas viewport for it. I've read several tutorials and I guess I keep messing it up somewhere.

Current Codepen project here.

Relevant code from the project:

---

Camera:

```
function Camera(PARENT, CANVAS, SUBJECT, ZOOM)
{
  this.draw = function()
  {
    var refs = [];

    Rect.call(this, SUBJECT.x, SUBJECT.y, CANVAS.width*ZOOM, CANVAS.height*ZOOM, "cen");

    for(o in PARENT.objects)
    {
      if(this.overlapping(PARENT.objects[o]))
        refs.push(o);
    }

    while(refs.length>=1)
    {
      var obj = PARENT.objects[refs.shift()];

      if(obj.draw)
        obj.draw(
          this.context, //Drawing ctx
          this.left, //Offset left
          this.top, //Offset top
          ZOOM //Scale factor
        );
    }
  };
}

```

Drawing function called by the Camera:

```
this.draw = function(context, offsetX, offsetY, scale)
{
  context.fillStyle = this.color;
  context.fillRect((this.left-offsetX)*scale, (this.top-offsetY)*scale, this.width*scale, this.height*scale);
};

```

---

How can I resolve the math here so that the zoom is correctly figured in to the drawing offsets?

# Answer
Generally speaking, you can use the `scale` function on the context to handle zoom.

```
function drawAll(context, cameraX, cameraY, scale) {
    context.save();
    context.translate(cameraX, cameraY);
    context.scale(scale, scale);
    // Draw everything else
    context.restore();
}

```

This means you can draw each of your rectangles like this:

```
this.draw = function(context) {
    context.fillStyle = this.color;
    context.fillRect(this.left, this.top, this.width, this.height);
};

```

Taking this approach means far less computations and a much easier way of manipulating the camera.
> 1 votes

# Answer
Well I've fixed my problem. I was not accounting for the difference between the `CANVAS` size and the `ZOOM`'d canvas size. *I haven't yet fully optimized this,* but I'm posting it as-is, because I think it makes a good example for anyone having similar issues.

Fixed Codepen fork.

Relevant changes to the code:

---

Camera:

```
function Camera(PARENT, CANVAS, SUBJECT, ZOOM)
{

  //...

  this.getRefs = function()
  {
    this.refs = [];

    for(num in PARENT.objects)
    {
      var obj = PARENT.objects[num];

      if(this.projectedRect.overlapping(obj))
        this.refs.push(num);
    }

    return this.refs;
  };

  this.worldToScreen = function(x, y)
  {
    if(!y&&typeof x == "object")
    {
      if(x.x!==undefined&&x.y!==undefined)
        y = x.y,
        x = x.x;

      else if(x.left!==undefined&&x.top!==undefined)
        y = x.top,
        x = x.left;

      else throw "worldToScreen Error";
    }

    return {
      x: (x-this.projectedRect.left)*(CANVAS.width/this.projectedRect.width),
      y: (y-this.projectedRect.top)*(CANVAS.height/this.projectedRect.height)
    }
  }

  this.screenToWorld = function(x, y)
  {
    if(!y&&typeof x == "object")
    {
      if(x.x!==undefined&&x.y!==undefined)
        y = x.y,
        x = x.x;

      else if(x.left!==undefined&&x.top!==undefined)
        y = x.top,
        x = x.left;

      else throw "screenToWorld Error";
    }

    return {
      x: (x*(this.projectedRect.width/CANVAS.width))+this.projectedRect.left,
      y: (y*(this.projectedRect.height/CANVAS.height))+this.projectedRect.top
    }
  }

  this.update = function()
  {
    var testRect = new Rect(SUBJECT.x, SUBJECT.y, CANVAS.width*ZOOM, CANVAS.height*ZOOM, "cen");
    if(!this.projectedRect||
       this.projectedRect.left != testRect.left ||
       this.projectedRect.right != testRect.right ||
       this.projectedRect.top != testRect.top ||
       this.projectedRect.bottom != testRect.bottom)
      {
        this.projectedRect = testRect;
        this.getRefs();
      }
  };

  this.update();

  this.clear = function()
  {
    this.context.clearRect(0,0,CANVAS.width,CANVAS.height);
  };

  this.draw = function()
  {
    this.clear();

    this.update();

    for(num in this.refs)
      PARENT.objects[this.refs[num]].draw(this);

    PARENT.mouseLoc.draw(this);
  };
}

```

Drawing function called on the objects:

```
this.draw = function(CAM)
{
  var screenPos = CAM.worldToScreen(this);

  CAM.context.fillStyle = this.color;

  CAM.context.fillRect(screenPos.x, screenPos.y, 10, 10);
};

```
> 0 votes

---
Tags: mathematics, javascript, html-canvas, rpg, viewport
---


# Question
Title: Properly rendering transparent areas of textures
I'm rendering a tree that contains branch meshes with partially transparent textures.

If I render it with AlphaTestEffect and set the ReferenceAlpha to something low, I'll get this.

I want to render the tree with BasicEffect, however, this is the result I get. BlendState is set to NonPremultiplied.

I am not even sure what I am looking at. It looks like the transparent area of the closest branch is covering up the one behind it (but not the trunk of the tree). If I set the DepthState to DepthRead, then all the branches are drawn out of order.

What exactly is the problem here?

# Answer
> 2 votes
The problem is that you don't sort your polygons here thus can not use alpha blending properly. The common ways to resolve this are:

* Alpha testing: discard the pixels which are below a certain alpha threshold so that you gain proper Z buffering, Z discard. This results is hard edges when looked from up close.
* Alpha to coverage: you have to set up a blend state which supports this technique. It is based on multisampling anti aliasing so you get better results when you turn it on to higher levels.
* Two pass rendering: first you render everything alpha tested to get correct sorting, then in a second pass you render everything with alpha blending and Z buffer writes turned off, but discarding pixels which are **above** a certain alpha level. This way you render only the smooth outlines of the transparent geometry, which gets you incorrect sorting, but the user won't recognize it (probably).

There are also some advanced techniques (order independent transparency) which are not really used in real time apps because of their performace hungry nature.

# Answer
> 0 votes
If you're using a render target instead of rendering directly to screen then make sure you use the most complete constructor overload of the render target to construct it so you can instruct it to create a depth buffer.

Other than that you should set your DepthStencilState to Default not Read as this means your branches are only depth tested versus what was already in the depth buffer and not against themselves.

The BlendState should be set to AlphaBlend. This is I think the only option that supports semi-transparent textures. NonPreMultiplied should only be used for content that was not imported using XNA's content pipeline.

Just a note, János Turánszki is correct, I'm just listing here how to get in done in XNA.

---
Tags: xna, directx, monogame, sharpdx
---


# Question
Title: How many active shaders at one frame in the game should I typically use? 5 or more like 100?
How many shaders are usually active, at the same time in one scene, in modern games? I know that multiple shaders are being used, with the games switching between them in each frame, and it's common to draw objects via the shader:

1. Draw all objects with shader one
2. Change from shader one to shader two
3. Draw all objects with shader two

Still, I know it's not as simple, especially with effects like a glow effect for whole scene, render to texture, etc., but I guess we can assume it works that way most of the time, right? The "group by shader" approach is good, because switching shaders is an expensive operation.

From one side, you cannot have too many shaders, because you want to render the scene fast. On the other hand, you need many different shaders (or uber-shader with branches - quite similar) for skin, metal, water etc.

How many (and which) different shaders would the theoretical, modern, third person, 3D detective game for PC (DirectX 11, if it matters) use? It would be 5, 20 or more like 100 active shaders, counting only active, at some "frame X"? I know it's not one number, but I wonder what scale and factors are important, in consideration for a PC game.

---

In my sample game, I would use about 9-11 per frame (count it as different, small shaders or one uber-shader - doesn't matter now):

1. Skin shader
2. Eye shader (not too much? but they are different)
3. Metal shader
4. Ground shader
5. Snow/rain shader (if required)
6. Water shader (if the water exists in scene)
7. Glow shader (only when some special effects are involved)
8. Light emiter shader (street lamps etc.)
9. Standard shader (for all other, just standard shading)
10. Standard shader with normal maps
11. 2D shader (for GUI etc.)

Is it "much" or "not many"? Did I forget about some important shaders that I would need?

# Answer
> 36 votes
It really depends on the technique. In a forward render you often have one shader for every different material type. In AAA games that use this technique shaders are often generated from a set of options on the material which an artist can set. This can lead to hundreds of shaders(1). But lets say generally the number of shaders is in the order of 40

In a deferred shading/rendering you often encode the material type in the G-buffer and later use one big shader to correctly render different material types differently. This leads to a lot less, but more complicated, shaders. Lets say the number of shaders here is in the order of 5.

*(1) Source: I worked for a contractor of Crystal Dynamics where I built a tool to reduce the number of generated shaders for Tomb Raider since automatic generation was getting out of hand ;). The goal was to reduce the number of shaders to the order of 40 or something like that.*

# Answer
> 5 votes
I know you wanted an answer for PC. But I'll answer for what I do in iOS and I don't expect to get your checkmark.

It looks like you have the right idea. It's going to be different for each app though. In the end it's all about doing what it takes to get your desired frame rate. On the iPhone my goal rate is 60. I don't like for it to get below 30. When I have an explosion with several hundred animating sprite based particles, it gets down to 30 on the iphone5 and much lower on the 4. So I have to make decisions about reducing complexity on certain devices. And sometimes that decision effects shaders.

But it doesn't generally effect how many shaders but rather which shaders I use for a task based on my frame rate goal.

In my opinion shaders when used correctly raises the frame rate. I have an app that has 80 shaders, but it doesn't use all of them on a single frame - probably around 10. And it compiles them as needed and discards them all between scenes. And on my hardware I haven't seen the shader count effect frame rate. Only the techniques used in the shader. But for sure I think that using 2 similar shaders is better for frame rate than having a more complex one that branches.

I also have shaders that reduce quality if the rendering is slow or on a slower device. I use normal mapping on the iPhone 5 but swap out the shader to one that doesn't do normal mapping on the iPhone 4.

I like Roy's answer and I'm always trying to get insight into how "real" games are made. Since I'm self taught I never know if my great discovery of the day is just how it's generally done or still a few steps behind the real professionals.

# Answer
> 1 votes
You can't really put a number on how many shaders you should or should not have, as it is dependent on the limiting factors of your game, as well as the target platform. In practice, reducing the number of active shaders to be "only as many as you actually need" should be followed. Sometimes this means you have only a handful of shaders (10 or so) at once, and sometimes it means you have a few dozen.

One way to help limit the amount of permutations that pop up in your game is to implement the "ubershader" technique, by which almost every shader is derived from a singular shader, and the differences and special behaviors are swapped out via a preprocessor. There are exceptions of course for special effects such as depth of field, ambient occlusion, and so forth.

My experience with AAA games up to this point has shown that a couple dozen shaders active is not unreasonable.

---
Tags: shaders, directx, rendering, directx11
---


# Question
Title: Why is my Slick2D spritesheet animation cut off when it loops?
I am loading a SpriteSheet with Slick2D and using the Animation function in the render method to display it. The spritesheet loads perfectly, but when the animation loops, it does so moved down a few pixels and cut in half.

It should always look like this:

But instead does this:

Here's my code. It's smalle because it's only a test.

```
package finalProject;

import org.newdawn.slick.*;
import org.newdawn.slick.state.*;

public class Dialogue extends BasicGameState {

    private SpriteSheet SSTommy;
    private Animation ATommy;
    Music playMusic;

    public void enter(GameContainer gc, StateBasedGame sbg) throws SlickException {
        playMusic = new Music("C:/OOP Resources/Bill Blaster.ogg");
        playMusic.play();
        playMusic.loop();
    }

    public Dialogue(int state) {
    }

    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
        SSTommy = new SpriteSheet("C:/Users/Usuario/Documents/Etc/Tommy_SS.png", 41, 87);
        ATommy = new Animation(SSTommy, 150);
        ATommy.setPingPong(true);
    }

    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
        g.drawString("This is the Play State", 100, 100);
        ATommy.draw(200, 200);
    }

    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
        ATommy.update(delta);
    }

    public void leave(GameContainer gc, StateBasedGame sbg) {
        playMusic.stop();
    }

    public int getID() {
        return 1;
    }
}

```

I tried other SpriteSheets but it keeps doing the same. I think this is releated to the render method, but I don't know what's doing it.

# Answer
> 1 votes
Why are you passing a sprite-sheet object to the animation, That would seem like your problem

try:

```
SpriteSheet spriteSheet;
Image player;
Animation aTommy;

public void init(){
    spriteSheet = new SpriteSheet("imgs/spriteSheet.png", sheetWidth, sheetHeight);

    player = spriteSheet.getSprite(_x, _y);
    aTommy = new Animation(player, 150);
}

```

Now if you want to actually create an animation:

```
SpriteSheet spriteSheet;
Image[4] player;
int[4] times = {150, 150, 150, 150};
Animation aTommy;

public void init(){
    spriteSheet = new SpriteSheet("imgs/spriteSheet.png", sheetWidth, sheetHeight);
    for(int i = 0; i < player.length; i++){
         player[i] = spriteSheet.getSprite(_x+i /*This is only possible if the animation frames in the spritesheet are beside eachother*/, _y);
    }
    aTommy = new Animation(player, times);
}

```

---
Tags: java, animation, slick
---


# Question
Title: How to display a hierarchical skill tree in php
If I have skill data set up in a tree format (where earlier skills are prerequisites for later ones), how would I display it as a tree, using php? The parent would be on top and have 3 children. Each of these children can then have one more child so its parent would be directly above it.

I'm having trouble figuring out how to add the root element in the middle of the top div, and the child of the children below each child of the root. I'm not looking for code, but an explanation of how to do it. My data in array form is this:

Data:

```
Array
(
    [1] => Array
        (
            [id] => 1
            [title] => Jutsu
            [description] => Skill that makes you awesomer at using ninjutsu
            [tiers] => 1
            [prereq] =>
            [image] => images/skills/jutsu.png
            [children] => Array
                (
                    [2] => Array
                        (
                            [id] => 2
                            [title] => fireball
                            [description] => Increase your damage with fire jutsu and weapons
                            [tiers] => 5
                            [prereq] => 1
                            [image] => images/skills/fireball.png
                            [children] => Array
                                (
                                    [5] => Array
                                        (
                                            [id] => 5
                                            [title] => pin point
                                            [description] => Increases jutsu accuracy
                                            [tiers] => 5
                                            [prereq] => 2
                                            [image] => images/skills/pinpoint.png
                                        )

                                )

                        )

                    [3] => Array
                        (
                            [id] => 3
                            [title] => synergy
                            [description] => Reduce the amount of chakra needed to use ninjutsu
                            [tiers] => 1
                            [prereq] => 1
                            [image] => images/skills/synergy.png
                        )

                    [4] => Array
                        (
                            [id] => 4
                            [title] => ebb & flow
                            [description] => Increase the damage of water jutsu, water weapons, and reduce the damage of jutsu and weapons that use water element
                            [tiers] => 5
                            [prereq] => 1
                            [image] => images/skills/ebbandflow.png
                            [children] => Array
                                (
                                    [6] => Array
                                        (
                                            [id] => 6
                                            [title] => IQ
                                            [description] => Decrease the time it takes to learn a jutsu
                                            [tiers] => 5
                                            [prereq] => 4
                                            [image] => images/skills/iq.png
                                        )

                                )

                        )

                )

        )

)

```

An example would be this demo image minus the hover stuff.

# Answer
I think your trouble mostly stem from trying to do this in a more automatic fashion than what is feasible.

I assume you want to end up with a skill tree where the skills have static positions, by far the easiest way to achieve that is to set those positions manually. Once you have decided what skills you want to have and what their dependencies should be, take a piece of paper and try drawing the skill tree until you have a visually pleasing and functional graph. Now you can simply give every skill a coordinate set according to its position on the graph.

I don't see any reason for arranging your data structure as a tree, put the skill objects on a flat list and make a field on each object detailing its dependency, or dependencies (You already made that field for some reason, despite being redundant in your current data structure).
> 0 votes

---
Tags: php
---


title: Rendering models in isometric view

text:
# Question
Title: Rendering models in isometric view
How to setup the rendering and camera for isometric gameworld projection? And specifically how do i get the images exactly the right size?

What angles to use to get the exact 2/1 isomtric view? Methods to set the camera on the right position? Options to set like anti alias off.

I have tried many things, 45, 30, 35.264 degree angles. What i do is set the angle of the camera, then place the camera in front of the model then use dolly/fov/lens settings to get the left and right edge of the model lined up with the save frame. Then adjust camera height so the bottom lines up with the bottom of the save frame. But i keep getting jagged edges and not the isometric style 2 width one height.

# Answer
Firstly, a 2:1 ratio is **not isometric**. It is a similar-looking dimetric projection (where two of the three axes are equally foreshortened, and the vertical axis is slightly less so)

Isometric projection is when all three axes are equally foreshortened. An axis-aligned square tile lying in the horizontal plane has an isometric projected width:height ratio of sqrt(3):1 (like two equilateral triangles stuck together)

For both projections, you want your camera to make an angle of 45° with each axis in the horizontal plane (yaw of 45).

For a 2:1 dimetric projection, the camera should be angled (pitched) down 30° from the horizontal. For true isometric, the angle is atan(1/sqrt(2)) which is about 35.264° (this aligns it with an axis drawn through two opposite corners of an axis-aligned cube).

Secondly, ensure you've configured your camera to use orthographic projection (as opposed to perspective projection - you don't want lines to converge & objects to shrink into the distance).

You can find additional information about isometric vs 2:1 dimetric projection here.
> 6 votes

---
Tags: rendering, isometric, 3dsmax, art
---


# Question
Title: How to make a bitmap font having only a PNG file?
Is there a way to "convert" an existing PNG file with the characters' images into a bitmap font? Basically, I want to create a FNT file using an image like this...
<sub>(source: opengameart.org)</sub>
...without the access to a TTF file of the image's characters or any other typical font formats.

# Answer
The characters in such a monospace font are ordered in increasing ASCII codepoint row-major order.

This means that you can derive the cell offset by simple arithmetic. Given the codepoint `base` of the top left character, the cell index `col,row` of a codepoint `ch` is:

```
col= (ch-base) % columns
row= (ch-base) / columns

```

You can then compute X and Y of the rectangle by multiplying the cell index by the width/height of a cell.

Given the computed extents of each character, you can then emit a FNT file based on the FNT specification, or try to find a FNT generator that you can provide with input regions and a bitmap.
> 3 votes

---
Tags: fonts
---


title: Change the shape of body dynamically

text:
# Question
Title: Change the shape of body dynamically
I have a problem where i have a ballon which i need to continuously inflate and defalte in update method, I have tried to used setScaleCenter but it is not giving desired result. Below is a code i am trying to make work

```
    scale += (float) ((dist-lastDist)/lastDist);
    Log.d("pinch","scale is "+scale);
    Log.d("pinch","change in scale is "+(float) ((lastDist-dist)/lastDist));
    player.setScaleCenter(scale, scale);
    player.setScale(scale);

```

# Answer
> 1 votes
I'll assume that `player` is of type `Sprite`. You are changing the sprite size and center of the scaling. That has no effect on the physics body.

You can try using the `setRadius()` method from the `Shape` class. Not sure if that works for every `Shape`, but it does work for circle shapes. If you are creating circle bodies like this:

```
Body b = PhysicsFactory(physicsWorld, player, bodyType, fixture);

```

Try:

```
b.getFixtureList().get(0).getShape().setRadius(newRadius);

```

---
Tags: box2d, andengine
---


# Question
Title: How can I avoid updating my Unity projects when I have two versions installed?
I currently have two versions of Unity on my Windows computer. I would like to not update my projects to avoid compatibility issues like I had in the past.

Installation in another folder goes just fine, but when I try to open Unity, it says that another Project is already opened and that if I want to continue I must update it. If I close this window, Unity aborts as well.

Is there a way to avoid this behaviour?

# Answer
Hold down the `Alt` key when starting Unity. It will bring up the list with your available projects and will let you open a new one.
> 4 votes

# Answer
**OP's Answer** (If you know an easier way to do so, please post it! :D )

The last opened project path is saved on a Registry Key in *HKEY\_CURRENT\_USER\Software\Unity Technologies\Unity Editor 4.x*

In my computer, `kProjectBasePath_h4113231939` is the key I'm talking about. You just need to delete its value to achieve the result. To do so, execute **regedit**, navigate to the path above, locate the key, right-click it, select *Edit* and delete the value.

If you frequently need to switch between Unity versions, you may want to create a file that does these operations for you, so that you won't need to do that over and over again.

Create a txt file and paste this:

```
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Unity Technologies\Unity Editor 4.x]
"kProjectBasePath_h4113231939"=""

```

Then change the extension to **.reg**. Opening this file will automatically delete your registry key value.
> 1 votes

# Answer
You can set Unity to always ask you which project it should open on startup. That way you can easily choose the compatible projects for your Unity version.

Just go to **Edit \> Preferences... \> General**

Then make sure the checkbox for **"Always show Project Wizard"** ist activated.

And you can press the "Alt" Key while you are starting Unity to force it to show you the Project Wizard. For me this isn't working when I use a Desktop Shortcut to open Unity on Windows 7. When I open it with the Startmenu, it does.
> 1 votes

# Answer
You can start another instance of Unity from the `CommandLine`/`Terminal`, and then specify the project path you would like to open with that instance. If you specify wrong path to project, Unity will show you project selection screen.

Under MacOS, you can launch Unity from the `Terminal` by typing:

```
/Applications/Unity/Unity.app/Contents/MacOS/Unity -projectPath pathToProjectOrAnyString

```

while under Windows, you should type to the `CommandPrompt`:

```
"C:\Program Files (x86)\Unity\Editor\Unity.exe  -projectPath pathToProjectOrAnyString"

```

As I mentioned, if you specify wrong project path you can then choose any project you like. That should avoid the Upgrade project question. Using CommandLine gives you better control on what project you open with which instance.
> 0 votes

---
Tags: unity
---


# Question
Title: How can I center an arbitrary string over a sprite?
Eyesore:

The problem is, the text should be exactly centered over the player, I want something like this:

My code to draw username above the player is:

```
g.drawString(username,(int) playerX,(int) playerY);

```

I can just do `playerX-(some number of pixels)`, but this won't work all the time, because if the player makes his name something that has fewer characters, it will not be centered any more.

How can I make the user-provided String 'username' always be centered above the player sprite?

# Answer
Check out this page : http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html

You must measure the string width in pixels, so that you will be able to offset the position to a suitable value. With Java 2D, that i assume you are using, considering the code sample you gave, that can be done like that for instance :

```
FontMetrics metrics = g.getFontMetrics(font);
int width = metrics.stringWidth(username)
g.drawString(username,(int) playerX - width/2,(int) playerY);

```

Where font is your Font object

Considering that you use your sprite x left coordinate, you may also have to use it's width to center perfectly the string (or it will be centered over the left side of the sprite)

```
g.drawString(username,(int) playerX - width/2 + SPRITE_WIDTH/2,(int) playerY);

```
> 3 votes

---
Tags: java, graphics
---


title: Optimizations using GLSL shaders

text:
# Question
Title: Optimizations using GLSL shaders
I have written a simple OpenGL application using GLSL shaders. Actually, my program just displays a simple cube with a phong lighting effect like below :

Here's a peace of the client code :

```
pShaderProgram->BindAttribLocation(scene::VERTEX_POSITION, "VertexPosition");
pShaderProgram->BindAttribLocation(scene::VERTEX_TEXTURE, "VertexTexture");
pShaderProgram->BindAttribLocation(scene::VERTEX_NORMAL, "VertexNormal");

glm::mat3 normalMatrix = glm::mat3(glm::vec3(pMeshSceneNode->GetModelViewMatrix()[0]),
glm::vec3(pMeshSceneNode->GetModelViewMatrix()[1]), glm::vec3(pMeshSceneNode->GetModelViewMatrix()[2]));

pShaderProgram->SetUniform("ModelViewProjMatrix", pMeshSceneNode->GetModelViewProjectionMatrix());
pShaderProgram->SetUniform("ModelViewMatrix", pMeshSceneNode->GetModelViewMatrix());
pShaderProgram->SetUniform("NormalMatrix", normalMatrix);

pShaderProgram->SetUniform("LightCount", (int)this->m_LightSceneNodeList.size());
pShaderProgram->SetUniform("colorMapSampler", 0);

glm::mat4 viewMatrix = this->m_pCameraSceneNode->GetViewMatrix();

glm::vec4 lightPosition = viewMatrix * glm::vec4(this->m_LightSceneNodeList[0]->GetPosition(), 1.0f);
glm::vec3 lightAmbient = this->m_LightSceneNodeList[0]->GetLightMaterial(scene::AMBIENT);
glm::vec3 lightDiffuse = this->m_LightSceneNodeList[0]->GetLightMaterial(scene::DIFFUSE);
glm::vec3 lightSpecular = this->m_LightSceneNodeList[0]->GetLightMaterial(scene::SPECULAR);

pShaderProgram->SetUniform("LightInfos[0].Position", lightPosition);
pShaderProgram->SetUniform("LightInfos[0].La", lightAmbient);
pShaderProgram->SetUniform("LightInfos[0].Ld", lightDiffuse);
pShaderProgram->SetUniform("LightInfos[0].Ls", lightSpecular);

glm::vec3 materialAmbient = pMeshGeometry->GetMaterial()->GetAmbient();
glm::vec3 materialDiffuse = pMeshGeometry->GetMaterial()->GetDiffuse();
glm::vec3 materialSpecular = pMeshGeometry->GetMaterial()->GetSpecular();
float shininess = pMeshGeometry->GetMaterial()->GetShininess();

pShaderProgram->SetUniform("MaterialInfos.Ka", materialAmbient);
pShaderProgram->SetUniform("MaterialInfos.Kd", materialDiffuse);
pShaderProgram->SetUniform("MaterialInfos.Ks", materialSpecular);
pShaderProgram->SetUniform("MaterialInfos.Shininess", shininess);

pMeshGeometry->GetVertexArray().Lock();
{
    if (pMeshGeometry->GetMaterial()->HasTexture())
    {
        glActiveTexture(GL_TEXTURE0);
        pMeshGeometry->GetMaterial()->GetTexture()->Lock();
    }
    pMeshGeometry->GetIndexBuffer().Lock();
    {
        glDrawElements(pMeshGeometry->GetPrimitiveType(),
            pMeshGeometry->GetIndexBufferSize(), GL_UNSIGNED_INT, OFFSET_BUFFER(0));
    }
    pMeshGeometry->GetIndexBuffer().Unlock();

    if (pMeshGeometry->GetMaterial()->HasTexture())
        pMeshGeometry->GetMaterial()->GetTexture()->Unlock();
}
pMeshGeometry->GetVertexArray().Unlock();

```

Here's my vertex shader :

```
#version 440

/*
** Vertex attributes.
*/
layout (location = 0) in vec4 VertexPosition;
layout (location = 1) in vec2 VertexTexture;
layout (location = 2) in vec3 VertexNormal;

/*
** Uniforms.
*/
uniform mat3 NormalMatrix;
uniform mat4 ModelViewMatrix;
uniform mat4 ModelViewProjMatrix;

/*
** Outputs.
*/
out vec3 Position;
out vec2 TexCoords;
out vec3 Normal;

/*
** Vertex shader entry point.
*/
void main(void)
{
    Position = vec3(ModelViewMatrix * VertexPosition);
    Normal = NormalMatrix * VertexNormal;
    TexCoords = VertexTexture;

    gl_Position = ModelViewProjMatrix * VertexPosition;
}

```

And my fragment shader :

```
#version 440

#define MAX_LIGHT_COUNT 10

/*
** Output color value.
*/
layout (location = 0) out vec4 FragColor;

/*
** Inputs.
*/
in vec3 Position;
in vec2 TexCoords;
in vec3 Normal;

/*
** Uniforms.
*/
uniform sampler2D ColorMapSampler;

struct Light
{
    vec4 Position;
    vec3 La, Ld, Ls;
};

struct Material
{
    vec3 Ka, Kd, Ks;
    float Shininess;
};

uniform struct Light LightInfos[MAX_LIGHT_COUNT];
uniform struct Material MaterialInfos;

uniform int LightCount;

/*
** Basic phong shading.
*/
vec3 Basic_Phong_Shading(vec3 normalDir, vec3 lightDir, vec3 viewDir, int idx)
{
    vec3 Specular = vec3(0.0f);
    float lambertTerm = max(dot(lightDir, normalDir), 0.0f);

    vec3 Ambient = LightInfos[idx].La * MaterialInfos.Ka;
    vec3 Diffuse = LightInfos[idx].Ld * MaterialInfos.Kd * lambertTerm;

    if (lambertTerm > 0.0f)
    {
        vec3 reflectDir = reflect(-lightDir, normalDir);
        Specular = LightInfos[idx].Ls * MaterialInfos.Ks * pow(max(dot(reflectDir, viewDir), 0.0f), MaterialInfos.Shininess);
    }
    return (Ambient + Diffuse + Specular);
}

/*
** Fragment shader entry point.
*/
void main(void)
{
    vec3 LightIntensity = vec3(0.0f);

    vec4 texDiffuseColor = texture2D(ColorMapSampler, TexCoords);
    vec3 normalDir = (gl_FrontFacing ? -Normal : Normal);

    for (int idx = 0; idx < LightCount; idx++)
    {
        vec3 lightDir = vec3(LightInfos[idx].Position) - Position.xyz;
        vec3 viewDir = -Position.xyz;

        LightIntensity += Basic_Phong_Shading(
            -normalize(normalDir), normalize(lightDir), normalize(viewDir), idx
        );
    }
    FragColor = vec4(LightIntensity, 1.0f) * texDiffuseColor;
}

```

All works perfectly. But as you can see in the client code there is a lot of 'SetUniform' calls. I think it could be judicious to gather some variables like materials in a simple float array and send this unique variable with a single call of 'SetUniform' instead one for each material component.

Until here the idea was to declare in the fragment shader a structure like below (this is the same way for lights materials):

```
struct Material
{
    vec3 Ka, Kd, Ks;
    float Shininess;
};

uniform struct Material MaterialInfos;

```

And the corresponding client code :

```
glm::vec3 materialAmbient = pMeshGeometry->GetMaterial()->GetAmbient();
glm::vec3 materialDiffuse = pMeshGeometry->GetMaterial()->GetDiffuse();
glm::vec3 materialSpecular = pMeshGeometry->GetMaterial()->GetSpecular();
float shininess = pMeshGeometry->GetMaterial()->GetShininess();

pShaderProgram->SetUniform("MaterialInfos.Ka", materialAmbient);
pShaderProgram->SetUniform("MaterialInfos.Kd", materialDiffuse);
pShaderProgram->SetUniform("MaterialInfos.Ks", materialSpecular);
pShaderProgram->SetUniform("MaterialInfos.Shininess", shininess);

```

Do you think it's possible to avoid a data struture like this and use a uniform variable like the following one:

```
uniform float MaterialBuffer[9];

```

The 3 first indices should be allocated for the ambient light components, the 3 following one for the diffuse light components and finally the 3 lasts for the specular light components.

I tried to use the opengl function 'glUniform3fv' which takes in parameter a float * but without success. So, do you think it's possible to not use the structure in the shader and use a simple array of floats or not? (I know that matrices can be stored into a Texture Buffer Object (TBO) and can be used as an array of samplerBuffer in the fragment shader but for the materials I don't know if my proposition could be possible...).

What are your opinions ?

Thanks a lot in advance for your help !

# Answer
> 2 votes
You absolutely do not want to create an array of floating-point uniforms. Some GPUs are not capable of storing uniforms as scalars, so each one of those may potentially take up the same storage as a `vec4`. There is a limit to the number of uniform components GLSL programs have for any given stage, and you may be approaching it 4x quicker than you ought to be. You should really pack that into something like 3 `vec4`.

However, the real issue at hand is that what you ***actually*** want is either a Shader Storage Buffer Object or Uniform Buffer Object. You can use either in GLSL 4.40, earlier versions of GL only supported UBOs. I would honestly suggest using a simple UBO for this, you would not benefit terribly from an SSBO, but it is an option.

---
Tags: opengl, shaders, glsl, fragment-shader
---


# Question
Title: Player's camera, how to obtain smooth movement
In a 2D platformer, I have a player that can move both horizontally and vertically. I also have a camera that moves in relation to player. In every update I do this:

```
public void RepositionCamera()
{
   // For the example I don't consider world rectangle bounds
   current_camera.Position =
      new Vector2(
         player_.Position.X - 250,
         player_.Position.Y - 100));
}

```

The problem here is that when I press very rapidly "left-right-left-rigth..." the camera does a very annoying effect, it seems an eartquake.

I think this is due to the strict relation to player's position and camera's position. This is just an example, it is annoying also when climbing onto stairs because every step I force the player's Y up to the step height, so the camera does the same thing!

How can I solve this? How can I edit my `RepositionCamera()` to be less strict about moving itself?

# Answer
> 1 votes
I solved by doing this:

```
   player_camera_.Position = new Vector2(
            MathHelper.Lerp(player_camera_.Position.X, player_.Position.X - 250, 0.08f),
            MathHelper.Lerp(player_camera_.Position.Y, player_.Position.Y - 100y, 0.08f));

```

# Answer
> 0 votes
The reason the camera shakes is most likely because of it is not being repositioned at the right time, so it lags behind one frame.

Example:

```
HandleInput() - right
UpdatePlayer() - move to right
Draw() - player after moving to right
RepositionCamera() - set camera to player position.

```

The world had already been rendered when RepositionCamera is called, and the player is always ahead of the camera. It could be the way around also.

I'd suggest you fix that first, but here's an example of moving the camera smoothly:

```
Vector2 delta = player_.Position - current_camera.Position; //Distance from player to cam
current_camera.Position += delta * 0.1 //Move the camera by 10%

```

---
Tags: xna, xna-4.0, camera
---


# Question
Title: How do I make other players see one player's die rolls?
I'm new to PHP and making a simple dice game. It works well in single-player, but in multi-player, I don't know how to show the results of one player's `rand(1,6)` dice roll to the others using a web page.

How can I do this?

# Answer
> 2 votes
You can use websockets to resolve this problem. To be short, a websocket provides a way to exchange messages between several clients and your server.

**Principles**

Your websocket application could behave like this :

1. Whenever someone opens your game web page, javascript will open a websocket connection with the server (You don't need any library on the client side, only a recent web-browser)
2. A client rolls the dice by clicking on a button
3. Some javascript sends the value on the websocket
4. The server receives the value and broadcasts it to all clients
5. Some javascript handles the value received on clients page and displays it.

**How to do that ?**

Node.js is particularly convenient to handle websocket-based applications on the server side, and that's why so many people would recommend it. However, it is also possible to handle websocket in PHP.

I'm not goind to write a full tutorial, so the best advice i can give you is to find one on how to implement a chat application with websocket in PHP. Then if you are able to develop a chat, you should be able to develop almost any real-time multiplayer web game.

I have found this tutorial for PHP : http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket

Have a look here too : Javascript and PHP for real-time multiplayer?

---
Tags: javascript, html5, php
---


title: Game slow with older phone

text:
# Question
Title: Game slow with older phone
I've made a game using libgdx. On m'y HTC One X, the game works good, even if there are some lags but only at the beginning. I wanted to try it on an older phone (well a less powerfull phone), a Samsung Galaxy Y, and on it my game is always very slow. How could I know how to fix it?

# Answer
> How could I fix it?

Well, first off, I would look "what" is actually making the game lag. For example, are you using sprites that are like 2048 pixels in y and x pixel then you should look forward to break it down.

Also, maybe it's an certain miss conception of code. Maybe there are some unnecessary function calls in your game loop?

You'd be better with using an profiler, in order to see where your programm starts to fall off in FPS.

I don't know the Samsung Galaxy Y, it's possible that it has not enough power to run a game.
> 2 votes

---
Tags: android, libgdx
---