# Question
Title: Is it possible to use 3G internet for a TCP/IP game server?
I'm working on a turned based multiplayer android game with a friend. I started working on the game server and client using socket programming. I found a few tutorials on how to implement a basic chat on android and I started extending that example to suit my needs. Basically the game is really simple and the communication only include sending a few string from the client to the server every turn and sending the calculated scores back to all the clients after each turn. the idea is that one of the players creates the game and thus initialize the server, and each player connects to this client using ip. I tried this solution and it seems to work great when all the players are using the same wifi connection or by using router port forwarding. The problem is when trying to use 3G internet for the server, I guess the problem is that 3G ip address isn't global and you can't use port forwarding there, correct me if I'm wrong here.

Is there a way to overcome this issue? or the only solution is to limit my game to wifi only or think of a different solution than the standard socket programming solution? I.E web server etc.

what do you think would be the best approach here?

Thanks.

# Answer
> 3 votes
Due to the fact that your game is turn-based you can get quite creative with your solution - you can still run the server on one of the phones but you don't need to rely (directly) on a direct IP connection.

In your situation what I would do is implement the XMPP protocol and send game state via that protocol - XMPP is particularly well suited to this because it is not only restricted to human-to-human messages (you would use IQ stanzas to transfer the commands) - and servers should blindly transmit IQ stanzas that they don't understand. The advantage here is that GTalk uses XMPP so you can obviously take advantage of Google's infrastructure (or indeed any public XMPP server like Jabber.org).

Finally you could also try and initially negotiate a Jingle session. If your NAT is traversable you would thus get a P2P connection, and if it is not you could simply use the XMPP connection that you have open. I doubt you would actually need to do this though, because of the fact that your game is turn-based.

# Answer
> 0 votes
As far as I know, usually 3G connections are NATted, so they can't be used as a server.

Why you would want to do it in the first place is beyond me. Get a real server. You can rent a VPS for like 5$/month or even less...

# Answer
> 0 votes
Aside from technical issues, the latency is going to be terrible. If you Google the major carriers you'll see reports of 200ms to 900ms latency - most definitely not suitable for a game server.

# Answer
> 0 votes
The only way to host over 3g would probably be to setup the 3G device to use a VPN, but it would be easier to just setup a Rackspace Cloud VPS.

# Answer
> 0 votes
Instead of having some one host it, just have the server make the first person in the room be the leader, and have the ability to pass leadership of they leave the game. Plus maybe use a password system for private games, but all servers show up in a public list, and have a lock icon next top the password servers. If someone starts a server they should be able to change the name and setting as leader.

---
Tags: android, multiplayer, client-server, socket
---


# Question
Title: Collision Detection Failing at faster Speed?
I am new to programming so thought I would make a Pac-Man clone to teach myself. I am doing it in C++ using SFML. Anyway, I use a bunch of collision tests. Everything works great.. but if I am going to fast then the collisions simply fail and nothing happens.

Pac-Man is moving though a factor = velocity * frametime;

I am using SFML rectangles to do the tests... eg...

sf::FloatRect.contains(pacman.getPostion);

This tests a point in space to see if it is inside the rectangle. The point being the centre of pac-man.

So yeah.. I would love to hear any ideas on this!

Thanks in advance --Jynks

```
if ( _rectSwitch.getGlobalBounds().contains( PacMan.getPosition().x, PacMan.getPosition().y )

```

# Answer
This is a problem inherent with basic AABB (axis-aligned bounding boxes) collision testing. The point is moving so fast that between frames it completely skips the box and "teleports" to the other side.

To solve this, the usual approach is testing a swept path against the box. In Pac-Man this would be either a perfectly vertical or horizontal line.

This explanation is already pretty detailed.
> 1 votes

---
Tags: c++, collision-detection, sfml
---


title: The point of using a scripting language

text:
# Question
Title: The point of using a scripting language
> **Possible Duplicate:**
> Why do we use scripts in development?

Im wondering, why do people use scripting languages like Lua or Python in game engines when we can use CLI/C++ or C# interpreters?

# Answer
> 1 votes
There are few advantages:

1. scripting languages can save lots of development time
2. the code can be "cleaner" and easier to modify
3. no need to recompile the code after each edit

And as the engine itself is usually written in compiled language, performance is usually not an issue and when it is you can port only the bottleneck code to C++, etc. and call it from your scripting language.

---
Tags: scripting
---


# Question
Title: How to initialize a BitmapDrawable Android
I have been using a shapeDrawable object for my android games player but now that i want to add some graphics in I have to use something different I was thinking of a BitmapDrawable but as I am new to this I have no idea how to initialize these sorts of classes, or how to get the image from the game resources could anyone put me on the right track or point me to some helpful tutorials.

# Answer
This is how you create a bitmap from a resource id :

```
bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

```

To create a BitmapDrawable from a bitmap :

```
bmDrawable=new BitmapDrawable(getRsources(), bm);

```

Be aware that, depending on the kind of game you are making, you might want to use the NDK and an opengl game engine like Cocos2d-x for example ( http://www.cocos2d-x.org/ ).

The Android SDK has not been designed for game, or maybe for simple games like crosswords, or sudoku, with not too much graphics fx. The powerful Android layout system on is designed to build a GUI for different screen sizes, but it's requiring too much CPU for most of the game.

I remember starting making a game for iOS 3 years ago with the UIKit library (equivalent of Android SDK/Layouts on iOS). The game was working fine but I was stuck with low performances, unresponsive touch screen, and it was impossible to add more on the rendering pipeline (like particles fx). I rewrote completely the game with Cocos2d, and that was so much better/smooth.
> 2 votes

---
Tags: android, html-canvas
---


title: Famous games written in Python

text:
# Question
Title: Famous games written in Python
I've seen a couple of these, namely Java and C#/XNA...and I've recently been picking up Python. Which kind of made me think.

What (famous) games have been written in Python, with Pygame/Pyglet/Pyopengl?

# Answer
> 23 votes
**Eve Online** is probably the biggest, and uses Stackless Python, a lightweight, microthreaded version of Python. And Civilization IV had a Python interpreter built-in, but I'm not sure if that was for scripting only, or how much of the game was written in it.

Also, Disney's Pirates of the Caribbean was written using the Panda3d game engine (which allows both Python and C++ scripting, but from googling it - Disney used Python). The *engine* is in C++, but then again, the Python *interpreter* itself also uses a lot of C code. :)

For a long list of games:

which also covers a lot of well-known games, like Mount and Blade.

# Answer
> 9 votes
The original version of Galcon was in pure Python, though it has long since been ported to other languages (at last count there were Obj-C, Flash, and C++ versions). It does still use Python for AI via the TinyPy library, but I suppose that is "just scripting".

As a general comment, Python isn't really well suited for making a blazingly fast graphics engine. You get far more control writing the core, performance-sensitive code in C or C++ and then writing the complex game logic in Python. Python excels at the more logic related areas since its expressiveness is a productivity win over C and the drop in performance isn't an issue. This is why everyone (CCP, Panda3D, Unity, Civ4, etc) all work like this. The real question is does this count as being "in Python"? For example, in Eve everything related to the actual game (more or less) is in Python, the C++ part is just a generic game engine that handles pushing pixels and audio.

# Answer
> 9 votes
Frets on Fire (in addition to Galcon, which is not native Python anymore) is the only "native Python" game I can think of that achieved some degree of lasting fame.

# Answer
> 4 votes
Also, Battlefield Heroes, the cartoony version of battlefield (Handles most of the game logic)

And, BattleField 2 and 2142 (For logic and server controls)

http://wiki.python.org/moin/PythonGames

# Answer
> 2 votes
Disney's "Toontown" and "Pirates of the Carribean Online" use the Panda3D engine with Python scripting.

http://toontown.go.com/
http://piratesonline.go.com/welcome

http://panda3d.org/

---
Tags: python
---


# Question
Title: How do I use transparent textures in panda3d?
I need to map a partially transparent texture on a flat quad with panda3d. With the quad as a canvas I'd like to create something like sprites positioned in the 3d coordinate system.

I wanted to render a tree. As you can see the color values of the trees border have been stretched over the texture. How can I change the texture mode to include the alpha channel ?

I just don't know how to get hold of the right settings. A link to the right manpage would be perfect. If you need more information about the setup you might want to look at my other question: How do I use setFilmSize in panda3d to achieve the correct view?

# Answer
ThomasEgi on the panda3d irc channel solved the problem. It's actually embarrassingly simple. You need to call

```
thenodePath.setTransparency(True)

```
> 4 votes

# Answer
Actually there are multiple transparency modes:

```
np.setTransparency(TransparencyAttrib.MAlpha)
np.setTransparency(TransparencyAttrib.MDual)
np.setTransparency(TransparencyAttrib.MBinary)

```

The manual explains these stuff.
> 3 votes

---
Tags: textures, transparency, panda3d
---


# Question
Title: My transparent objects overwrite opaque objects depth and always draw on top?
I have set up an 'Order Independent Transparency' method for drawing my transparent objects.

The algorithm can be simplified as follows:

DrawOpaqueObjects() DrawTransparentObjects()

Drawing the transparent objects uses the following render target setup:

```
        colourAccumulation = new RenderTarget2D(
            game.GraphicsDevice,
            game.GraphicsDevice.PresentationParameters.BackBufferWidth,
            game.GraphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            SurfaceFormat.Rgba64,           // 16 bit floating point texture (required for alpha blending caculations)
            DepthFormat.None
            );

        depthComplexity = new RenderTarget2D(
            game.GraphicsDevice,
            game.GraphicsDevice.PresentationParameters.BackBufferWidth,
            game.GraphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            SurfaceFormat.Rgba64,           // 16 bit floating point texture (required for alpha blending caculations)
            DepthFormat.None
            );

```

The transparent objects are combined with another render target texture that all the opaque objects are drawn to before hand:

```
        scene = new RenderTarget2D(
            graphicsDevice,
            graphicsDevice.PresentationParameters.BackBufferWidth,
            graphicsDevice.PresentationParameters.BackBufferHeight,
            false,
            SurfaceFormat.Color,
            DepthFormat.Depth16,        // Requires a depth format for objects to be drawn correctly (e.g. wireframe model surrounding model)
            0,
            RenderTargetUsage.PreserveContents
            );

```

They are combined as follows:

```
PixelShaderOutput PixelShaderFunction(VertexShaderOutput input)
{
PixelShaderOutput output;

// Background colour 'Cbg'
float4 BackgroundColour = tex2D(BackgroundSampler, input.TextureCoordinates.xy);

float4 SumColour = tex2D(Texture0Sampler, input.TextureCoordinates.xy);

// [Depth complexity]
// • Each time a pixel is written by the transparent object it adds 1 to the value [float4(1, 1, 1, 1)]
// • This is why a render target with 16-bits per channel is required (SurfaceFormat.Rgba64)
float n = tex2D(Texture1Sampler, input.TextureCoordinates.xy).r;

// If no transparent pixel has been drawn at this location, return the background colour
if (n == 0.0)
{
    output.Colour = BackgroundColour;

    return output;
}

SumColour = Upscale(SumColour);
n = Upscale(n);

// Average colour 'C'
float3 AvgColour = SumColour.rgb / SumColour.a;

// Average alpha based on depth complexity 'A'
float AvgAlpha = SumColour.a / n;

// T = (1 - A) ^ n
float T = pow(abs(1.0 - AvgAlpha), n);

// [Weighted Average Formula]
// • Cdst = (C * A * (1 - (1 - A)^n) / A) + Cbg * (1 - A)^n
// • Cdst = (C * A * (1 - T) / A) + Cbg * T
// • Cdst = C * (1 - T) + Cbg * T;
output.Colour.rgb = AvgColour * (1 - T);
output.Colour.rgb += BackgroundColour.rgb * T;
output.Colour.a = 1;

return output;
}

```

The problem is that all transparent objects are never obscured by the opaque objects drawn before hand as denoted by the yellow circle in the following picture:

The depth test has to be disabled for the transparent objects but it is enabled for the opaque.

Why is this incorrect effect occurring?

# Answer
> 3 votes
You want depth *testing* enabled (so that opaque objects block transparent objects), but you want depth *write* disabled (so that transparent objects don't update the depth buffer, and don't occlude each other).

```
depthState.DepthBufferEnable = true;
depthState.DepthBufferWriteEnable = false;

```

---
Tags: xna, c#, rendering, depth-buffer
---


title: Random number hlsl

text:
# Question
Title: Random number hlsl
How do you generate a random number in HLSL?

I'm asking because I want to try gpu ray tracing. You need to generate random directions in a pixel shader. So I want `randFloat()`, where the result is a random number between -1 and +1.

Also, what is the deal with the hlsl noise instruction? The docs say it was *removed* from HLSL 2.0 and up. **Why**?

I read about an approach where you fill a texture with random values, then have a texture coordinate in each vertex that has an index into that texture. But that's *per vertex*, I need an instruction I can call in the pixel shader. Plus this approach requires "reseeding" the per-vertex texcoords if you want different values each frame, and that requires a vertex buffer update each frame (which can be expensive!)

With detail, how can you cheaply generate a random number on the GPU?

# Answer
Pseudo random numbers in a pixel shader aren't easy to obtain. A pseudo random number generator on the CPU will have some state which it both reads from and writes to, on every call to the function. You can't do that in a pixel shader.

Here's some options:

1. Use a compute shader instead of a pixel shader - they support read-write access to a buffer, so you can implement any standard PRNG.
2. Sample from one or more textures containing random data, based on a parameter like screen space position. You can also do some maths on the position before using it to look up into the texture, which should let you reuse the texture if the maths involves a random-per-draw-call shader constant.
3. Find some mathematical function of screen space position, that gives results that are 'random enough'.

A quick google search found this page with these functions:

```
float rand_1_05(in float2 uv)
{
    float2 noise = (frac(sin(dot(uv ,float2(12.9898,78.233)*2.0)) * 43758.5453));
    return abs(noise.x + noise.y) * 0.5;
}

float2 rand_2_10(in float2 uv) {
    float noiseX = (frac(sin(dot(uv, float2(12.9898,78.233) * 2.0)) * 43758.5453));
    float noiseY = sqrt(1 - noiseX * noiseX);
    return float2(noiseX, noiseY);
}

float2 rand_2_0004(in float2 uv)
{
    float noiseX = (frac(sin(dot(uv, float2(12.9898,78.233)      )) * 43758.5453));
    float noiseY = (frac(sin(dot(uv, float2(12.9898,78.233) * 2.0)) * 43758.5453));
    return float2(noiseX, noiseY) * 0.004;
}

```
> 15 votes

# Answer
Here is how I generate pseudo random numbers for my particle effects with a compute shader. Not sure how truely random this code is but it works good enough for my purposes.

The key to giving each GPU kernel it's own random sequence is to feed the compute shader an initial random seed from the CPU. Each kernel then uses this seed to cycle the number generator using it's thread id as a count. From there, each thread should have it's own unique seed to generate unique values.

```
// Source
// http://www.gamedev.net/topic/592001-random-number-generation-based-on-time-in-hlsl/
// Supposebly from the NVidia Direct3D10 SDK
// Slightly modified for my purposes
#define RANDOM_IA 16807
#define RANDOM_IM 2147483647
#define RANDOM_AM (1.0f/float(RANDOM_IM))
#define RANDOM_IQ 127773u
#define RANDOM_IR 2836
#define RANDOM_MASK 123459876

struct NumberGenerator {
    int seed; // Used to generate values.

    // Returns the current random float.
    float GetCurrentFloat() {
        Cycle();
        return RANDOM_AM * seed;
    }

    // Returns the current random int.
    int GetCurrentInt() {
        Cycle();
        return seed;
    }

    // Generates the next number in the sequence.
    void Cycle() {
        seed ^= RANDOM_MASK;
        int k = seed / RANDOM_IQ;
        seed = RANDOM_IA * (seed - k * RANDOM_IQ ) - RANDOM_IR * k;

        if (seed < 0 )
            seed += RANDOM_IM;

        seed ^= RANDOM_MASK;
    }

    // Cycles the generator based on the input count. Useful for generating a thread unique seed.
    // PERFORMANCE - O(N)
    void Cycle(const uint _count) {
        for (uint i = 0; i < _count; ++i)
            Cycle();
    }

    // Returns a random float within the input range.
    float GetRandomFloat(const float low, const float high) {
        float v = GetCurrentFloat();
        return low * ( 1.0f - v ) + high * v;
    }

    // Sets the seed
    void SetSeed(const uint value) {
        seed = int(value);
        Cycle();
    }
};

```
> 3 votes

---
Tags: hlsl, random, gpu
---


title: Unit selection circle

text:
# Question
Title: Unit selection circle
I do not know whether it's called a circle, or whether it's called a halo or whatever.

But, I do know that I want to know what is the game development world term for this.

So, how do we call it?

# Answer
I would call it a **Selection Indicator**.

The green circle around the ship object as well as the beam and circle drawn on the ground are all part of it. The beam and circle on the ground are there to show the relative location of an object at one height with the location of an object on the ground or at a different height. It's a common strategy in 3D games, for example, Homeworld 2 made extensive use of similar drawing for movement:

Here are some Google image searches for Selection Indicator:

The blue part:

The green and red part:

The green corners:

**EDIT**

I've found the people call this, pretty much whatever they want.

* Selection Icon
* Selection Marker
* Selection Circle
* Selection Symbol
> 7 votes

---
Tags: terminology, selection
---


# Question
Title: Constant rotation of a revolute joint in box2d
I would like to have a line with one end attached to a location and have it rotate constantly (with the same speed) with a maximum of 45 to -45 degrees (i.e. I would like to have it swing like a rope back and forth 90 degrees).

Is this possible or should I use non box2d objects to do this (cheat box2d engine)?

# Answer
> 1 votes
That's certainly possible, but you might have do some tests to find the exact forces needed so that it works to your satisfaction.

Almost all joints can have a "motor" which you can enable and which applies a force to your joint. So in your case you have to set:

```
myJoint->EnableMotor(true);
myJoint->SetMaxMotorTorque(yourTorque);
myJoint->SetMotorSpeed(yourMotorSpeed);

```

You'll have to experiment with the torque.. I suggest you start with a pretty high value, so that the motor doesn't get hindered too much by other objects or objects attached to the joint. Also, if you want to limit the joint movement, you have to enable the joint limits. In the following example the joint would be limited to -90 to 90 degrees.

```
myJoint->EnableLimit(true);
myJoint->SetLimits(-90.0f * DEGTORAD, 90.0f * DEGTORAD);

```

The only thing left to do is to check if the joint reaches a limit and then switch direction. So in your update loop you would do something like:

```
float speed = myJoint->GetMotorSpeed();
float angle = myJoint->GetJointAngle();
if((speed < 0.0f  && angle <= myJoint->GetLowerLimit()) ||
   (speed > 0.0f  && angle >= myJoint->GetUpperLimit())
){
    // reverse motor speed whenever we overshoot limits
    myJoint->SetMotorSpeed(speed * -1.0f);
}

```

That should make your joint swing around from -90 to 90 degrees.

# Answer
> 0 votes
If you want to have it rotate at a constant speed, there's no reason to use a physics engine. Simply draw the line rotating one way then the other.

However, if you're actually interested in a swinging motion, constant speed is not going to give a very realistic interpretation. Check out pendulum motion to see the math behind the motion of a swinging object. Even with a pendulum, you shouldn't need the physics library to simulate it. You don't mention you'll have anything interacting with it, so just use a simple harmonic motion formula for movement.

---
Tags: iphone, box2d, cocos2d-iphone
---


# Question
Title: Generate random starting points at same distance between them
Is there an algorithm to generate random 2D points that are at the same distance between each other? Useful for starting points. Check map:

Don't be picky, I know in the image points are not at the same distance, lol, but you get the idea.

# Answer
> 7 votes
It's tough to be really "random" but this is how I would simulate it. Create a grid of equilateral triangles. The initial position and rotation of this grid can be random. Then overlay this grid onto your land mass. Now pick vertex points from that grid that fall on land.

# Answer
> 5 votes
I think the only way to get a set of points that are exactly equidistant from their neighbours is to place them on the vertices of an equilateral polygon, such as a square, pentagon, hexagon, octagon, equilateral triangle, etc.

Note that you can't guarantee that all points are equidistant from each other in 2 dimensions unless you limit yourself to 3 points on an equilateral triangle. (In 3 dimensions you can do it with a tetrahedron, and so on.)

If you're happy to have some points closer than others providing they have a uniform distance to whichever point is nearest (*e.g.* as in your example) then you can use any of the shapes listed at the top, plus any tessellated combination of those shapes (which excludes pentagons and octagons, etc).

Your image would not be possible to implement because the point in the middle would be nearer to all the others than the others are to their neighbours. But if you added another point you could have 6 equilateral triangles in a circle.

If we assume you don't need points to be at *exactly* the same distance, then you can try and generate positions through an iterative method. First, pick completely random positions. Then for each point, if it is closer to any other point than the ideal distance you're searching for, move it away from that point by a distance proportional to how far it would have to move to fix the problem entirely (*e.g.* 10%). If it's too far, do the opposite. Once you have done this for all points, keep repeating until either each point is a suitable distance from the others, or none of the points have moved much this iteration. At that point, you can decide whether the generated positions are good enough or not, and try again if not. This works well for an arbitrary number of points but won't necessarily guarantee a very regular shape.

Alternatively, if shape is important and you know how many points you need to place, generate the basic layout first (*e.g.* by tessellating some equilateral triangles) and then try to translate and rotate that to fit in your map. It's probably easiest to place the centroid of the layout over the centroid of the map and then just try a bunch of possible rotation values to see if any fit.

---
Tags: 2d, algorithm
---


title: Interactions between game objects

text:
# Question
Title: Interactions between game objects
I'm programming a basic Pacman clone to teach myself game programming. However, I'm struggling with the best way to have the game objects communicate/interact without my code becoming a huge mess.

Right now, I have a stack (implemented as a list) of objects in my base Game class. These objects include components such as Graphics, Input, etc. as well as "actual objects" such as Map, Pacman, etc. While running the game, the Game class loops through all of the objects and updates the ones which want to be updated and draws the ones which want to be drawn.

However, these objects must obviously interact. I implemented a Link function on the objects which allows one object to be "linked" to another; i.e. it gives one class a pointer to the other class so interaction can take place. For example, the Pacman class may use Link to be given a pointer to the Map class so Pacman can determine whether or not it can move in a certain direction.

With a game as simple as Pacman, this structure probably won't be too challenging to maintain, but were a game to have many interacting objects, I suspect the code would get out of hand. Is the method I am using right now alright, or should I look at another implementation of object communication? If so, what would you recommend?

I've looked at Communication between objects in games?, but whenever I try to implement the mediator pattern, I end up with a giant mediator class which is a challenge to maintain. Is the mediator pattern what I should be using?

# Answer
> 1 votes
In a small game like Tetris and perhaps Pacman, having everything know about everything is probably ok. In a larger game, an RPG, RTS, or any game with many subsystems and interactions, an event system can help. You lose some typesafety in the programming language, but you can decouple dependencies.

Instead of explicit function calls, game objects communicate by creating and consuming events. The event can be a single string, or a string/desciption of the event pluss one or more parameters. This is up to you. By using strings, your program will become more error-prone (typos) and maybe slower (an optimization is to use hashed strings). You could define events using a specific type in C++, allowing you to take advantage of compiler typechecks, but you lose the flexibility of defining new events at runtime. Plus, all users of that event will have to include it.

Here are some links:

http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

http://t-machine.org/index.php/category/entity-systems/

Java Entity-framework http://gamadu.com/artemis/

C++-based entity-event system in development http://totem-edk.com

Mike McShaffry has a chapter on event-systems in his book Game Coding Complete.

---
Tags: c++, objects, architecture
---


title: Create acceleration with direction

text:
# Question
Title: Create acceleration with direction
I want to move my object with an acceleration in the proper direction. For example if I have these values:

```
friction = 0.3;
direction = 180;
speed = 5;

```

For making it clear, I need a formula to create a linear acceleration.

# Answer
> 5 votes
You can calculate the invidual components by using sin and cos:

```
xSpeed = sin(direction)*speed;
ySpeed = cos(direction)*speed;
[...]
xPos += xSpeed;
yPos += ySpeed;

```

Accleration is simply increasing the speed.

```
xAccel = sin(accelDirection)*accleration;
yAccel = cos(accelDirection)*accleration;
// [...]
xSpeed += xAccel;
ySpeed += yAccel;

```

# Answer
> 2 votes
Acceleration is the rate at which velocity changes. If it is zero, then you will keep moving at your start velocity. If it is larger than zero, and in the same direction as the current velocity, velocity will increase.

```
velocity = old_velocity + acceleration;
position = old_position + velocity

```

If acceleration = 2, then your velocity will increase by 2 for each timestep.

# Answer
> 1 votes
To do any movement or physics calculations you should always use the time spent since the last frame (dt or delta); this depends on the main loop implementation, but is generaly passed to a method called update as parameter. (If this is not available assume dt = 1)

To update speed with acceleration and time and position with speed and time you can:

```
speed += acceleration * dt;
position += speed * dt;

```

Note that acceleration, speed and position are vectors, so they have the operations:

* vector addition
* scalar and vector multiplication

more info: http://en.wikipedia.org/wiki/Euclidean\_vector#Addition\_and\_subtraction

To create a vector with a given angle you can use the method described by Mr. Beast.

To simulate friction you can do something like:

```
speed -= speed * friction

```

Where friction should be a number: 0 \< friction \< 1

---
Tags: mathematics
---


# Question
Title: Slick2D: Changing an Image's colour to Color.white
I am working on a game where we would like the enemies to flash **white** when hit by a bullet. Ideally, we would like to use the same mechanism to render an Image in any colour. Our Images are all png files with transparent backgrounds and these transparent areas must exist in the coloured version of the Image.

Testing shows that Image.draw(x, y, filter) does not change the appearance of the image when given `Color.white`

Testing has also shown that Graphics.drawImage(Image, x, y, color) has no affect when `color` is set to `Color.white`

Is there a way to change an Image to **white** using existing Slick2D functionality? Failing that, is there an easy way to use LWJGL to perform the colouring that can be easily incorporated into a Slick2D project?

**NB** Answers that allow an Image to be rendered in an arbitrary colour will be preferred over answers that are specific to `Color.white`

# Answer
> 2 votes
I think I may have found the function you were looking for.

It appears that what you want is drawFlash: http://slick.ninjacave.com/javadoc/org/newdawn/slick/Image.html#drawFlash%28float,%20float,%20float,%20float,%20org.newdawn.slick.Color%29

This, according to the javadocs linked above "Draw this image at a specified location and size as a silohette".

(Kevin apparently cannot spell silhouette, but as Slick2D is just so stinking useful, we'll forgive him, no?)

If you are curious as to why your original attempt to rendering using a color filter did not work, I recommend googling color modulation, as that is what the color filter does, and why using Color.WHITE didn't work... all of the color components were multiplied by 1, which doesn't change them in the slightest).

All the best.

---
Tags: java, lwjgl, color, slick
---


# Question
Title: How many Fringe/Base layers in a 2D map editor?
I'm creating a highly flexible 2D tile-based map editor in XNA to make some of my future projects easier (will work for side-scrollers and top-down games). This editor can work with any sized tile.

This editor is based on a standard system. It has pre-determined layers such as Base, Fringe, and Collision. However, I've run into a bit of a problem. I don't know how many Fringe layers to use.

I'll be working with fairly detailed tilesets and will want enough Fringe layers to be able to render a wide variety of fairly complex scenes (e.g., forests with lots of trees overlapping).

I'm also considering having multiple Base layers to enable things like a player walking both over and under a bridge.

So my question is this: Is there a "right way" to approach this situation, and if so, what is it? Just lots of Fringe and Base layers? If you were a map editor, how would you expect/want this situation to be approached?

Also, while I have this question here, is storing layered maps in 3D arrays a good way to go about things? Meaning the first level is an array of layers, the second is an array of tile columns within the layer, and the third is the array of tile rows within the column.

# Answer
> 2 votes
There is a concept in software architecture called the "**Zero, One, Infinity Rule**". This basically states that you should support either zero of something, one of something, or any number of somethings. You should (almost) never write an application that supports (for example) 3 of something.

So in your case, if you are sure that a single "Fringe" layer will not be enough, the next solution - without considering any other requirements - is to support any number of fringe layers.

Of course, part of the problem is that you're committing a fairly major game development sin by creating technology for a game that doesn't exist. So any requirements are purely speculation. It is almost inevitable that you will over-develop some areas and under-develop others.

**If I were in your shoes:**

* My first reaction would be to stop making an editor at all, unless I had a specific game to go with it.
* Failing that, I would think about making base/collision/fringe layers all be "layers". At which point you have 3 of something - so according to the rule you should allow for any number of those things (and in any order). I believe this is what a few existing tile editors support. They let the game code handle the semantics of the layers.
* And, failing that, I would support a single fringe layer, and not implement multiple layers until an actual need for them existed. YAGNI.

One other important thing to note - one place where YAGNI may be worth ignoring is with your file format. If you choose to have just one layer now - but think you might add more layers later - be sure that your data is stored in such a way that you can store multiple layers without breaking old files.

---

To answer your "bonus" question: Yes a 3D array is acceptable until some other requirement comes along to contradict that. Although if you go down this route, be sure you are storing a proper 3D array (`[,,]`) not arrays of arrays (`[][][]`).

Personally I would go with a list of 2D arrays (`List<Tile[,]>`).

# Answer
> 1 votes
Well what you should do is not worry about that and design it to be flexible. Perhaps even allow the users to choose how many they want. But in reality, don't even bother until you have made your game or at least some sort of design doc. That way you can know what you actually need and can design around that. Like many have said, don't design engines, design games.

On a side note, in terms of memory layout, you can either use single or double arrays for the individual layers, then have a list or an array holding that, making a double/triple array.

---
Tags: xna, 2d, tiles, map-editor, draw-order
---


title: Interacting with box2D objects

text:
# Question
Title: Interacting with box2D objects
How can I interact with an object in box2d, I'm completely new to this so I have no clue what to do. The box is created like this:

```
bodyDef.type = b2Body.b2_dynamicBody;
fixDef.shape = new b2PolygonShape;

fixDef.shape.SetAsBox(0.5, 0.5); // Half-Width, Half-Height

bodyDef.position.x =  5;
bodyDef.position.y =  5;
world.CreateBody(bodyDef).CreateFixture(fixDef);

```

How can I change the x, y positions of that box, tried `bodyDef.position.x--;` but it returned "bodyDef is not defined". How do I access this?

# Answer
For moving here is SetTransform, for interacting MouseJoint. BodyDef is used to make creation of bodies easier, so it is used just in that function, you have to store value returned by CreateBody, and read documentation first.
> 1 votes

---
Tags: physics, javascript, box2d
---


# Question
Title: Why are my exported illustrator graphics blurry and messy in-game when scaling?
Non-scaled image:

And this is 2x-scaled:

I use 300dpi and did tick anti-aliasing settings for export png-24 image for my game in illustrator. But it look still bizzard when scaling. Could you please tell me what's wrong here??

What is the best way to get better art in my case?

Thank you in advance!

# Answer
Scaling up any bitmapped image such as png will always look pixelated. To avoid this, if you have the memory, save the non-scaled image twice the size you currently have now and scale down 50% to get it looking like the non-scale image in the above diagram. To get it looking crisp at 2x-scale, you don't scale at all because it is already at that size.

Your other option is to use vectors, but this can become expensive in terms of consuming processing time and may lack finer details compared to bitmap, i.e. look cartoony but that could be a positive on your game. You also need to find an appropriate library to do this. The advantage of using vectors is that it will most likely take up less memory and will look good, as long as it isn't too tiny, at any scale compared to using bitmaps.
> 4 votes

---
Tags: graphics, art
---


# Question
Title: How to simulate pressure with particles?
I'm trying to simulate pressure with a collection of spherical particles in a Unity game I'm building. A couple notes about the problem:

* The goal is to fill a constantly changing 2d space/void with small, frictionless spheres. The game is trying to simulate the ever-growing pressure of more objects being shoved into this space.
* The level itself is constantly scrolling from left to right, meaning if the space's dimensions are not changed by the user it will automatically get smaller (the leftmost part of the space will continually scroll off-screen).

I'm wondering what some approaches are that I can take to tackling these problems...

1. Knowing when to detect when there is space to fill and then add spheres to the space.
2. Removing spheres from the space when it is shrinking.
3. Strategies to simulate pressure on the spheres such that they "explode outwards" when more space is created.

The current approach I am contemplating is using a constantly moving wall, that is off screen and moves with the screen, as this image illustrates:

.

This moving wall will push and trap the spheres into the space. As for adding new spheres, I was going to have either (1) spheres replicate themselves upon detecting free space, OR (2) spawn them at the left side of the space (where the wall is) - pushing the rest of the spheres to fill the space. I foresee problems with idea #1 because this likely wouldn't really create/simulate pressure; idea #2 seems more promising, but raises the question of how to provide a location for these new sphere particles to spawn (and the ramifications of spawning them when there IS no space).

Thanks so much in advance for your wisdom!

# Answer
I'm not exactly sure what it is that you want to achieve, is the wall pushing the particles as the space rolls off the screen a game mechanic?

As for your three points, I think those behaviors would all emerge if you treat your particles like so: Have each particle repulse every other particle inversely proportional to the distance, and also have them collide with the walls of your space to stop them.

Particles close together would repulse each other and thus spread out to fill empty space until stopped by obstacles. If/when the walls move to make the space smaller, and push the particles, they will get pushed closer to other particles, repulse them stronger which in turn will push on other particles, increasing the overall pressure.

This would be pretty similar to an n-body simulation with negative attraction, so depending on the number of particles, it could get quite expensive to compute repulsion for every particle with every other particle. You could possibly try to simplify this by having each particle being repulsed just by the averaged center of gravity of your mass of particles, that might produce odd behavior in long thin areas with bends though (your gas not expanding into areas that bend away from the center of gravity, for example).

As for creating and deleting particles (to make sure there are just the right amount to visually fill the space I presume?), you would probably want to make sure not to simply add or remove particles when the density is lacking, as that would introduce more particles repulsing other particles, and hence increase or decrease the pressure.

So you might want to introduce a factor into the repulsion calculation, say start out with 1.0 and when you add x particles, make the new factor *n/(n+x)* where n is the number of total particles before adding the new ones.
> 6 votes

# Answer
Pressure (like in a gas) is just the result of plain elastic collisions between your particles and between the particles and the wall. You just measure the ammount of collisions per time with the walls to get a value for your pressure.

The 2 ideas you give have no direct connection to pressure, as pressure is given with a constant ammount of particles in a closed volumina and a given temperature (which results in the particles moving faster or slower).

If you add particles to this closed system, the pressure should rise, because there is more energy in the whole system (you just added a new particle with a given temperature\<-\>speed).
> 2 votes

# Answer
Each loop, you should iterate through all of your particles, and then calculate a final force on that particle. Basically, the wall always gives them a positive force vector on the x axis, if they are colliding with it (particle.x - particle.r \<=0).

Then, each particle they are colliding with also gives them a force vector, depending on the angle between them. You collect these angles for all particles, calculate the average, and there you go!

There are many optimization techniques you can use here, too, just look up some ball physics tutorial. You basically want to iterate through each **pair** of particles **only once** and calculate the force vector for **both** and store it in them.

This will simulate gasses, basically, and if you give them a constant force, liquids too, I presume.

As for creating and deleting particles, I implement a ParticleEmitter class, which has a position, direction and some other usefull stuff. Your example would be better off with an emitter that can create particles in a certain range, or even better, a rectangle.
> 0 votes

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


# Question
Title: Using Coffescript in HTML5 game development?
I just stumbled on this library/language called Coffescript, and thought it would do the coding part so much easier.

As an example, drawing maps with a `for` loop would be:

```
map = [0, 0, 0, 0, 0]

drawTile = (tile, tx = tile * ts, ty = 0) -> c.drawImage(tile, tx, ty)
drawTile tile for tile, i in map

```

Translates to this:

```
var drawTile, i, tile, _i, _len;

drawTile = function(tile, tx, ty) {
  if (tx == null) {
    tx = tile * ts;
  }
  if (ty == null) {
    ty = 0;
  }
  return c.drawImage(tile, tx, ty);
};

for (i = _i = 0, _len = map.length; _i < _len; i = ++_i) {
  tile = map[i];
  drawTile(tile);
}

```

I've only had an hour to look at this, but sofar I think its beautiful. My question is how would this fit into HTML5 game development? Could there be any problems using this that I don't see?

I know the code above is useless in a real game, but I haven't figured out loops yet.

# Answer
No, there is no problem in using CoffeeScript, if you really want to (I like this language, too). Everything that runs in Javascript runs just as well in Coffeescript.

The only issue you could have is with debugging. The only way to debug is to look into the Javascript code, which is not the code you produced. But if you can handle that, go ahead.
> 1 votes

---
Tags: html5, coffeescript
---


title: Best way to design a negotiation deal?

text:
# Question
Title: Best way to design a negotiation deal?
I'm currently coding a heavily text-based RPG game which requires you to do deals with characters or suppliers in the game, sometimes the deals are good/bad.

Currently the way I'm doing it is that, given your current XP level, you get a list of suppliers with the offers/prices they give are fixed.

Its okay, but a bit basic -- plus there's no sense of feeling where you're cutting a good deal or not.

I've been thinking of other ways to handle negotiation, the only game I'm aware of that has a deal system is the old Amiga and DS game, Theme Park as seen in this movie clip on Youtube:

Theme Park DS, http://www.youtube.com/watch?v=vS8i9E8mUmg

Other than this, what would be a good way to display or design a negotiation deal which gives the user a sense of a good/bad deal.

Thanks

# Answer
One way of doing this is have your bartering ability tied to a character attribute.

Then, you could decide on the transaction factor against the canonical price of the item.

For example, When buying items, the canonical price is divided by the transaction factor, and when selling item, it is multiplied.

One way to work out the transaction would be the ratio of the Merchant's bartering skills against the players.

For example:

```
Gwendoline has 'bartering' @ lvl 60
Merchant has 'bartering' @ lvl 30
'Sword of unholy truth' has canonical value 100 gold pieces
transaction factor is 60/30 = 2.0
Gwendoline can buy 'Sword of unholy truth' for 50 gold pieces.
Gwendoline can sell 'Sword of unholy truth' for 200 gold pieces.

```

Now, with the relative skills reversed:

```
Tristan has 'bartering' @ lvl 10
Merchant has 'bartering' @ lvl 50
'Chalice of Good Times' has canonical value 100 gold pieces
transaction factor is 10/50 = 0.2
Tristan can buy 'Sword of unholy truth' for 500 gold pieces.
Tristan can sell 'Sword of unholy truth' for 20 gold pieces.

```

Morrowing, Oblivion and Skyrim have a similar system, although they add several twists:

* Letting the player choose the transaction factor
* Have the merchant accept or refuse the player offer based on skills, luck and how much the merchant likes the player (the merchant's disposition towards the player)
* Every refused offer reduces the Merchant's disposition towards the player, making bartering harder.

In order to show how good/bad a deal is, you can simply display the canonical price, so that the player knows how much they've been had.

You probably don't want the players to do any math, so it would probably be best to use a traffic light system, that shows red when it's a bad deal, amber when the deal is OK, and green when you're making lots of money.

Some other twists you can have:

* Have Merchants that have better deals for some merchandise than others. This could be implemented by having the merchant skill be item-type specific. For example, it should be easy to swindle a potion merchant into buying a sword at more than fair value, but much harder to pull the same deal with an armourer.
* Don't show the players their bartering skill score, but instead increase it slightly with every transaction they make and have the score reflected in the dialogue of the merchant:
    + You're eating me out of house and home! (high player skill)
    + You drive a hard bargain!
    + I think I gave you a fair price, don't you?
    + Please come again soon
    + It was such a pleasure doing business with you (low player skill)
> 4 votes

---
Tags: game-design, rpg, interface
---


# Question
Title: Avoid the same code several times in game state enum
I use a switch with enums to divide my game in different parts. In the code below, that is simplified, I have a problem, becasue I need to show the same text in two or perhaps more parts and I wonder if there is a better way to do this, to avoid the use of the same code at several cases?

```
 switch (currentGameState)
        {
            case GameState.Start:
                // Code
                break;

            case GameState.Info:
                // Code
                break;

            case GameState.PlayGame:
                spriteBatch.Begin();
                spriteBatch.DrawString(scoreFont, "Score : " + currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.DrawString(timeFont, "Time : " + secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.DrawString(timeFont, "Spaceship : " + numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.End();
                break;

            case GameState.NewSpaceship:
                spriteBatch.Begin();
                spriteBatch.DrawString(scoreFont, "Score : " + currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.DrawString(timeFont, "Time : " + secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.DrawString(timeFont, "Spaceship : " + numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
                spriteBatch.End();
                break;

            case GameState.GameOver:
            // Code
                break;
        }

```

# Answer
> 4 votes
This is what functions (and methods) are for. Create a new function, add those 5 lines to it, and call the function in each switch case instead.

# Answer
> 4 votes
You have a few options. You can double up cases on switch statements. Remember if those `break`s aren't there, the execution just continues along:

```
case GameState.PlayGame:
case GameState.NewSpaceship:
   spriteBatch.Begin();
   spriteBatch.DrawString(scoreFont, "Score : " + currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.DrawString(timeFont, "Time : " + secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.DrawString(timeFont, "Spaceship : " + numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.End();
   break;

```

Or you can pull out your duplicate code into a function:

```
case GameState.PlayGame:
    Draw();
    break;
case GameState.NewSpaceship:
    Draw();
    break;

```

Then somewhere else in your code:

```
public void Draw() {
   spriteBatch.Begin();
   spriteBatch.DrawString(scoreFont, "Score : " + currentScore, new Vector2(10, 10), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.DrawString(timeFont, "Time : " + secondsToDisplay, new Vector2(10, 30), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.DrawString(timeFont, "Spaceship : " + numberOfSpaceship, new Vector2(10, 50), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
   spriteBatch.End();
   break;
}

```

Or do both!

```
case GameState.PlayGame:
case GameState.NewSpaceship:
    Draw();
    break;

```

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


# Question
Title: Shader compile log depending on hardware
I'm done with the core of my graphics engine and I'm testing it on every platform I can get my hands on. Now, what I noticed is that different drivers return different shader and program compile log content.

For example, on my friend's laptop if you successfuly compile a shader then the log is simply empty. However on my PC I get some useful information along with it.

So if I compile a vertex shader, I'll get:

> Vertex shader was successfully compiled to run on hardware.

Which isn't that impressive, but is what happens when I compile a program. On my friend's computer the log is empty, since the program compiles. However on my own computer I get:

> Vertex shader(s) linked, fragment shader(s) linked.

Which is awesome, because I'm attaching a geometry shader with 0 (I have a geometry shader file with trash, so it doesn't compile and the pointer is set to 0), and the compiler just tells me which shaders linked.

Now it got me thinking, if I was going to buy a graphics card, is there a way for me to get the information about whether or not I'll get this "extended" compile information? Maybe it's vendor specific? Now I don't expect an answer TBH, this seems a bit obscure, but maybe somebody has any experience with this and could post it.

# Answer
> 1 votes
Well, what I do in my engine is write the contents of the shader log to my own log, regardless of whether the compile failed or not. Then I check whether the compile actually failed. Here's what that looks like:

```
    // compile vertex shader

    m_HandleVertex = glCreateShader(GL_VERTEX_SHADER);
    const char* code_vert = m_CodeVertex.c_str();
    glShaderSource(m_HandleVertex, 1, &code_vert, NULL);
    glCompileShader(m_HandleVertex);

    glGetShaderiv(m_HandleVertex, GL_INFO_LOG_LENGTH, &bufflen);
    if (bufflen > 1)
    {
        GLchar* log_string = new char[bufflen + 1];
        glGetShaderInfoLog(m_HandleVertex, bufflen, 0, log_string);
        LOG_TRACE("Log found when compiling '%s.vert':\n%s", m_Name.GetData(), log_string);

        delete log_string;
    }

    glGetShaderiv(m_HandleVertex, GL_COMPILE_STATUS, &success);
    if (success != GL_TRUE)
    {
        LOG_ERROR("Failed to compile vertex shader.");
        return false;
    }

    LOG_TRACE("Compiled vertex shader.");

```

So, to answer our question: I don't think there's a way to detect whether a vendor returns an empty string on success or a string with "No errors". The best you can do is output the log when you have one, but also check whether it actually compiled.

# Answer
> 1 votes
With OpenGL the hardware vendor must provide the full GLSL compiler as part of their driver, so you're always going to get different results for different vendors, and may even get different results for different revisions of the same vendor's driver.

The textual output in the logs is useful for helping with errors, but I honestly wouldn't rely on it for much else. For the specific case you mentioned - which shaders are attached post-link - try glGetAttachedShaders instead. There are other glGets which will also give the kind of useful info you're looking for but won't be hardware-dependent, so that's the way to go (plus you can programmatically respond to unwanted conditions without having to parse textual output).

# Answer
> 0 votes
The shader is compiled by your graphics driver. As far as I am aware, it is done on the CPU but cannot be done without the GPU because it needs to know the target platform's features and limitations (although that's not entirely true... there are some compilers that can compile offline but just like our C/C++ compilers, they must have a target platform).

Anyway, the point of the above paragraph was to conclude that the compile errors you will get (or won't get) depend directly on the vendor and their drivers for the graphics card.

So is there any way to get the information before hand? That is a very good question and unfortunately I could not find any documentation with the drivers that would allow us to assess what the compiler features are (and perhaps a list of error/success codes which will in turn let us know the errors it is capable of handling).

# Answer
> 0 votes
As others have said, the output depends on vendor and driver version since that's where the compilation occurs.

I wrote an offline command-line app that compiles the shaders and just spits the log back to stdout and stderr. I run that as a compilation step within Visual Studio, which parses the output (which most drivers report in a standard format with line/col numbers, etc.) and reports it to the error and warning list as appropriate. It's nice to be able to see and navigate to errors at compile time, and the tool was very simple to create.

---
Tags: graphics, glsl
---


# Question
Title: How do I clear a specific render target when more than one are set?  Or how do I keep the depth but clear the color?
Let's say I set two render targets

`GraphicsDevice.SetRenderTargets(rt0, rt1);`

If I call

`GraphicsDevice.Clear(Color.Transparent);`

both render targets will be cleared.

Therefore, how can I clear a render target at a specific index? For example just 'rt1' and not 'rt0'.

I would like to avoid texture baking the contents of 'rt0' to another render target and copying them back to 'rt0'. This is because PreserveContents on the XBOX 360 can only hold one render target in memory.

EDIT:

Is there any way just clear the color for a render target? I would like to keep the depth for depth reading.

# Answer
To clear a specific render target you can either call SetRenderTarget() with only the one you want to clear, or use a pixel shader that outputs an opaque colour to one target and transparent to the other.

To avoid clearing depth use `GraphicsDevice.Clear(ClearOptions.Target, Color.Transparent, 0.0f, 0);`
> 1 votes

---
Tags: xna, multiple-render-targets
---


# Question
Title: Drawing very large slowly rotating planets
I'd like to draw very large (~500 px) graphics of planets slowly rotating. These graphics are meant to impress. What's the best way of doing this? I don't have experience with any particular 3D engine, and I'm not even sure what platform this game would run on, so:

* I could pre-render each frame, but at 500px and a rotation period of 10 seconds, that's a ludicrous amount of data per planet.
* I could use a 3D engine and map the planet's texture onto a mesh approaching a sphere, but at 500px, I fear the polygon count would have to be huge to make it look good.
* I could write a kind of custom 3D engine that does nothing but efficiently render a textured sphere, by converting the x/y coordinate of each view pixel into the coordinate space of the sphere's texture - but this is involved, and couldn't benefit from graphics acceleration.
* Something else I haven't thought of?

Here's an example animated GIF of what I mean. (At 100x100 px and 60 frames, it's already pretty huge, sorry.) Imagine this much, much bigger, rotating much slower, and animated more smoothly:

But if this were 500x500 px and 10 x 25 = 250 frames, we'd be talking about hundreds of MB of data, so this straightforward approach doesn't work.

# Answer
> 10 votes
The number of polygons to render a "good looking" 500x500px sphere with a single draw call is trivial for GPUs to handle on most platforms, especially if there isn't much else in the scene. There's also some notes about texturing spheres to avoid texel distortion; make sure to use a cube map.

# Answer
> 4 votes
Since you are looking at the sphere with a constant camera, you can do high quality rendering extremely fast with a simple precalculated lookup-table.

As the precalculate step, with any method you like (usually with polygons or raytracing) you render a texture mapped sphere to an offsceen buffer, but instead of calculating the colors based on the texture, you only store the texture u/v-coordinates.

Then when rendering the actual planet you render a simple square and for each pixel you fetch the actual u/v-coordinates from the lookup-table and the pixel colors from the planet texture using those u/v-coordinates. To rotate the sphere you just offset the u-coordinate with the rotation angle.

This technique was very popular in the demoscene for example with texture mapped tunnel effects, but unfortunately I couldn't find any good tutorials about it.

# Answer
> 0 votes
If you are doing this in a 2D setting, see this previous question...

3D Illusion of a 2D Planet Texture

The same concept would work fine with a large image and by dynamically moving the terrain texture on a layer beneath the "hole" in space.

Read the above link to know what I mean by this.

# Answer
> 0 votes
If you compressed the resulting animation with a modern video codec, it wouldn't be particularly big at all and nowhere near "several hundred MB of data" nor ludicrous...

But as already stated, it all depends on what your target platform is and as everyone else said; just rendering a smooth 3D sphere would actually involve an insignificant amount of polygons and very little data storage (the texture being all there is and even at really high resolutions, standard jpeg compression would bring it down to nothing).

It all also depends a bit on how picky you are - if you're after the quarter-pixel-scrolling-look and texture details on par with state-of-the-art demos and not just contemporary games with all their interpolation and aliasing issues even at 8x FSAA - then it could get almost endlessly involved to achieve (and require a bit of artistic trickery as well) ^^

# Answer
> 0 votes
If you have issues with performance doing this the traditional way (texture and normal mapping on a high polygon sphere), which as many have mentioned should not be a problem at that resolution:

"Raytrace" it with a fragment shader. If your camera is fixed all you need is a uniform float input to your fragment shader (for the angle of rotation) and the shader can take care of computing the texture coordinates. The lighting vectors might even be the same each frame as well. As for anti-aliasing you can also get a perfect spherical silhouette with little ingenuity (if pixel is on sphere boundary, compute its coverage)

This has you only sending 4 vertices through the pipeline, and does not require you to allocate a gigantic multisampled framebuffer to fight jaggies.

At the cost of having to come up with several built-to-order algorithms.

---
Tags: 2d, 3d, graphics, graphics-programming
---


# Question
Title: How to make multiple levels game in XNA game studio 4.0?
I am doing 2D game using XNA framework 4.0. I'd like the game to have multiple levels. Where do I store the levels and how do I implement a scoring system for the game? Can I use XML for storing data for that levels and scores? Finally, is there any code samples for a multiple level game in Windows phone 7 using XNA 4.0?

# Answer
> 2 votes
See the platformer kit on the app hub. Includes Xbox, PC, and WP7.

http://create.msdn.com/en-US/education/catalog/sample/platformer

It has examples of what you are asking (including XML levels).

# Answer
> 0 votes
Well, you can store games in the content folder (make sure to set them to compile:none in the item properties) and then load them using

**\[Microsoft.Xna.Framework.Storage.TitleLocation + Content.RootDirectory + file\_name\]**

using something like StreamReader or XML (it also does not have to be in the content folder but just the game root directory). To load them, either hard code their names into the game or name the files like 1.level, 2.level, etc.

# Answer
> -1 votes
You can store arbitrary XML files in the XNA asset manager but remember to set the compiling off for those files (so the remain as plain text and don't get saved as binary files). You can see an example in my open source game Urban Race. It's 3D but the concept still applies, I read XML for the levels at runtime, just what you want.

---
Tags: xna-4.0
---


title: Good open source iOS games?

text:
# Question
Title: Good open source iOS games?
I would like to see how things are done in modern iOS games, I am especially interested in Cocos2D games. I need a game that will compile (warnings are ok) and since most of the project I have seen fail with errors that I can't fix, I decided to ask here. Maybe someone knows some?

# Answer
There are two books that have complete games for cocos2d in them. Both books seem to take slightly different but equally valid approaches to game design with cocos2d.

Learn Cocos2d Game Development with iOS 5, by S. Itterheim and A. Low.

Learn Cocos2d: A Hands-on Guide to Building Games with Cocos2d, Box2d, and Chipmunk, but R. Strougo and R. Wenderlich.
> 2 votes

# Answer
Fabien Sanglard has released an engine/game of his written in C. It's not exactly AAA quality, but it runs and compiles on all major platforms (iOS and Android included). He has quite a few writeups describing various aspects of it, including why he chose C. You can find it here.
> 0 votes

---
Tags: cocos2d-iphone, ios, objective-c
---


title: JavaScript rendering: Canvas or DIV?

text:
# Question
Title: JavaScript rendering: Canvas or DIV?
I am planning on developing a multiplayer RPG (kinda like RuneScape, but don't worry, with a different gameplay) and i want to do this in the browser. Now before saying things like "A MMORPG is hard to make" or "Others tryied that too" please keep in mind that i am not dreaming at a huge game, it's just an idea that i want to see "breathing".

The reason i choose JavaScript and HTML5 over other technologies is that i have some experience in web development (which of course includes a deep understanding of JS).

I've looked over some libraries (or so called engines) on the web and i've found some that **might** have what i need.

My question is: **What is the best way to render this kind of game in the browser, also could you suggest me the library that you think is the most suitable for this kind of job?**

# Answer
That's completely game-specific, actually.

If your game is in some very simple/discrete space, then moving divs around will do.

But if you really want to do more complex graphics without much coding, go with the standard for HTML5 games - the canvas element. Do note that many HTML5 game engines support DOM rendering, but I'm not sure to what extent, I doubt that you'll have that awesome canvas API at your disposal.

As for engines, refer to this answer: https://gamedev.stackexchange.com/a/32777/9736.

The only other comparison I can make between the canvas and the DOM is that the DOM is a bit faster, or so I hear. But really, nothing substantial.
> 4 votes

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


# Question
Title: Is it possible to read the frame to be output to the screen from GPU in XNA?
I want my XNA game to do its thing and at the end of the Draw() call read the the frame that is sent to the screen into memory (which in XNA would presumably be a Microsoft.Xna.Framework.Color\[\]).

Is is possible to this from XNA? If so how and when should I do it? Immediately before or after my:

```
base.Draw(gameTime);

```

call?

# Answer
(This was going to be a comment but it got too long, so...)

Not an XNA-specific answer, but in general terms this is something that you ***don't*** want to do.

The reason why is because of the way your GPU and your CPU work together. Draw calls and other commands that you send to the GPU don't happen immediately; instead they go into a buffer and your GPU will get round to processing them sometime later; it can normally be up to 3 frames later. This is one of the reasons why GPUs get to be so fast; the CPU can continue doing work at the same time as the GPU is processing draw calls and other commands.

Reading back from the GPU will break all of that. In order to read back from the GPU, the CPU has to pause, the GPU has to immediately execute everything that's been buffered up to the time of the readback, then the readback happens. No more asynchronous processing, instead you get a massive stall. Because of the "up to 3 frames" buffering, you can lose up to two-thirds of your performance. That's not trivial.

So, like I said, you really don't want to do this if at all possible. If there is something specific you're trying to achieve then letting us know what that something specific is can be helpful, as there are often solutions that don't involve a readback but will give you the result you want without the huge performance cost.
> 3 votes

# Answer
You generally don't want to do it, and mh01 explains why very well in his answer. You don't want to make it part of gameplay. You might want to add it for taking screenshots or video. But I recommend an external tool like Fraps for that anyway.

But, that being said, you can do it in XNA. There are two methods.

Method number one is to call `GetBackBufferData` (MSDN). You need to set your game project to the HiDef profile (the method is not compatible with the Reach profile).

(I also think you may need to play with the `RenderTargetUsage` of the backbuffer, if you also want to render that frame to the screen. I haven't played with it enough to be sure. But this answer gives you a starting point.)

The place to do this is right before the end of your `Draw` method. You could even put it in `EndDraw`. It basically needs to happen after everything is drawn, but before the backbuffer gets sent to the screen (and becomes unavailable to you).

The second method works in the Reach profile. The theory is similar, but instead of drawing to the backbuffer, you draw to a `RenderTarget2D`. You need to set that as the render target (with `GraphicsDevice.SetRenderTarget`) either at the begninng of your `Draw` method, or where you would otherwise call `SetRenderTarget(null)` (which would set the back buffer as the render target).

At the end of your `Draw` method, you've got an empty backbuffer and a render target with your scene in it. So simply call `SetRenderTarget(null)` and then use `SpriteBatch` (or similar) to draw the render target to the backbuffer to make it display.

When you want to extract the content of the render target, call `RenderTarget2D.GetData`. You can also use methods like `SaveAsPng` \- which is convenient if you are trying to implement a screenshot feature.
> 1 votes

---
Tags: xna, gpu, depth-buffer
---


# Question
Title: How do I identify a collision with a specific body?
How can I identify when the ground body collides with another b2Body? I can use `b2ContactListener` to be notified of collision events, but how do I tell which bodies collided?

# Answer
This is the point of b2Body's `UserData` member. It's a pointer you can set to anything you want. During the collision you can check this pointer and change how you react to the collision depending on its value.

For a trivial case, you can make the user data a NSString. For example,

```
groundBody->SetUserData(@"Ground Body");

```

Then inside your `b2ContactListener` subclass, or when you loop over bodies checking their contact points, you can use:

```
if ([bodyA->GetUserData() isEqual:@"Ground Body"]) {
    // Do something special if the body is the ground body.
}

```

(n.b. This is not compatible with ARC. I wouldn't recommend using ARC with games yet if you're an Objective-C beginner. The libraries aren't ready and the best idioms have not gelled).
> 1 votes

---
Tags: iphone, cocos2d-iphone, box2d
---


title: Refresh a single view

text:
# Question
Title: Refresh a single view
The game I'm working on is based on different levels. I can use different activities or only one activity with different layouts ( or maybe only one layout, you have to apologize me but I'm studying alone and it's pretty hard to learn alone ).

My problem is: I'm not sure what is best way to implement levels in game. If I use only one activity as container for each level, where I design each level as different layout, how can I refresh my current activity with the new content ? To make it clear, think about "Cut the rope", is every level a different activity or they load different xml's on the same ?

I'm sorry if this question is not properly written, but I can't find more specific terms to make it better.

# Answer
> 1 votes
In general your "game" is a single activity. You may have several activities in your program if you end up include external libraries like an ad-service.

I can't speak to the "best way" to implement levels, but one way is to implement your level's view and logic in a generic manner and use simple files (text, xml whatever) to describe the specifics. This may all sound vague at first, but consider what makes up a simple level in a game such as Nintendo's "Super Mario" on the NES. The level made up of a background, some foreground objects (bricks, pits, ?-blocks), and enemies (Koopas, Goombas) and the flag pole at the end. If your level's implementation knows how to apply a background, place fore ground objects in the world, places enemies, and set the end goal, then adding the new levels is easy, just add a new level input file.

In your "Cut the Rope" example, it is unlikely (I say unlikely because I didn't write that game) that a different layout is used for each level. More likely is there is a single game activity using a single layout for the game's view. Each new level reuses the same layout and replaces the content.

# Answer
> 1 votes
In Android, anything you can do in XML layout file can be also be created via Java code. For example, instead of using the XML tags you could have your code that initializes the level create one:
`LinearLayout myLL = new LinearLayout(this);`

`myLL.setOrientation(LinearLayout.HORIZONTAL);`

`TextView text = new TextView(this);`

`myLL.addView(text);`

Check the API documentation to dynamically create the objects that your game needs to display for your level.

---
Tags: java, android, architecture
---


# Question
Title: Why use this equation to get a percentage?
In an XNA book I read that this code does an action with a 0.2% of probability but I don't' understand why:

```
float chance = 0.2f;

if((float)rand.Next(0,1000) / 10 <= chance)
{
...
}

```

I understand the statement, but not the reasoning for that equation. Can anyone explain me, please?

# Answer
> 11 votes
```
(float)rand.Next(0,1000) / 10

```

Picks a random number between `0` and `1000`, the divides by `10`. This gives you a random number between 0 and 100. If that random number is less than or equal to your chance (`<= .2`), then the statement is true and whatever is inside the if statement is executed.

If you want to get a .2% chance, that means that for every .2% of the times you run this code it will be true. So how do we do that? Pick a random number between 0 and 100, if it's less than .2 it's true.

Throw a random dart at this image:

If the dart were truly random, you'd expect it to hit blue 50% of the time and red 50% of the time. So we want something to happen 50% of the time, this is what we would use. So what if we wanted it to happen .2% of the time? I means our image needs to look at bit less equal.

Throw that random dart at this image and you'll hit blue .2% of the time.

***EDIT to address your comment***

The thing about random numbers is that they don't care about the number that was chosen before them. If you were to flip a **fair** coin, you have a 50% chance of it landing on heads and a 50% chance of it landing on tails. So should would you be surprised if you flipped it twice in a row and it came up heads both times? No, I don't think you would. How about if you flipped it 6 times, would you be surprised if if came out 4 tails and 2 heads? No that is totally possible. How about 6 heads in a row? Well that is certainly less expected, but it's not impossible. What about 100 flips and they're all heads? Now that seems totally impossible. But it's not, it's just very, very unlikely. Here's the thing though. If you're on flip 99 and they've all been heads up until that point, there's still only a 50% chance that the next flip will be heads too. The next flip has nothing to do with any of the previous flips or any of the flips to come after. Just because you've had 99 heads in a row doesn't make it any more likely that the next flip will be tails (see Gambler's fallacy). However as the sample size grows the number of heads and number of tails will start to equalize. See this simulated coin toss distribition:

As you can see, there are times where if you stopped right then, things would look very unbalanced. But as the sample size continues to grow, it does start to equalize towards 50/50. You can also see that I got lucky and this animated gif matches the color scheme I picked :).

Probability belongs to statistics. Statistics is one thing that people are typically not good at (if you need proof of that, just look at all the lottery players). It is however very beneficial to study statistics. It'll help you in programming and life in general.

Basically what you should take away from this is:

* Random numbers are not affected by any number that appeared before or after them.
* With small sample sizes, the distribution of probability might look wrong, so don't worry.
* The lottery is a tax for people who don't know statistics
* Random numbers do not guarantee their distribution
* Know statistics well and you will be a superhero

# Answer
> 12 votes
There is no reason. It's just a stupid thing which works but is completely unnecessary. The author probably just wanted to write down the chance as percent and not as permille .

Better is:

```
// In Permille: 2‰ == 0.2% == 0.002
int chance=2;
if(rand.Next(0, 1000) <= chance)
{
  [...]
}

```

It will give you the same result but without those divisions and conversions to float.

Or if you prefer floating points over fixed numbers:

```
double chance=0.002;
if(rand.NextDouble() <= chance)
{
  [...]
}

```

# Answer
> 8 votes
The part `(float)rand.Next(0, 1000)` generates a number between 0.0f and 999.0f inclusively.

Then, you divide it by `10` to get a number from 0.0f to 99.9f.

Checking if the number is *below or equal* to `0.2f` checks if we hit the desired percentage, hence giving it a `0.2%` chance of entering that if block.

Why the equation `(float)rand.Next(0, 1000) / 10`? Because you want to at least have a *chance* of getting into that if block.

If it had been simply `rand.Next(0, 100)`, it would have entered the loop 1% of the time (when it would have given 0).

If my maths are not actually failing me this morning, by using the `(float)rand.Next(0, 1000) / 10`, you get the range from 0 to 2 (3 numbers) that give you a chance of entering that loop (since they are the only that `x < 10 >= 0.2`). `3/1000` gives your 0.003, or 0.3% chance (you'd have to remove that `=` from `<=` to get that actual 0.2%).

Instead, I recommend you to use `rand.NextDouble()` in your code. It is less obscure for other programmers (or yourself after a few months not looking at the piece of code) and more flexible.

Example of use in your context:

```
const float Chance = 0.2f; // I gave them programmers consts, programmers loooove const variables.
const float Percent = Chance / 100.0f; // divide by 100 to actually get the 0.2%

if (rand.NextDouble() < Percent)
{
    ...
}

```

# Answer
> 4 votes
Sorry I misinterpreted your question, here is the actually working code simplified as much as possible so that it's easier to see what's going on.

```
double chance = 0.2; //we use real percentages now

//We choose a random number in [0...999] because we want enough precision for 1000
//different chances (100% to 0.1% or even 0%), we multiply our chance by 10 to
//move it from the 0.0~100 range into the 0~1000 range
if(Random.Next(0,1000) < chance * 10)
{
   ...
}

```

---

**This is the old, wrong answer, here for reference only, I missed that it was .2% and not the 2% I assumed**

I don't get the equation either its convoluted, we could do without the weird division by and 10 and it's not clear why a random number in \[0...999\] is chosen instead of a random number in \[0..99\], maybe that's why you're having trouble with it. Let's get rid of the unnecessary cast and the division and clean it up as much as we can. The equivalent and, in my opinion, much more readable version would be:

```
double chance = 2; //we use real percentages now
if(Random.Next(0, 100) < chance)
{
    ...
}

```

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


title: Blending colors on Surfaces in PyGame?

text:
# Question
Title: Blending colors on Surfaces in PyGame?
So I'm making a game in Python and PyGame. I have aliens and blocks that each adopt one of several colors; rather than make several copies of them in different colors, I plan on making the sprite once in white, and recoloring individual aliens and blocks.

Problem is, with PyGame, I only know how to use PixelArrays to replace specific colors with other colors (e.g. pure white with pure red, or (255, 255, 255) with (25, 34, 255)). The sprites aren't going to be super complex, but they will be shaded.

I *could* use the Python Imaging Library, but I'd kind of like to minimize dependencies. If this is the best way then so be it.

What I'd like to know is this; how can I use color-blending in PyGame? More than anything I'm concerned about color-blending algorithms (that ignore certain desired colors, e.g. black for outlines). Alpha blending is not of concern.

# Answer
So apparently it's actually not that hard.

This site right here, though aimed at Web development, has some useful tips for software development in general. And I just so happened to find a series (five parts so far!) about image blending.

The tutorials are in Javascript, but that doesn't matter, the main feature here is the math (it's just algebra). You can ignore pretty much anything not highlighted in blue; these tips are good for blending images or colors. Just iterate over every pixel, and apply each blend pixel by pixel with the given formulas. Too many blending modes to describe here right now.

As for PyGame? First create a `PixelArray` of a `Surface` so you can manipulate individual pixels. Then use `Surface.map_rgb` to get the integer that represents the colors to change or blend, apply the math, and throw it back into the `PixelArray`. Remember to delete the `PixelArray` when done, or else you can't blit your image.

There, now I don't have to rely on the PIL for one function.
> 1 votes

---
Tags: mathematics, python, pygame, blending, color
---


# Question
Title: What is an easy way to work subsurface scattering into a raycaster?
I've got some neat effects with path tracing:

I want to add in an ability to do subsurface scattering, but I'm unsure of the general algorithm. With path tracing, it's:

```
foreach pixel:
    trace( ray into scene )
        color = 0
        if( ray hits an object )
            if( that object is emissive )
                color += object.emissive_color
            if( that object is translucent )
                color += trace( object.refracted ray into scene )
            if( that object is specular )
                color += trace( object.specularly-reflected ray into scene )
            if( that object is diffuse )
                color += trace( object.random-direction reflection ray into scene )

        return color

```

That's the rough outline. Where does subsurface scattering go and how can I integrate it?

# Answer
> 3 votes
A common approach to subsurface scattering in offline rendering is the so-called "dipole approximation", which is described in the paper A Practical Model for Subsurface Light Transport by Henrik Wann Jensen and others. Unfortunately, I can't do much more than point you at the paper, as I haven't studied it enough to understand it in detail. Googling for "dipole subsurface scattering" will also find you a few more links.

Jensen also has a page with some more images and links to other papers on the subject here.

Finally, it's also possible to simulate subsurface scattering with a brute force Monte Carlo approach, using either path tracing or photon mapping, as long as your renderer supports volumetrics. You pretty much just make a volume that has an extremely high scattering coefficient (orders of magnitude more than you'd use for smoke/haze/etc.) This is very slow though, even by Monte Carlo standards.

---
Tags: raycasting, raytracing
---


# Question
Title: How is AI most commonly implemented in popular games?
I'm no gamedev, I'm just a curious coder of not-games. I wonder, how does AI work in popular modern games, say, FPSs? Is it based on hard-coded rules? How much does it have in common with other kinds of AI (like the one which powers autonomous cars etc)? How do developers ensure the AI behaves naturally and is fun to play against?

Stuff I've googled mentioned different derivatives of MinMax but failed to answer how AI deals with continuous, changeable world, for what actions/states AI is rewarded and how it figures out its chance for success of different actions. I've also seen Machine Learning mentioned here and there but it seems it's not used in any serious game?

# Answer
> 16 votes
There are many methods. I will answer for FPSes because each genre has its own set of problems, and AI approaches are heavily dependent on the problem domain and how best to represent it.

Common FPS approaches include:

And various permutations and variations on the above.

Minimax is not generally used for games with continuous state like FPSs, more for turn-based games in discrete game spaces like Chess etc. It can be used for planning at a high level, but generally it is not because there are better systems (ie. the above) when faced with multiple enemies, incomplete information, but simple plans.

They ensure the AI is fun by playtesting. If it's too challenging, they may introduce error into any decision heuristics, or a delay on their reactions, or apply a random factor to their aiming, etc. If it's not challenging enough, they will just need to improve the data supplied to the algorithm.

# Answer
> 5 votes
There are papers out there on how various AIs work, the one I'm most familiar with is F.E.A.R

# Answer
> 2 votes
Two more common methods

UCT search. There is a formalism, but the idea is basically to do a random playout until the game ends, with feedback to weight the winning games more heavily than losing ones. The nice thing about the pure form of this is that the AI needs no knowledge about what might be a better or worse move.

Minmax search, usually combined with alpha-beta tree pruning, basically does a complete search of the game space to some depth, evaluating every terminal node with a static evaluator which assigns a numerical value. This works well for games where there are obvious metrics that measure progress toward a win.

---
Tags: ai
---


title: Timer to control the object in XNA

text:
# Question
Title: Timer to control the object in XNA
I thought this was a great concept; a method that is activated from the constructor when the object is created and in the method, see code below, after 3 seconds call another object to remove it from a list, but unfortunately this isn't working the way I want! There seems to be some problems with the timer, because the call to remove the object is done immediately without any delay! Have I missed something or isn't this possible? Perhaps in another way?

```
public void ExplosionTimer(GameTime gameTime)
    {
        seconds += (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (seconds > 3)
            objectManager.ExplosionControl();
    }

```

# Answer
What does the method activated from the constructor do? Allow the gameobject to be explodable? Are you setting seconds = 0 in the constructor? What does objectManager.ExplosionControl() do? Loop over all objects and find the ones with seconds \> 3? If so, why don't you just pass the object itself and ask it to be removed from the list?

```
objectManager.removeExplodedObject( this ); // for example

```

What you are describing should work. Are you calling ExplosionTimer on each update?
> 1 votes

# Answer
Not exactly an answer to you problem but simply an alternative to your timer logic. You could also define a field that stores the time in the future when you want to trigger your behaviour.

The following example will cause damage & trigger a particle effect every half second regardles if this method is called more often than that period.

```
  private double _particleTimeSpan;

  public override void OnHurt(Vector2 location, float amount, DamageTypeEnum type, Actor cause, GameTime gameTime)
  {
    if (_particleTimeSpan < gameTime.ElapsedGameTime.TotalSeconds)
    {
        _hurtParticle.Trigger(location);
         Health -= amount;
        _particleTimeSpan = gameTime.ElapsedGameTime.TotalSeconds + 0.5;
    }
  }

```
> 1 votes

---
Tags: xna
---


# Question
Title: 2D Quads : Translation with OpenGL ES 2.0 on Android
I have a simple 2D engine that renders 2D textured quads, and right now I can scale the quad or rotate it, but when I try to translate it I have a strange distortion (the quad is squashed in the half left part of the screen with an infinite perspective effect), here's the code :

```
private final float quad_vertex[] = {
-0.5f, 0.5f, 0.0f,   // top left
-0.5f, -0.5f, 0.0f,  // bottom left
0.5f, -0.5f, 0.0f,   // bottom right
0.5f,  0.5f, 0.0f    // top right
};

final float left = -width/2.0f;
final float right = width/2.0f;
final float bottom = -height/2.0f;
final float top = height/2.0f;
final float near = 0.1f;
final float far = 200.0f;

Matrix.orthoM(projection_matrix, 0, left, right, top, bottom, near, far);
Matrix.setLookAtM(view_matrix, 0, 0, 0, 1.0f, 0.0f, 0f, 0f, 0f, 1.0f, 0.0f);

```

...

```
Matrix.setIdentityM(model_matrix, 0);

Matrix.scaleM(model_matrix, 0, scale_width, scale_height, 1.0f);
Matrix.translateM(model_matrix, 0, x, 0, 0);
//Matrix.rotateM(model_matrix, 0, x, 1, 0, 0);
x = x + 1.0f;

Matrix.multiplyMM(viewprojection_matrix, 0, projection_matrix, 0, view_matrix, 0);
Matrix.multiplyMM(modelviewprojection_matrix, 0, viewprojection_matrix, 0, model_matrix, 0);

```

So, any idea what is the problem ? Thanks in advance :)

# Answer
You should translate before you scale. If you scale first, you'll effectively scale your translation.
> 2 votes

---
Tags: 2d, android, opengl-es, matrix
---


# Question
Title: Finding a suitable axis-angle to avoid gimbal lock
In OpenGL the camera faces the -z axis with the +y axis pointing up. I am using quaternions to represent the orientation of my objects (which works well) and am trying to do the same for the camera. I want the camera's initial orientation rotation to face the +x axis with the up vector being +z. I was attempting to initialize the camera's quaternion rotation by multiplying two 90 degree rotation quaternions in an effort to achieve this, but I believe I am experiencing gimbal lock because I cannot orient the camera properly (the first rotation works fine, the second one produces undesired results). I haven't been able to wrap my head around an axis-angle representation that will orient the camera the way I want.

In summary:

I'm searching for an axis angle (or anything that can be converted to a quaternion really) that will provide the following rotation:

inital camera orientation: facing -z axis, +y pointing up

desired orientation: facing +x axis, +z pointing up

Note: I am already aware of gluLookAt, this problem was my attempt at understanding more about how everything works.

# Answer
The orientation you are looking for is:

```
Rotation Axis : 0.577, -0.577, -0.577
Rotation Angle: 2.094 radians or 120.0 degrees

```

The quaternion that represents that orientation is:

```
q: 0.500, -0.500, -0.500, 0.500

```

where the first 3 terms are the imaginary part (the rotation axis) and the last term commonly known as w, the encoded rotation angle.

Following is the code I used to calculate the orienation. If you don't have a linear algebra library yet, this is the point where you either want to roll your own or to download one. glm for instance.

Now back to the calculation. The first orientation frame you describe is basically the identity matrix for the opengl camera (facing -z axis, +y pointing up). The second orientation frame is our target orientation: facing +x axis, +z pointing up. Calculating the matrix from those 2 parameters is pretty straight forward, the following function is an example how to do it:

```
void gm33GetOrientationMatrix(
        matrix33 result,
        vector3 const dir,
        vector3 const up )
{
    gv3CopyNegated( result[2], dir );
    gv3CrossProduct( result[0], up, result[2] );
    gv3Normalize( result[0] );
    gv3CrossProduct( result[1], result[2], result[0] );
}

```

Once we have this matrix, its pretty simple to calculate a quaternion from it, here you can find the code for the matrix-quaternion conversion.

And voila, that's it, we have the quaternion. As an example, here is the full code I used to calculate it:

```
// calculate our target rotation matrix
vector3 target_dir = { 1.0f, 0.0f, 0.0f };
vector3 target_up = { 0.0f, 0.0f, 1.0f };
matrix33 target;
gm33GetOrientationMatrix( target, target_dir, target_up );

// convert it to a quaternion
quaternion rot;
gqFromM33( rot, target );

```
> 2 votes

---
Tags: opengl, camera, matrix, rotation, quaternion
---


title: Electricity and Magnetism: Relevant?

text:
# Question
Title: Electricity and Magnetism: Relevant?
The computer science major at my university requires that I take a sequence in either biology, chemistry, and physics, plus an additional natural science course (which I might fill with meteorology). Since I'm into game development, physics is the obvious choice. That, and I go to a big pre-med school; why damage my GPA being weeded out from a path I never wanted to take?

There are two main versions of the physics sequence, both covering the same material; one in three semesters, one in two, which I'm interested in. The course descriptions (the best info I can get right now) follow;

> **PHY 131: Classical Physics I**
>
> First part of a two-semester physics sequence for physical-sciences or engineering majors who have a strong mathematics background and are ready for a fast learning pace. It covers mechanics, wave motion, kinetic theory, and thermodynamics. Calculus is used concurrently with its development in MAT 131. Three lecture hours and one recitation hour per week. The Laboratory component, PHY 133 (Lab 1), could be taken concurrently.

Since that's motion, waves, etc. it's obviously extremely useful, and therefore worthy of my attention. No question there. I'm going to take this in Spring of '13.

> **PHY 132: Classical Physics II**
>
> Second part of a two-semester physics sequence for physical-sciences or engineering majors who have a strong mathematics background and are ready for a fast learning pace. It covers electromagnetism, electric circuit theory, and optics. Calculus is used concurrently with its development in MAT 132. Three lecture hours and one recitation hour per week. The Laboratory component, PHY 134, may be taken concurrently.

(For reference, the descriptions for the three-semester versions are at this link, because they're a bit more descriptive.)

What I want to know is this; besides the obvious things like possible game design elements, does the material in PHY 132 play any significant role in game physics or similar? If so, what are some examples?

I ask because if I can skimp on the material, I might take a PHY 132 equivalent online next summer at some community college. That way I can ease the pressure on myself and free up a slot for something interesting.

At the very least, I might take a PHY 126 (part 2/3) equivalent online so I can take the more relaxed PHY 127 (part 3/3) that fall. But I'd prefer the former option.

Any tips?

# Answer
> 2 votes
If you're specifically interested in graphics/rendering, having some E&M and optics wouldn't be a bad thing. You won't use it *directly*, but just having that background knowledge could be helpful for a rendering programmer to understand and contextualize rendering theory and algorithms. After all, graphics is the simulation of light, which is an EM wave - even though we don't simulate it down to that level of detail.

More generally, I think that some physics background is helpful for programming / game development in general because of skills it teaches that are applicable beyond physics: dimensional analysis, making quick order-of-magnitude estimates of quantities, analyzing extreme cases (e.g. what happens when some quantity is very small or very large), guessing which effects in a complicated system are worth modeling and which are subtle enough to be ignored. And of course it'll give you a lot of math practice, including vector math (E&M particularly uses vectors a lot), which you'll use all over the place in game development.

---
Tags: mathematics, physics
---


title: Procedural terrain using 3D noise

text:
# Question
Title: Procedural terrain using 3D noise
I'm coding a procedural terrain generation based on this article from GPU Gems 3.

But using CPU (not GPU). I'm stuck at generating the procedural terrain. I just can't figure out how make a 3D texture the way it looks in the article (fig. 1-10). Am I missing something big here? Here is the code:

```
float CTerrain::DensityFunction(float x, float y, float z) {
    CPerlin3DTexture perl_tex;
    float noise;
    uint32_t octaves = 3;
    float amplitude[10] = {0.25,0.5,1.0,1.9,4.1,8.1,16.1,9,10};
    float lacunarity = 1.5;
    float freq[10] = {4.03,1.96,1.01,0.51,0.2487,0.12563,0.8013,0.39913, 0, 0};
    uint32_t i;

noise = 0.0;
    for(i=0; i < octaves; ++i ) {
        noise += perl_tex.noise(x * freq[i],
                                y * freq[i],
                                z * freq[i]) * amplitude[i];
        x *= lacunarity;
        y *= lacunarity;
        z *= lacunarity;
    }

    return noise;
}

```

Values (nx,ny,nz) = (128,128,10)

```
float ***CTerrain::GenerateDensityTexture(uint32_t nx, uint32_t ny, uint32_t nz) {
float step[3];
int32_t i, j, k;

step[0] = 1.0 / (float)nx;
step[1] = 1.0 / (float)ny;
step[2] = 1.0 / (float)nz;
for(i = 1; i < nx-1; i++) {
    for(j = 1; j < ny-1; j++) {
        for(k = 1; k < nz-1; k++) {
            tex[i][j][k] = DensityFunction((float)i * step[0],
                                           (float)j * step[1],
                                           (float)k * step[2]);
        }
    }
 }

return tex;
}

```

Help, anybody? This is what I get from the above code:

# Answer
> 5 votes
In the article, the base density function is `float density = -ws.y;` This means that at high altitudes, the density will definitely `>= 0` producing completely air, and at low altitudes `density < 1` producing solid land.

From your screenshot, it looks like you just generated a solid block of uniformly 50% dense terrain instead of the gradient the article used.

---
Tags: opengl, perlin-noise
---