title: Fire simulation using java and opengl

text:
# Question
Title: Fire simulation using java and opengl
i'm newly working with opengl. I'm trying to create a simple program that will simulate fire. My question is what are the ways other than particle effects to simulate fire. And can fire simulation really be done without particle system effect??

# Answer
You could try something like the method described here . Basically, you generate random heat sources (random pixels in a texture for instance), then iterate over the whole texture and compute each pixel as a function taking the nearby ones as arguments.

Let c0 be the color of the current pixel, c1 is at its left, c2 at is right, and c3 and c4 the two at its bottom; c0 color (value) is the result of (c1+c2+c3+c4)/4. Do this for every pixel at every frame, and voilà, you got a (somewhat basic) 2D fire. Feel free to distort the source image to add realism.

Note that the very same technic is usable on 3D as well.
> 2 votes

---
Tags: opengl, java
---


# Question
Title: Some help understanding and modifying a 2D shader
I have a similar question as the one posed here, except that I don't wish to use a 1D Color Palette.

I simply wish to have it display 1 color of my choosing (red, for example). I plan to use this as a "shield" effect for a 2D ship.

I also wish to understand how it works a little bit better, as I'll be the first to admit that shaders in general are not my strongest suit. I'm not asking for an overview of HLSL (as that is too broad of a subject), just an explanation of how this shader works, and the best way to implement it in a 2D game.

Code examples would be ideal (even if they are theoretical) but if the answer is explained well enough, I might be able to manage with plain old text.

This is also in XNA 4.0.

Thanks in advance.

# Answer
**Diatribe:** You should be trying to figure this out yourself - I was myself in the exact same position as you a year ago; and now I am doing soft-edged water etc. *without copying code* because I figured it out myself. I will try to explain the thought process you should be using - but you won't get one complete snippet. Furthermore, he uses a `Texture1D` \- which we don't have in XNA; so my answer will vary slightly.

To start you should first search on how to use `Effect`s, and how to use custom ones with a `SpriteBatch` (if that is what you are using).

Firstly, if you look at the video you will notice that the waves are moving outwards from the center - in order for a shader to perform any form of animation over time you need to provide it with knowledge of time. Therefore provide it as a uniform parameter (this means that it will retain its value over an entire frame):

```
uniform float time; // Set this to the current total elapsed game time each frame.

```

Now we would like it to move outwards from the center; that means we need to define 'center':

```
uniform float2 center; // The center of the ship in local texture coordinates (most probably 0.5f, 0.5f)

```

Note that this center is *local to the texture* \- in other words don't pass the coordinate in in terms of screen space. Also, remember that you perform Texture lookups on the GPU using 0 -\> 1 (not 0 -\> `size of texture in pixels`). In most cases you could probably just set center to `0.5f, 0.5f`.

Finally we need to access the texture - to read colors from a texture you use a sampler - this will contain the graphic for the ship.

```
sampler BaseTexture : register(s0); // According to how sprite batch works.

```

And one for the shield - which we will repeat over the entire area of the ship (you will need to see this).

```
sampler ShieldTexture : register(s1);

```

A pixel shader automatically 'loops' over every pixel (it's not actually what happens, but you can see it this way), so we will get some information from the GPU.

```
float4 ShieldPixelShader(float2 inTex : TEXCOORD0) : COLOR
{
   /* ... */
}

```

What this means is that we have a function that takes the current texture coordinate and returns the resulting color. The GPU will fill in the value of inTex for you (because of the TEXCOORD0 semantic).

The first thing we need to do is figure out how far the current pixel is from the center of the ship:

```
float dist = length(inTex - center);

```

Now we need to figure out how opaque to make the second texture based on that distance and the time. The distance will be in the range 0-\>1 (because of how texture coordinates work); and we want the 'bright spot' to move from 0-\>1, reset and repeat - this sounds mightily like a modular problem. The `%` returns the remainder of division - and it conveniently restricts a value to a range (in a repeating fashion) - so for example `i % 5` will do this:

> 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, ...

What's also great is that it also works on real numbers (things like 0.5) - so if we just take `time % 1` it will get us our repeating expanding circle:

```
float targetDist = time % 1;

```

Now all we do is figure out how close we are to targetDist, so we can see how opaque we want to make the second texture:

```
float distDiff = 1 - min(0, abs(targetDist - dist) - 0.5);

```

That subtraction and `min` is so that we can contract the size of the gradient (remember it occurs in a small space around the current desired distance, not all the way from `0.5, 0.5`).

Now we can finally get to the bit where we mix the two textures, remember that I said we are going to repeat the shield texture. Another nifty the thing the GPU can do for us is wrap textures, that is, if you ask for a pixel at 1.1 it will actually grab it from 0.1 (if you think about it you will see that they are also just using `%`/mod for this). So in order to repeat a texture we can just multiply it by the number of times we want it repeated:

```
float2 shieldCoord = inTex * 20; // Repeat it 20 times.

```

Finally we grab the colors for each texture:

```
float4 shipColor = tex2D(BaseTexture, inTex);
float4 shieldColor = tex2D(ShieldTexture, shieldCoord);

```

Finally we perform the simplistic alpha mix:

```
float4 finalColor = (shipColor * (1 - distDiff)) + (shieldColor * distDiff);
finalColor.a = shipColor.a; // Use the ships alpha (transparency).

```

And return it to the graphics card:

```
return finalColor;

```

*Side note:* You will need to turn off premultiplied alpha blending for this shader to work - search around to find out how to do this.
> 4 votes

---
Tags: xna, 2d, xna-4.0, shaders, hlsl
---


# Question
Title: Moving a big set of box2d bodies in an iOS endless side-scroller game (such as Canabalt)
I am working on an iOS endless-running game (Robot Unicorn, Canabalt, etc). I'm using box2d for the Physics and Collision Checking and cocos2d for graphics.

To achieve the notion of an endless level, I instantiate "boards" which encapsulate a set of box2d bodies (floors, enemies, etc). I place two of these "boards" alongside and I check for their current position every frame. When they leave the visible area of the iPhone screen, I move the board and it's set of bodies to a new position, further ahead.

To do this I use the SetTransform() method of the b2Body class.

I also put all my bodies to sleep before doing this.

My issue is that every time I perform this task, the FPS has a noticeable drop.

I ran the Profiler and it seems the problem is within the SetTransform(). Apparently, box2d is removing and inserting leafs in the dynamic tree.

I am moving around 50 bodies in one frame.

My question to you guys is if anyone knows of a more convenient way to translate bodies without it taking a toll in performance. Perhaps it's cheaper to create new bodies, instead of moving the existing ones? Am I missing some kind of flag I should activate before calling SetTransform()?

Thanks in advance!

# Answer
In a more general point of view (ie. not talking about box2d), you could double the amount of objects present in the scene (if you want to display one enemy, you should actually have two of them instantiated). Once the first got out of the screen, enable the second one (which will then enter the screen), and recreate the first one (hidden, then) in the background. That way, although theoretically slower in average, permits to keep a constant framerate.
> 2 votes

---
Tags: box2d, ios, performance, platformer, side-scroller
---


# Question
Title: How do I implement a quaternion based camera?
**UPDATE** The error here was a pretty simple one. I have missed a radian to degrees conversion. No need to read the whole thing if you have some other problem.

I looked at several tutorials about this and when I thought I understood I tried to implement a quaternion based camera. The problem is it doesn't work correctly, after rotating for approx. 10 degrees it jumps back to -10 degrees. I have no idea what's wrong. I'm using openTK and it already has a quaternion class. I'm a noob at opengl, I'm doing this just for fun, and don't really understand quaternions, so probably I'm doing something stupid here. Here is some code: (Actually almost all the code except the methods that load and draw a vbo (it is taken from an OpenTK sample that demonstrates vbo-s))

I load a cube into a vbo and initialize the quaternion for the camera

```
protected override void OnLoad(EventArgs e) {
    base.OnLoad(e);

    cameraPos = new Vector3(0, 0, 7);
    cameraRot = Quaternion.FromAxisAngle(new Vector3(0,0,-1), 0);

    GL.ClearColor(System.Drawing.Color.MidnightBlue);
    GL.Enable(EnableCap.DepthTest);

    vbo = LoadVBO(CubeVertices, CubeElements);
}

```

I load a perspective projection here. This is loaded at the beginning and every time I resize the window.

```
protected override void OnResize(EventArgs e) {
    base.OnResize(e);

    GL.Viewport(0, 0, Width, Height);

    float aspect_ratio = Width / (float)Height;

    Matrix4 perpective = Matrix4.CreatePerspectiveFieldOfView(MathHelper.PiOver4, aspect_ratio, 1, 64);
    GL.MatrixMode(MatrixMode.Projection);
    GL.LoadMatrix(ref perpective);
}

```

Here I get the last rotation value and create a new quaternion that represents only the last rotation and multiply it with the camera quaternion. After this I transform this into axis-angle so that opengl can use it. (This is how I understood it from several online quaternion tutorials)

```
protected override void OnRenderFrame(FrameEventArgs e) {
    base.OnRenderFrame(e);

    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

    double speed = 1;
    double rx = 0, ry = 0;

    if (Keyboard[Key.A]) {
        ry = -speed * e.Time;
    }

    if (Keyboard[Key.D]) {
        ry = +speed * e.Time;
    }

    if (Keyboard[Key.W]) {
        rx = +speed * e.Time;
    }

    if (Keyboard[Key.S]) {
        rx = -speed * e.Time;
    }

    Quaternion tmpQuat = Quaternion.FromAxisAngle(new Vector3(0,1,0), (float)ry);
    cameraRot = tmpQuat * cameraRot;
    cameraRot.Normalize();

    GL.MatrixMode(MatrixMode.Modelview);
    GL.LoadIdentity();

    Vector3 axis;
    float angle;

    cameraRot.ToAxisAngle(out axis, out angle);
    //////////////////////////////////////////////////////////////////////
    // THIS IS WHAT I DID WRONG: I NEED TO CONVERT FROM RADIANS TO DEGREES
    //////////////////////////////////////////////////////////////////////
    //BEFORE
    //GL.Rotate(angle, axis);
    //AFTER
    GL.Rotate(angle * (float)180.0/(float)Math.PI, axis);
    GL.Translate(-cameraPos);

    Draw(vbo);
    SwapBuffers();
}

```

Here are 2 images to explain better: I rotate a while and from this:

it jumps into this

Any help is appreciated.

**Update1**: I add these to a streamwriter that writes into a file:

```
    sw.WriteLine("camerarot: X:{0} Y:{1} Z:{2} W:{3} L:{4}", cameraRot.X, cameraRot.Y, cameraRot.Z, cameraRot.W, cameraRot.Length);
    sw.WriteLine("ry: {0}", ry);

```

The log is available here: http://www.pasteall.org/26133/text. At line 770 the cube jumps from right to left, when camerarot.Y changes signs. I don't know if this is normal.

**Update2** Here is the complete project.

# Answer
While you haven't shown the necessary code to verify my assumption here, I can almost guarantee that your problem is actually that this line:

```
cameraRot.ToAxisAngle(out axis, out angle);

```

is returning an *angle* value expressed in **radians**, while

```
GL.Rotate(angle, axis);

```

wants *angle* to be provided in **degrees**.

To fix it, you need to convert the *angle* value when passing it to GL.Rotate(), like this:

```
GL.Rotate(angle * 180.0/3.141593, axis);

```
> 9 votes

# Answer
Don't. It may seem that it would be less work to have a camera that can be manipulated like other scene objects, but in the long run it is better to have a camera where you can define a position, eye direction and up vector. Especially when you start programming motion models it is really a pain to work with quaternions.
> 1 votes

# Answer
Don't know much about OpenTK internals. In my experience I did not see math library with proper implementation of quat that keeps needed precision (machine), because all of them affects e^2-e^3 errors. So the effect you see: the precision (and epsilon value) is about 10^-5, and it 'jumps' near zero. This is my guess :)
> 0 votes

---
Tags: opengl, c#, camera, quaternion, opentk
---


# Question
Title: What languages are required for an mmo browser game?
What 'Things' are required for this sort of game? I understand java, c++, javascript, and objective c (iphone programming) fairly well, however I know nothing about networking programming, but I do know about networking in general (packets, mac addresses all that good stuff)

So this is my main question: for a game like Tribal wars, Evony, Shadowland online, travian, what programming languages do I need to know to take this on and finish it by myself? I'd imagine that most of it will be done in java, but for the whole connecting other players, combat, leader boards and (most importantly) making online payments for things, what languages should I learn for developing something like this?

# Answer
> 4 votes
I've been considering the same thing but for a Scorched Earth/Gunbound style game.

To make the kind of game you are talking about there are going to be two parts:

1. The client side (player's browser)
2. The server side (your game's server). This encompasses:
    1. The language used on the server
    2. The database used to store data

## Short Answer

For the client side your two options are pretty much (in no particular order):

1. Javascript + HTML
2. Actionscript (Flash)

For server side languages (again, no specific order):

1. Javascript via node.js (see Bane's answer)
2. PHP (see Lohoris's answer)
3. Java (sorry don't really have a link, but you mentioned you are familiar with it)
4. Ruby
5. Python

For databases (no specific order):

1. MySQL
2. Postgresql
3. MongoDB (this is a NoSQL database)

## Long Answer

The server side can be pretty much whatever the heck you want it to be. You'll likely want support for sockets which PHP and node.js support, making them viable options. Your question mentioned you are familiar with Java and that's a viable option as well. If you're comfortable with Java (and not doing this to learn new languages/technologies) that's may be your best bet.

As far as databases go MySQL and Postgresql are widely supported and established databases. Something like MongoDB is a bit more exotic and may not be supported by your server side language of choice. Me, I'd probably use Postgresql unless I was interested in mucking around with NoSQL or thought it gave some clear, tangible benefit.

On the client side, game interactivity is going to require either Javascript or Actionscript (i.e., Flash). None of the games you called out look like Flash games to me or, if they are, they appear like they could be made without Flash so I'd recommend you stick with Javascript here.

As for integrating with payment gateways and other third party solutions you'll want to checkout things like PayPal and see what they support. Typically they support a few different languages (PHP and some flavor of Microsoft are usually safe bets) and have code samples in all supported languages. The Facebook API is friendly with PHP and Javascript.

---

## Other Considerations

### Does Your Game Need To Use Sockets?

Both Flash and Javascript\** support socket connections. Flash does this via the Socket class and supports sending and receiving binary data. As mentioned by Bane there is a node.js Javascript implementation of sockets via socket.io. However, binary sockets are not supported and browser support can be iffy (though socket.io compensates for this).

To me this then becomes one of two questions:

1. Which technology do I want/need to use server side? Or,
2. Which technology do I want/need to use client side?

In my case I wanted to use Javascript on the client and node.js + socket.io seems to be the best (possibly only, certainly easiest) technology that would enable socket connections to the server. So I'm using Javascript + HTML in the browser and node.js on the server. Another benefit is that I'm using the same language on both the client and the server which is nice.

If I needed binary sockets or wanted to use Java on the server I'd probably choose Flash on the client side. There are a lot of socket servers written in Java for the express purpose of supporting multiplayer Flash games (SmartFox is one example).

\** Via WebSockets in most modern browsers.

### Can You Get By With Remote Procedure Calls Instead of Sockets?

If you can use RPC (think AJAX) then you're really free to do things however you see fit. Just about any browser (even the shambling corpse that is IE6) supports AJAX calls, as does Flash. Likewise any server technology is going to be able to respond this these requests. If your design allows for this it really becomes a matter of which technologies you prefer.

### What Languages Are Supported By Third Party Solutions

If you'll be integrating with third parties you should check out what technologies they support. While there is no reason you cannot run the game server in Java and integrate with your payment gateway in PHP but it would probably be easier to just have it all be in one or the other.

# Answer
> 5 votes
You can do it all in JavaScript. For server side, use node.js. That's basically a JS interpreter outside of the browser, so you can run it just like you run Python or other great scripting languages. Not just that, it gives you support for many networking features, mainly you'll be serving the actual content with it. For communication you'll want to use socket.io. These two have great communities that are always being helpful and basically are the future of web-development. It also helps to code both the client and the server side in the same language.

I'm building a browser MMO as well. Here's my dev blog, I describe various problem that you might encounter.

# Answer
> 2 votes
PHP+MYSQL+HTML is enough for a start. JavaScript if you want to do AJAX stuff (you want to).

Java is completely unrelated, as is networking, since HTTP will handle this sort of things.

---
Tags: mmo, browser-based-games
---


title: How can I improve this architecture?

text:
# Question
Title: How can I improve this architecture?
In a roguelike I'm developing in Ruby, I started with a traditional object hierarchy where all game logic relevant to creatures were contained in the `Creature` class. Movement logic, for example:

```
Creature.instance_methods(false)    # => [ :move ]

```

In my design, the map and creatures are decoupled: the map has no idea what's on a tile and the creature has no idea which kind of tile it is on. What brings them together are coordinates.

Movement logic requires information about where on the map the creature is, so the creature would need access to the map. The map belonged to the game, so I just added a game attribute to every creature as a quick solution. I didn't really want to pass a map instance every time the creature needed to move around because the map the creature is on isn't likely to change.

In the end, I removed the game logic from the `Creature` class, and separated them into modules:

```
Game::Logic::Movement.singleton_methods(false)    # => [ :move ]

```

The way I understand it, these logic modules integrate multiple game parts which depend on each other in a way not easily expressed hierarchically. The methods are just algorithms that operate on the given information. For example, the implementation of the `move` method:

```
def self.move(creature, map, dx, dy)
  coordinates = Map::Coordinates[dx + creature.x, dy + creature.y]
  tile = map[coordinates]
  creature.coordinates = coordinates if tile and tile.passable? # Teleport!
end

```

These methods are called directly from the game loop:

```
def handle(input)
  case input
    when :up then Logic::Movement.move character, map, 0, 1
    # ...
  end
end

```

This is how the game is currently organized. Movement is the only game logic I've added as of now, so I think it would be wise if I revised the architecture while it is still small. So, what do you think of it? What are the problems, and what can I do to improve it?

I'm also interested in how it compares to component-based game architecture. I've read a lot about it during my research, and it seems to be the most maintainable and reusable way to write game code. I think it would fit naturally in the Ruby world, due to its dynamic nature and message-based method invocation. The thing is, I really never understood how different components interact with each other, and I'm looking for something I can make sense of.

# Answer
One thing to note is that if you are going to have a lot of creatures/monsters, you should probably make them flyweights. You would have a Creature class with individual-specific information like current hit points, and a CreatureType class with information that is common to all instances of that particular type of creature (things like max hit points). All creatures of a particular type contain a reference to a single, shared CreatureType object. You will only have a few instances of CreatureType in your entire game (one for each type of creature), so the more information you can place in that object as opposed to hundreds or thousands of Creature objects, the better your memory savings will be.

In my game I also place the movement logic in the CreatureType class, since all creatures of a particular type use the same movement AI.
> 3 votes

# Answer
There's not really much to speak of yet. You could shift the logic around as much as you like but that movement function would still look pretty much identical. It's too early to judge whether this is going to work for you or not. You need to come up with a few more use cases, specifically complex stuff, and see how it fits into the system. You'll quickly see where the problems lie.

> I'm also interested in how it compares to component-based game architecture. I've read a lot about it during my research, and it seems to be the most maintainable and reusable way to write game code

Reusable? Sure. Maintainable? Nope. I think components make games harder to maintain because the number of possible interactions between components grows exponentially as you add new ones. They have pros and cons.
> 1 votes

---
Tags: architecture, design-patterns, ruby
---


title: 3D Location Handling

text:
# Question
Title: 3D Location Handling
I am thinking about making a simulator type game that will involve having lots of small objects in a 3D space. What is the typical solution for handling these objects? The first thing that comes to mind is a 3D Array, but I can't help but think there is a more efficient solution. Another idea that comes to mind is objects having possession of smaller items. For example a House possesses a Table which possesses a Cup and Bowl.

The final way I can think of handling this is just having an array of "objects" that each have an x, y, z value. While this would make storing them easy I do not understand how you would detect collisions without just looking at every possible object and checking to see if it is in the way.

Are there other ways of holding onto these objects that is more efficient?

**Edit:** Following up with the comments below, are there typical thread-safe ways of implementing these structures in Java?

# Answer
> 2 votes
You could use a scene graph, or just a list of objects with some sort of spatial hash to speed up collision checks.

But even just sorting objects by one of the coordinates and using that knowledge to limit the comparisons is a good enough optimisation for most simple applications, and your application fits the bill. Imagine you took the solar system and flattened it down onto 1 dimension - how many objects would overlap? Hardly any (except perhaps a few asteroids). That would mean that for each object, you only need to check a couple of other adjacent objects to see if a collision has happened.

As for thread-safety, what 'safe' means depends on what you're trying to achieve. The term "thread-safe" refers more to algorithms than to data structures. (A data structure may be thread-safe, but that doesn't mean your use of the data is correct with regards to multiple threads.)

---
Tags: 3d, architecture, java, software-engineering
---


title: SpriteSheet Animation with XNA

text:
# Question
Title: SpriteSheet Animation with XNA
Hi i'm working on my First 2D Game with XNA and I have a little problem. To give a *running* effect to my Sprite, I scroll through a *SpriteSheet* with this code(running right):

```
if (AnimationDelay == 6)
{
    if (CurrentFrameR.X < SheetSizeR.X)
    {
        ++CurrentFrameR.X;
    }
    else
    {
        CurrentFrameR.Y++;
        CurrentFrameR.X = 1;
    }

    if (CurrentFrameR.Y >= SheetSizeR.Y)
    {
        CurrentFrameR.X = 0;
        CurrentFrameR.Y = 0;
    }

    AnimationDelay = 0;
}
else
{
    AnimationDelay += 1;
}

xPosition += xDeplacement;

```

And these are the objects used :

```
Point FrameSizeR = new Point(29, 33);
Point SheetSizeR = new Point(5, 1);
Point CurrentFrameR = new Point(0, 0);
int AnimationDelay = 0;

```

I have the same Code with different *SpriteSheet* when the sprite is running Left. Everything is working fine I'd say 90% of the time but the other 10% the sprite animation stays on one Frame of the *SpriteSheet*, on both directions(left and right) and it stays stuck until I close the program. The thing is I can't quite figure out why since it never happens at the same moment..Sometimes after 10,15,30 seconds and sometimes even on boot! Any idea why? Thanks in advance and let me know if you need any other parts of the code

# Answer
> 6 votes
I bet it's because `AnimationDelay` manages to make it past 6 somehow. I'd change the if statement to:

```
if (AnimationDelay >= 6)

```

# Answer
> 3 votes
John's question will do, however you might still want to look at doing it 'correctly' in the first place.

```
// It's important we make the current frame a float; because something like 0.1f
// might be added to it at really high framerates.
// This will refer to each frame as if the tileset was actually a single lines of frames.
// (Even though they are not)
private float CurrentFrame;

********** In your update/draw method. **********

// Animate your sprite at 15 FPS.
CurrentFrame += gameTime.ElapsedGameTime.TotalSeconds * 15;

// Constrain CurrentFrame to the number of frames available.
// (This replaces your if; frame = 0; etc.)
CurrentFrame %= SheetSizeR.X * SheetSizeR.Y;

// Find out the X and Y position of the current cell we want, from
// CurrentFrame. You must use integral division here - as it has a
// few properties that makes mapping a 1D index to a 2D array more
// straight-forward.
CurrentFrameR.X = (int)CurrentFrame % (int)SheetSizeR.X;
CurrentFrameR.Y = (int)CurrentFrame / (int)SheetSizeR.Y;

```

---
Tags: xna, c#, sprites, spritesheet
---


# Question
Title: What is the preferred starting address for a C64 game?
When writing a C64 game in 6502 Assembler and loading the game using `LOAD "Game",8,1`, I can choose the address where the game is loaded to. The most popular address I saw is `$c000`, closely followed by `$0810`, but I also saw `$1000` and `$2000` used a lot.

Why would I choose one over the other? I understand `$0810` because it's close to `$0801` which you have to write the `SYS` instruction to, but the other addresses all seem arbitrary.

Can someone shed some light into this?

# Answer
> 7 votes
$0810 is good start for asm stuff. Near start of basic mem $0801 so you can put sys 2064 in $0801...

$c000 -$cfff is after basic rom area and free so basic programs "poke" asm sub routines there often...

$1000-$1fff (and $9000-9ffff) usually in asm programs contain music because that area contains shadow copy of fonts and can't be used for own charactersets, so it's ideal for music...

# Answer
> 2 votes
> The $0801-Adress is the place where normal Basic-Listings start. If you do a list after loading some programm, you normally have a SYS-Line (fex. 1989 SYS 2064) So the code at 2064 ($0810) is started.

That quote was from this thread: http://www.lemon64.com/forum/viewtopic.php?t=870&sid=a13a63a952d295ff70c67d93409bc392

So basically you load to that address, starting your code with a short BASIC instruction to jump to wherever your code actually is. (Oh, and I think the first $0801 there is a typo),

---
Tags: commodore-64
---


# Question
Title: How do I get light to go through a window texture in Unity?
I'm having trouble with the lighting (I have windows and the light wont go through). How do I get the light to proceed through the glass?

# Answer
You need to attach different materials on transparent and opaque objects. Then, if you assign a transparent shader to transparent surfaces, the light will go through. Another approach could be detaching glasses on the modeling program, create and assign some other layer for the glass parts and have the light ignore that layer.
> 1 votes

---
Tags: unity, lighting
---


# Question
Title: Are objects made out of lines still classified as meshes?
A cube or a sphere is a mesh, but are lines and circles?

I'm currently creating a renderer responsible for drawing many different types of object. functions in a namespace called MeshDescription are responsible for running and returning mesh objects so you can do things like this:

```
Mesh mesh = MeshDescription::Cube();

```

but I'm wondering if functions for lines and circles should be categorised differently? with a view to changing this soon so that everything is instanced.

# Answer
> 1 votes
A mesh will usually fall into one of the 3 following categories:

* Imported
* Procedurally generated
* Primitive

At it's core, a mesh is just a collection of vertices, edges, and faces.

If you want to import an object I would separate it's identity from it's mesh. So if you import a plane into the game, I would have some object called "GameEntity" which is a class that has a property of type mesh. The mesh is nothing more than the collection of vertices, uv coords, and other mesh specific properties.

If you want to procedurally generate a terrain, I would have an object called "Terrain" that inherits from "GameEntity". This would already have the mesh property from it's parent class. Again, you are separating what the object does from it's mesh representation.

Lastly if you have primitives, I would have stored representations of each object which would include it's mesh, but also all of it's identifying information like name etc. So this would fall under the "GameEntity" class as well.

Long story short: in your example you are defining cube as a subobject of mesh. Instead I would define everything under a master object class called "GameEntity" which can include a mesh component. Do remember if you implement this that not all "GameEntity" objects must have a mesh. Especially if you had objects like "Camera" inherit from "GameEntity"

I have "Game Engine Architecture" by Jason Gregory. It's a pretty decent overview of the components needed for a game engine. It has a whole section on the rendering engine, but knowing that there are dependencies on the objects you design for rendering is pretty important so you can extend your codebase later.

# Answer
> 1 votes
This is highly subjective; so this is clearly my opinion.

Perfect grammatical code should never be your first priority - discoverability and consistency is. Once a developer knows the 'go to' place for shapes (as a broad term) they typically won't look somewhere else; and will re-implement it.

Don't classify your objects based on their *exact* category; rather their function. You could do something like:

```
Mesh mesh = MeshDescription::TwoDimensional::Line();
Mesh mesh = MeshDescription::ThreeDimensional::Cube();

```

Which retains the common entry-point, the discoverability and the consistency.

---
Tags: graphics-programming
---


# Question
Title: How can I change this isometric engine to make it so that you could distinguish between blocks that are on different planes?
I have been working on an isometric minecraft-esque game engine for a strategy game I plan on making. As you can see, it really needs some sort of shading. It is difficult to distinguish between separate elevations when the camera is facing away from the slope because everything is the same shade. So my question is: can I shade just a specific section of a sprite? All of those blocks are just sprites, so if I shaded the entire image, it would shade the whole block. I am using LWJGL. Are there any other approaches to take?

Here is a screenshot from the engine:

# Answer
One possible solution would be drawing edges along where the terrain changes height in dark black. So, the effect generated would look like height lines.
> 3 votes

# Answer
A simple suggestion and something I recently put into my game. For all the horizontal upward faces, find if they are also the base of an adjacent horizontal face. For example, when I'm building my VBOs I run some code like this:

```
    Color[] colors = new Color[4];
    Color faceColor = GetColorForFace(x, y, z, face);
    colors[0] = faceColor; //mpp
    colors[1] = faceColor; //ppp
    colors[2] = faceColor; //mpm
    colors[3] = faceColor; //ppm
    if (face == CubeFaceDirection.YPlus) {
        if (Cube.IsSolidCube(GetCubeAt(x + 1, y + 1, z))) {
            colors[1] = colors[1].darker();
            colors[3] = colors[3].darker();
        }
        if (Cube.IsSolidCube(GetCubeAt(x - 1, y + 1, z))) {
            colors[0] = colors[0].darker();
            colors[2] = colors[2].darker();
        }
        if (Cube.IsSolidCube(GetCubeAt(x, y + 1, z + 1))) {
            colors[0] = colors[0].darker();
            colors[1] = colors[1].darker();
        }
        if (Cube.IsSolidCube(GetCubeAt(x, y + 1, z - 1))) {
            colors[2] = colors[2].darker();
            colors[3] = colors[3].darker();
        }
    }

```

Where colors\[\] are originally set to whatever the lighting makes them, then darkened if there are cubes next-to-and-above. colors\[\] represents the colors the 4 vertices that make up the two Y+ facing triangles.

The effect is something like the following. Where on the left is the original rendering style and the right is the new "shaded" style.

EDIT: After looking at my image again, I noticed I left out the corner case (literally!), so I'll add those cases to my code:

```
    if (Cube.IsSolidCube(GetCubeAt(x + 1, y + 1, z+ 1))) {
        colors[1] = colors[1].darker();
    }
    if (Cube.IsSolidCube(GetCubeAt(x + 1, y + 1, z - 1))) {
        colors[3] = colors[3].darker();
    }
    if (Cube.IsSolidCube(GetCubeAt(x - 1, y + 1, z + 1))) {
        colors[0] = colors[0].darker();
    }
    if (Cube.IsSolidCube(GetCubeAt(x - 1, y + 1, z - 1))) {
        colors[2] = colors[2].darker();
    }

```
> 5 votes

# Answer
You are using LWJGL which is an OpenGL wrapper, so you have 3D rendering at your disposal. Break your sprite into three quadrilaterals for the three faces of your block; you can then assign colors to light the faces of the blocks differently as well as shade across each face (by giving different colors to the corner points).

As long as you give the proper (interpolated) texture coordinates, your sprite will still look the same as it did before — there is no need to go to actually positioning in 3-dimensional space if you aren't already.
> 1 votes

---
Tags: java, lighting, lwjgl, voxels, shadows
---


# Question
Title: What's the best presentation/terminology for "quit" functionality?
I'm writing a game in XNA for Windows and Xbox, and I'm trying to decide how to present quitting options to the user. It seems to me that there are two basic types of "quits":

1. Quit the game and close it completely. On the PC, return to Windows. On the Xbox, return to the Dashboard.
2. Quit the current playthrough and return to the title screen.

Is there accepted language for these things? I've tried a few basic searches - I apologize if this has already been asked - but I couldn't find anything. The best I can come up with is this:

* Provide a **"Quit"** option on the title screen menu. This will close the game completely (see #1 above). This might not be strictly necessary on the Xbox, since players can close games using the Guide button (aka the "Xbox button").
* Provide an **"Exit to Title Screen"** option elsewhere in the game. This will quit the current game and return to the title screen (see #2 above).

I don't love the latter option, because it's a bit too verbose for my tastes, but using something shorter, e.g., just "Quit" and "Exit", doesn't seem clear enough.

It seems like the word "Quit" is the logical choice in both places, but wouldn't using the same word for two different things be inconsistent and confusing?

What are other "quit" conventions that you've seen?

# Answer
I suggest you use "Exit Game" on the main menu to mean returning to the desktop or to the dashboard. It's nice and brief, and my unscientific survey of screenshots/videos of some Xbox game title screens all seem to use it. Within the game, use one of:

* Exit to Main Menu
* Exit to Title Screen
* Return to Main Menu
* Return to Title Screen

I prefer the "exit" versions since they more strongly imply the destructive nature of the operation the user would perform. You could also just use "Exit to Title" if you prefer brevity, or just overload "exit game" and use it in-game to return the title screen. If you are worried that overloading the term might confuse users, you could provide some kind of tooltip or help prompt -- either when the option is selected or hovered over, or in a confirmation dialog, which you can bake together with the typical notice about unsaved data being lost.

For example, if the user selects "Exit Game" during gameplay, a prompt can appear reading "You are about to exit the game and return to the title screen. All unsaved data will be lost. Do you want to exit?"

The actual verb "quit" in UI is far more common on the Mac (and apparently PS3) than it is on Windows or Xbox. The latter platforms tend to prefer "exit" or some variant thereof.
> 9 votes

---
Tags: game-design
---


title: AS3 > Mouse Event not happening?

text:
# Question
Title: AS3 > Mouse Event not happening?
**Background:** Trying to make a ball appear in the same location the mouse is positioned. Using Box2D Library. Working on a class file (.as)

**Issue:** The mouse event does not work (I click but nothing happens) . No output errors whatsoever. :(

**Mouse Event:**

```
   private function _clicked(e:MouseEvent)
            {
                sim.addCircle({x:mouseX, y:mouseY, radius:0.25, density:5});
                sim.start();

```

**Full Code:**

```
package  {

    import flash.display.MovieClip;
    import com.actionsnippet.qbox.*;
    import flash.events.MouseEvent;

    [SWF(width = 350, height = 600, frameRate = 60)]

    public class MouseTest extends MovieClip {

        public var sim:QuickBox2D;

        /**
         * Constructor
         */
        public function MouseTest()
        {
            sim = new QuickBox2D(this);
            sim.createStageWalls();

            addEventListener(MouseEvent.CLICK, _clicked);
        }

        /**
         * ..
         * @param e MouseEvent.CLICK
         */
        private function _clicked(e:MouseEvent)
        {
            sim.addCircle({x:mouseX, y:mouseY, radius:0.25, density:5});
            sim.start();

        }
    }

}

```

**Download Project** (BOX2D Included)

http://gabrielmeono.com/download/BOX2D-Mouse\_Test.zip

# Answer
When you use `addEventListener` in the class it only dispatches the mouse clicks that fall on the actual visual data inside that `DisplayObject`. If you use `stage.addEventListener` you can use the whole stage.
> 2 votes

# Answer
QuickBOX2D uses meters instead of pixels. To work with pixels with this library, one must divide each number by 30. I simply added a "/30" to the mouseX and it worked! I updated my code for future reference.

```
package  {

    import flash.display.MovieClip;
    import com.actionsnippet.qbox.*;
    import flash.events.MouseEvent;

    [SWF(width = 350, height = 600, frameRate = 60)]

    public class MouseTest extends MovieClip {

        public var sim:QuickBox2D;

        /**
         * Constructor
         */
        public function MouseTest()
        {
            sim = new QuickBox2D(this);
            sim.createStageWalls();

            stage.addEventListener(MouseEvent.CLICK, _clicked);
        }

        /**
         * ..
         * @param e MouseEvent.CLICK
         */
        private function _clicked(e:MouseEvent)
        {
            sim.addCircle({x:(mouseX/30), y:(mouseY/30), radius:0.25, density:5});
            sim.start();

        }
    }

}

```
> 0 votes

---
Tags: actionscript-3, box2d, mouse
---


# Question
Title: Does VK_SNAPSHOT not send a WM_KEYDOWN; only WM_KEYUP?
On my machine, every key sends a WM\_KEYDOWN message except for `SysReq`/`Print Screen` key: which only seems to send WM\_KEYUP.

Is this actually the case?

# Answer
> 1 votes
I am getting exactly the same behaviour - I think you might need to add `WM_PRINT` and `WM_PRINTCLIENT` (`Alt` \+ `Print Screen`) as borderline cases.

However, why not just use DirectInput - which sits a lower level than the window manager?

# Answer
> 0 votes
Several of the old function keys such as Print Screen, Scroll Lock, etc., have peculiar behaviour because they have special hardware routines to send multiple scan codes rather than single ones, etc. This is presumably why the special messages like WM\_PRINTCLIENT exist, to handle the special cases.

# Answer
> 0 votes
You can receive PrintScreen via the WM\_HOTKEY message after registering it with RegisterHotKey. See this article for more information. Registering the hotkey does prevent the ordinary behavior of PrintScreen (taking a screenshot) from functioning, I believe.

But yes, you get WM\_KEYUP but no WM\_KEYDOWN (registering the hotkey gets you a WM\_HOTKEY in place of WM\_KEYDOWN). It's a bit peculiar.

---
Tags: input
---


# Question
Title: When pausing an XNA Xbox game and showing a "pause menu", which controller buttons should I use?
I'm making a simple 2D XNA game for Xbox 360. My game can be paused by pressing the `Start` button on the Xbox controller. While paused, a simple menu pops up with options like `Resume` and `Exit to Title Screen`. The way I've currently programmed it, the menu options can only be selected with the `A` button on the Xbox controller, but I've found that I intuitively want to press `Start` to resume the action again.

I think it's a given that `Start` pauses the game and displays the pause menu, but once the pause menu is displayed, I can think of 3 options for dealing with input:

* Menu options can be selected with the `A` button. `Start` does nothing.
* Menu options can be selected with the `A` button or the `Start` button.
* Menu options can be selected with the `A` button. `Start` resumes gameplay regardless of which menu option is selected.

What's the best control scheme to pause a game and accept input on a pause screen menu? Are there any guidelines or standards to help choose between these options?

# Answer
As a gamer, I appreciate it when games use the following conventions:

* I press Start to pause the game.
* Unless it has some special function (like bringing up a secondary menu), I want the B button to unpause the game.
* Same goes for Start button.
* I want to move the selection with either the left thumbstick or the D-pad, and I want the selection to wrap. ie: If I am at the top of the list and press up, then it should go to the bottom.
* 'A' button selects menu items.

Also, slightly unrelated, but when the game is paused, keep a timer and if there's no user input after 3-5 seconds or something please fade down the music and other continuously playing sound effects.

**Update**

Adding Trevor's comment in the answer because it's important:

> An extra often-forgotten point: Any current controller vibration should be stopped as soon as the pause screen is opened. The vibration should NOT be resumed when leaving the pause screen.
> 13 votes

---
Tags: game-design, xbox360, xbox-controller
---


# Question
Title: Checking Collisions In 2D Platformer With Tiles
My team and I are developing a 2D platformer with C++/SDL/OpenGL, and we already defined a collision system, but we have a problem checking collisions with the tilemap.

The tiles of the tilemap are 32x32, so we try to define that the max speed in X and Y of the player it's less than 32 because in this case we found the problem that if the speed it's bigger than the tile size, when checking the collisions the position it's updated with the speed which it's more than 32, so in that case, the position skip a tile which causes a huge problem for verification, so at the momento we limit the X and Y speed to 30, but we don't know how make the speed bigger than the tile size without losing the complete collision detection with some possible tiles that may be skiped.

Thanks a lot

# Answer
The Easiest way is to update your world twice(or more) every cycle. using this method you can increase your max speed 2 or more times.

The more Universal way to do it but is to check collision of the shape generated by the moving object, with all the tiles. something like the picture below while red box moves collision is checked for every square in map and the blue area (which is a polygon generate by convex hull algorithm):

physic engines usually have a support for such a feature, to check continues space for movement. for example in box2d there is a member (isBullet) which indicates if engine should use continues movement checking.
> 3 votes

---
Tags: opengl, c++, 2d, collision-detection
---


# Question
Title: Licence to use RPG systems like Pathfinder
I am sketching out my 2012 programming project, and Im planning to make a classic fantasy RPG game.

The world design, plots, characters and all that I can make, but being a avid tabletop role-player, I would love to use a stable and tested rpg system like Pathfinder, since its balanced and interesting.

Would there be a problem if I make a game (indie dev, but still planning on selling it) using the pathfinder license ? Do I have to purchase a license? And would I able to say that it's based on the Pathfinder ruleset, or should i keep that under wraps.

All big official D&D games boast with that they are official, so doesn't this mean that unofficial games can exist too ?

It's not because I wan't to jump the lowest fence, and all storylines and the game setting will be by my own hand. But I love the Pathfinder system and actually think it could use some publicity as well.

Was considering posting this on the rpg board, but this is a game dev issue in my eyes.

# Answer
Basically, rules aren't subject to copyright or trademark, but the names of the rules, and any non-obvious names used in the rules, are. Also, any particular lists of data in their rulebooks are copyrighted.

So, without a licence, you can use the various dice roll methods of action resolution, you can use the generic concepts like levels and stats, but you can't call it 'Pathfinder', nor can you copy their equipment or monster lists in whole or in part.

As with any legal advice, people can tell you what they understand the law to be, but that doesn't stop anybody else from attempting to sue you even if you're in the right, so err on the side of caution.
> 2 votes

# Answer
> I would love to use a stable and tested rpg system like Pathfinder, since its balanced and interesting.

And what makes you think that it would be "balanced and interesting" in a videogame? For example, NeverWinter Nights used a simplified version of D&D 3.0's ruleset, but it certainly wasn't *balanced* by most definitions of that term. There were a lot of classes and power combinations that were flat out better than others.

What works on the tabletop does not necessarily work in a videogame.

Take Charisma, for example. In D&D 3.x-based games, it's already as close to a dump-stat as it gets. It's utility is based primarily around non-combat encounters. Unlike every other stat, it has no *inherent* utility in battle. Str gives a hit and damage bonus to melee; Dex gives a bonus to AC, to-hit with ranged, and reflex saves; Con gives a bonus to HP at level-up and fortitude saves; Int gives bonuses to skill point increases; and the Wis bonus is added into your will save. Charisma has no inherent utility; everything it does is based on some class feature.

In a videogame environment, non-combat encounters have to be substantially simplified. A dialog tree is about the best you're going to be able to do. Charisma and most of the abilities around it will be of relatively limited utility compared to, for example, casting a fireball.

There's a reason why most games use different rules from tabletop games. They are meant to be played by human beings, with other human beings, and with a human being as a neutral arbitrator. Those rules do not necessarily work anymore if you take all but one of the human beings out of the equation.

You can certainly start with something *like* Pathfinder, but you should never let it limit how your gameplay can develop and evolve. Let it inspire your design, not define it. Always make sure that you are working towards an RPG system that is fun *as a videogame*.
> 4 votes

---
Tags: game-design, game-mechanics, licensing
---


# Question
Title: How to animate a character from a sprite sheet?
I'm making an online game, and I had been using a blank square as the character until recently. Now I want to add a real, animated character.

I downloaded a free sprite sheet which has 12 (3x4) character sprites.

What is the general method to animate the character?

I see why having all the character animations in one file can be useful, but I don't understand how it would be done. I don't want code or anything, I just want to know how you normally use the sprite sheet to animate a character so I code it afterwards.

# Answer
> 3 votes
The answer to **why** to use a sprite-sheet has already been answered in this question.

How you use a sprite-sheet in your game is quite simple. Usually you have a class that keeps track of the elapsed time and displays another frame once a given threshold has been reached (eg. if *1/25th* of a second has passed or similar).

How to display a new frame depends on your underlying graphics API. You might have to copy the new pixel data to a pixel-buffer, or modify UV coordinates of a quad, so that it shows another portion of the sprite-sheet.

# Answer
> 1 votes
Usually, to animate a sprite, you have to keep track of three things: time of course to handle animation speed, current animation (which can be the 'line' in an unoptimized sheet) and current frame in animation (which can be the 'column' in an unoptimized sheet).

Depending on your needs, you might also have a variable 'hotspot' which is the reference point from which the sprite will be drawn. This is useful especially for human character walk and run animations, to avoid 'sliding' effects.

Now, to actually draw your sprite, you want to draw only a region of your sprite sheet, which will be either computed (x = current frame * frame width, y = current animation * frame height), or stored in some data structure created by a tool.

Anyway, at this point, you should have a mapping from state (animation + frame) to a rectangle in your sheet. Depending on your technology stack, you might draw a clipped version of the image (GDI+, Java, etc...) or texture a quad with the proper UVs (OpenGL, ...), or use SpriteBatch with a source Rectangle (XNA).

# Answer
> 0 votes
Simply stated, to animate a sprite using a sprite sheet you divide the sprite sheet into all its columns and rows then draw each individual column & row comination in a series at a given speed(rate of switching between sprite positions) and when you loop all that it gives the appearance of animation.

Also you can slow or speed the rate of switching between these columns and rows to give the appearance of a slow walker or a scurrying character and you can increase/decrease the x and y coordinates of the sprites position on the screen to add motion to the animation.

---
Tags: animation, sprites, character, spritesheet
---


# Question
Title: Working together on a game as a project over the internet
I'm looking for someone who would be willing to work on a project that would potentially become something similar to the game evony/tribal wars, but the project won't be primarily for actually making the game, rather than learning from starting to make the game work.

What website would I go about finding someone willing to help me with this and work together on a little project, no money involved unless things started really progressing, in that case if we actually do complete something worth money, then there will definitely be an even split of the income. I'm not what you would call great at programming, I have learned everything from teaching myself and have never taken a college level (or highschool) programming class, but I'm not bad at it or anything. And if anyone reading this is interesting, leave a comment.

# Answer
> 4 votes
We've got a chat for these things too, by the way. `:)`

**For talking to random strangers on the internet**: From personal experience, it's better to be able to say "*hey, look, want to help me improve this prototype*?" than "*I'm looking for someone to code a game with*". People come and go: Don't be afraid to start something yourself!

**As for actually working on a game with others (strangers or not):** Familiarise yourself with revision control software if you're going to be working on code with other people.

I can highly recommend *Mercurial* and I've got friends who like *git*. However, if you're going to have large non-text files, *git* can get pretty messy. *Mercurial* only somewhat cleaner in that respect. *SVN* is clumsy, but there's no escaping that it deals better with large binary files.

**Most of all**, don't worry about the details, just get the ball rolling. If nothing else, you're learning.

# Answer
> 3 votes
The *best* possible choice here is actually to find and meet other local game developers who are interested in working with you on a project. If you're not in a big city, then maybe you'll have to make a trip to one every month or so. If you're completely in the middle of nowhere, however, then you might need to look for people online.

The best possible way to find people for a project online is to go onto various game development forums and start posting about your project. Videos of what you've done so far, screenshots, general goals of where you're taking it. If you're lucky, someone will be interested in your project and offer to help. *Do **not*** just go onto forums and post "hey here's my idea, someone help me make it". That is frowned upon, and the only time someone will offer to help in such a case is if they're really desperate for money/something to do. The issue here is that a lot of people have their own ideas, and they'd much rather work on those than help someone else (unless their ideas are the same as yours...) So it's very hard to find someone to help on a project unless you pay them money from the start.

There's some useful advise here, as well: Finding other programmers to help on a project

# Answer
> 0 votes
Work iteravely. Break down your roadmap to completion into steps and start by offering smaller jobs to do. Ask for help on particular features, say you want to implement a foundation for an AI system that you can build on. It's less daunting than to say "I need someone to help me with these goals: to add a bunch of enemies, at least 10 story quests, and this many hours of gameplay". If you find someone that's interested in doing more the first time around, then consider yourself lucky, but you will more likely get responses from people that are okay with pitching in for a shorter time than going in it for the long haul.

Target a problem that you are most willing to tackle first and go from there. Don't confuse this with bait-and-switching people by making them do more than they initially offered to do, unless they're interested.

---
Tags: browser-based-games, project-management, social, dev-groups
---


title: Fire range arc behind buildings

text:
# Question
Title: Fire range arc behind buildings
need some help with HLSL. Each charater in my game shows a fire range arc (which is a textured model) which show how far the guy can shoot, see

It looks ok, but I hate the fact that it shows even behing buildings. Now I already have a shader for rendering the Arc (where I only manipulate the u coordinate to achive oscilating effect) and I'm pretty sure that I can use the Shadow map approach for that - generate Shadow map as seen by the camera (my deferred renderer takes care of that), then when rendering the arc, compare current Depth to the one stored in shadow map and voila..

But I just can't get it to work. I know the theory, but I'm no expert in HLSL and shadow mapping...

Here is the code I have

```
...
float4x4 World;
float4x4 View;
float4x4 Projection;

float4x4 ObserverWVP; // of the character casting the arc

texture DepthMap; // as seen by the camera
...
struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinates : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinates : TEXCOORD0;
    float4 Observer : TEXCOORD1;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.Observer = mul(input.Position, ObserverWVP);

    output.TextureCoordinates = input.TextureCoordinates;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    ...

    float2 temp = (input.Observer.xy / input.Observer.w) * 0.5 + 1; // half pixel
    float depth2 = tex2D(DepthSampler, temp);
    float depth = input.Observer.z / input.Observer.w;

    if (depth < depth2)
    {
        discard;
    }

    return c;
}

```

And the ObserverWVP calculated in XNA

```
Matrix ObserverWVP = boneTransforms[mesh.ParentBone.Index] * worldMatrix // world
                        * Matrix.CreateLookAt(pos, pos + direction, Vector3.Up) // view
                        * Camera.Instance.ProjectionMatrix; // projection

```

Note that the direction vector is not normalized - it signifies the entire vector from the source (the character) to the outter edge of the arc.

I'm guessing the pixel shader is wrong. But I have no idea how to modify it. Any suggestions?

# Answer
> 1 votes
It seems a problem to be solved with raycasting

# Answer
> 0 votes
I would represent the range arc as a spotlight model, since these types of lights stop right when they hit a wall and don't shine through. They have a set lighting angle and attenuation distance which would correspond to the characters' fire range.

As you have a deferred lighting system in place already, this shouldn't be too hard to apply. Spotlights are usually represented as a mesh, so you can make it either conical or pyramid-shaped, whatever suits your needs for the game. All you gotta add are the textures.

The Cansin Deferred Renderer has a spotlight rendering feature- it would probably be a good idea to see the code behind it.

---
Tags: xna, shaders, hlsl, shadow-mapping
---


# Question
Title: Accessibility of games, how is important for you?
I'm blind and I would know if there is someone that consider important the accessibility, from a blind in particular, when develop a new game. I don't speak about an audio game, I'm speaking about a video game that implements a TTS or a GUI compatible with screen readers!

# Answer
Unfortunately, right now, "games that blind people can play" are pretty much just audio games. The problem is that a lot of modern games rely heavily on visuals, for feedback and as an interface. In addition, many games require fast reflexes, and a TTS or screen reader would slow the player down quite a lot. Additionally, most games use a different output system than the built in operating system one, and screen readers are probably not built to handle that.

For now, designing a game that works well for a blind person and a sighted person would be tricky. There's probably a few games that are like this, but they most likely have very good sound design, as well as audio cues for different menu items. I can't think of too many that fit this requirement.

Finally, there's likely some companies out there who design games specifically for accessibility, but the quality of those games might vary by a large amount, and the games are almost certainly more expensive than a typical game.
> 3 votes

---
Tags: accessibility
---


# Question
Title: What is instancing, and how can I update my graphics code to do it?
This question directly follows on from this one:

How can I implement a renderer that can draw many kinds of primitives?

I have a small amount of drawing code structured in the following way:

A mesh object can be instantiated with different configurations of vertices and indices in order to form any desired shape. A reference to this mesh is then passed to every gameObject class, this class holds spacial information and a draw method that combines this data with that of the mesh to draw that object with the proper transforms.

The mesh is simply responsible for holding pointers to the appropriate buffers.

I was under the impression (wrongly I think) that because I actually only have one object of each type that I'm drawing multiple times, that this WAS instancing. I know this isn't the case.

What EXACTLY is the difference between what I'm doing and hardware instancing and what changes do I need to make to achieve it?

# Answer
> 9 votes
Anything I can say on the subject is said better here: http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter03.html, but I'll give you my best shot anyway.

The idea behind hardware instancing is that you reduce the amount of GPU draw calls by sending each mesh only once, together with a list of transforms. This offloads some of the work done by the CPU to the GPU and reduces amount the communication between CPU and the GPU.

So the difference between hardware instancing and your approach is that you apply the per-instance transforms on the CPU and that use a draw call for each instance. Vs a draw call per mesh for hardware instancing.

To implement hardware instancing you would have write a shader to apply the per-instance transforms and pass the relevant data to this shader. Also you need to use a different OpenGl or DirectX function to do the drawing (for OpenGl you would need to use glDrawInstanced instead of glDraw).

For more details on how to do this exactly, please read the Gpu Gems chapter in the link.

---
Tags: c++, directx, graphics-programming, directx10
---


# Question
Title: Computer generated 2d graphics for games - how to get started
I've seen a lot of nice 2d games recently, like Geometry wars that have really nice computer generated graphics.

I would like to know how is it done so game looks really nice even if it is composed only from really primitive graphic objects. All those lights, glowing particles, transformations etc.

Do you have any tips, info, books, articles that would uncover some details about creating graphics this way?

And what about development for all the mobile platforms, any good frameworks for this kind of work?

# Answer
Most of those flashy 2D games are *hardware-accelerated*, which allows the developer to take full advantage of the graphics hardware, and apply nicer-looking effects without impacting performance that much. Geometry Wars was most likely made with 2D polygonal lines or sprites, with several shaders for effects.

Shaders can be thought of as special programs that run in the GPU of the video card, that do additional stuff with pixels and vertices that would be much faster than doing it on the CPU. To get an idea of what shaders could do, here are a few examples. The explanations are very trivial and I think are pretty good for a total noob to start playing around with them. With some basic math and shader programming it's possible to get those "warp" or "glowing" effects you see in the background.

Object transformations are usually done with matrix-vector operations, or sometimes using linear algebra.

However, the graphics in that game are also simple to the point that a lot of those objects can be also created as sprites, and then it's a simple matter of blending sprites appropriately to create those effects. If you can reproduce the same visual effects from an artist's point of view, it's usually easier and faster to work that way.

I don't know of any good mobile frameworks, not having programmed for mobile platforms before. However I know that cocos2d is a good one, usually used for iOS games and it's based on OpenGL so it's hardware accelerated.
> 4 votes

---
Tags: 2d, graphics, graphics-programming, graphic-effects
---


# Question
Title: Use my computer as a controller/keyboard for the PS3
I imagine that I should be able to pair my computer to my PS3 via bluetooth and use my computer as a controller for the menus and for typing. Are there any open source projects that have done this? If not, where should I start to write my own? Maybe just look at the drivers people have written to pair their computer to the PS3 controller?

# Answer
> 4 votes
I would use HIDClient on Linux for this. It makes your computer emulate a Bluetooth keyboard, and you can customise it at will (add scripting or triggers) since the source code is available.

I will let someone else research the equivalent software for Windows, because I could not find anything satisfying.

# Answer
> 2 votes
Um...you can just plug a regular USB keyboard directly into the PS3, and I'd imagine you can also pair any Bluetooth keyboard with it as well. What's the computer needed for?

---
Tags: playstation3, controllers
---


title: Player Visibility Problem

text:
# Question
Title: Player Visibility Problem
I'm looking into designing and implementing an online RPG (or more accurately, redesigning an existing piece of server software).

One of the problems is that of managing visibility. Update data for other players should only be sent to a game client if their player is near the other players (i.e. you shouldn't get health updates for people you can't see on the other side of the map). The main problem is that if you had to compare all the players every time an update is sent, it would just take way too long as the number of players scales (think up to a few thousand players per map and each of them updating up to 3-5 times a second).

If the players are in a 2D space (it's 3D but the z difference shouldn't affect visibility) what is the best way to manage the visibility of other players?

My idea is to have a separate thread that compares the space difference of all the players every few seconds or so and stores references to all nearby players in the player's object for easy access when an update needs to be broadcasted.

The existing system uses grids to organize players, and only uses only players in the current and neighbouring grids to do updates. There are some problems with the system though, as it isn't that efficient (besides knowing which grid they are in, no other caching) and sometimes visibility limits should extend beyond 2 grids of distance.

Is there a better or easier way? If it can be multithreaded that would obviously be better, and the less main-thread calculation the better.

(For anyone wondering, the project is in C++).

# Answer
> 1 votes
Your current grid system sounds like the spatial hashing system described here.

In theory, the performance should be fine unless too many entities exist in the same grid block.

However, the grid-based hashing isn't as commonly used as a Quadtree. The Quadtree is a bit more involved to implement, but it has a few nice features.

* it costs O(log N) to find something. This is pretty graceful in terms of scaling up to thousands or millions of objects.
* It isn't fixed at a particular scale. This means that it works just as well when you have 1000 really close to each other or 1000 objects really far apart. Obviously both these cases are not handled gracefully by the grid.

---
Tags: c++, optimization
---


# Question
Title: A pattern for a contextual InputState in a Game State Management architecture
**Context of the question :**

When developing a game using Game State Management I came across a problematic when it came to handling user input : I want my game to retrieve user input a single way, but to handle it in a completely different way, depending on the context.

For example, the \[Up\] key will always mean "Menu Up" when you're in a menu, but if you're in the game, it might do different things, depending on the key bindings. Another difference would be, for example, that in a menu, a .5sec `KeyDown` on a key should be interpreted as a single command, but when you're in game, a .5sec `KeyDown` should often be seen as a .5sec movement / burst / charge shot / etc...

Then way I though about to achieve this result is the following :

* Have an `InputState` class that keeps the current and previous Keyboard/Gamepad input states, just like the usual InputState class. Have this `InputState` class implement all the methods I would need in all the different contexts.
* Create an Interface per context. For example, `IMenuInputState`, `IGameInputState`, `ICutsceneInputState`, etc. These interfaces would only contain the method definitions related to the context.
* Have the `InputState` implement all the `I[...]InputState` interfaces. If two or more context need the same method, the same implementation would be used.
* In the `ScreenManager`'s Update method, the `InputState` would be Updated, but depending on which screen must handle the `InputState`, a different `I[...]InputState` would be sent. Even though the screen could access the other methods by casting the interface, only the contextual methods would directly be usable.

**My question is the following :** Is my idea a proper / common way of handling this issue?

If it is, could you tell me the name of that "pattern" or direct me to some online resources so I can read on that and avoid the known pitfalls. If it's not, how would you suggest I handle the problem?

Note: I know this question is borderline since the answer is partially subjective but I'd appreciate some help on this issue since I think it's a critical decision in my project.

# Answer
If I am understanding, then you are saying that you will have a class called `InputState` that implements many interfaces. Then, other classes should never use `InputState`, but rather, pick an interface that applies to them.

With this model, you will be losing the advantages of inheritance. All of the code will be in one class, `InputState`, and the way of accessing that class becomes less clear. These kinds of statements should be a red flag in object-oriented languages:

> Have this InputState class implement all the methods I would need in all the different contexts.

How about something like this:

* `InputState` receives all inputs and reports on them
* `ContextualInput` is a class which defines all of the shared contextual methods
* `MenuInput`, `GameInput`, `CutsceneInput` all extend `ContextualInput` and have context-specific methods

`InputState` will only have general methods such as `InputState.isKeyHeld()`, `InputState.getMousePosition()`, or `InputState.getAccelerometer()`.

`ContextualInput` holds a reference to the `InputState` object, which can be easily swapped out when you want to do testing and supply fake user input. It can also have methods that are shared among all contextual inputs, such as `ContextualInput.getLastAction()`.

Each of the classes that extend `ContextualInput` implement their own methods that are completely abstracted from the way they are triggered. You could use a publish/subscribe pattern for other classes to be notified of these events:

* `MenuInput.onMenuOpen()`
* `CutsceneInput.onAdvanceSlide()`
* `GameInput.onCharacterJump()`
> 3 votes

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


title: How to install java 3d in ubuntu

text:
# Question
Title: How to install java 3d in ubuntu
I'd recently asked a question for getting started in game development from where I was suggested for the book "Killer Game Programming-Java".

On the page there is a java 3d program which needs to be installed. I'd downloaded and installed `java3d` file from here and also from the sun/oracle's site. But the program given there is not working.

I would like to know how to install that java3d package in Ubuntu 10.10, and also is there any need to set environmental variable `$PATH` or `classpath` for java, and if so, how to do that?

The downloaded version of java3d is 1.5 and it is a .bin file.

# Answer
How did you install the file? You say it's a .bin file, so you should run "sh j3d-1\_5\_2-linux-i586.bin" from a shell to install/extract it. That's how I unpacked the JDK from Oracle. In order to run the examples you have to put any necessary libraries from Java3D into the classpath of the example you want to compile or run. Doing this on the commandline is cumbersome, you might want to use an IDE like Eclipse, IntelliJ or Netbeans.

However, "Killer Game Programming" is outdated in terms of the Java version they use. You might want to read it, understand the basic principles and then code a game using a current Java version. If you want to create 3D graphics in Java, you should look into Lightweight Java Game Library
> 2 votes

---
Tags: 3d, java
---


# Question
Title: Andengine Traffic game: moving sprites along path on map
I'm developing simple traffic educational game, like *"Allianz Křižovatky"*. When the player taps on a car sprite, it should start to move with the other cars. If the player made a mistake in choosing a car, a collision happens.

I decided to use AndEngine for this game, because I have time limitations in developing it. How do I make the car automatically move along a specified path, with smooth turns? How would I specify this path on a map?

# Answer
> 3 votes
If you already know the path then to make it move smoothly you would apply a low-pass filter to the actual movement. A simple low-pass filter that might work for you is the weighted moving average.

For example, instead of snapping the car directly to the path like this:

```
car.x = pathNode.x
car.y = pathNode.y

```

You would only move the car partway to where the next node is:

```
car.x = car.x + (pathNode.x - car.x) * 0.8
car.y = car.y + (pathNode.y - car.y) * 0.8

```

This gives up some accuracy to smooth out sharp turns over time. You will have to play around with the weight (0.8 in this case) until it looks good.

---
Tags: java, andengine
---


# Question
Title: Implementing jumping and heightmaps in 2D RPG/Adventure style games?
I've been putting together, albeit slowly, a traditional style game engine in flash/AS3 along the lines of Alundra/Final Fantasy 3/etc etc..

Everything so far is working smoothly (maps from XML data, collision, animation, etc) but I am having trouble gaining height/jumping.

See the image from Alundra to understand the style I am talking about:

I would like for platforms to be jumped on. I am trying to brainstorm different ways to approach this. The player can obviously jump and move at the same time, so every tile would need a 'height' property I'm guessing, and vertical collision would be checked against the tile's height?

Are there any resources/tutorials or even starting points around this that people would like to share? Someone suggested a graph - see the last forum post here http://www.gamedev.net/topic/605520-building-a-map-and-navigating/

# Answer
If I were to do this game, I'd approach it like this:

1. When designing the sprites I'd give each sprite that represents a part of the map a certain height value
2. When the character collides with a plane, if the difference in height is equal to 5 then the character can walk on that plane.
3. The maximum height of jump is 9, so for example if the player tries to jump from ground (height 0) to the stairs (height 10) they won't be able to do that.
4. The red surfaces: either make the character fall down to the next plane (if you want the character to have the ability to fall) or don't allow the character to walk over them (I have set a very high value of 100 so that character can neither jump or walk on those walls).

As for the problem of jumping, as I mentioned, I gave the max height a value of 9. The character coordinates should be assigned like this:

```
 // Whatever value of x that you assign when you move it
 charMC.x = x;
 // The y value should be equal to the actual y position minus how far
 // the character is off the ground
 charMC.y = y - jumpHeight;

```
> 6 votes

---
Tags: 2d, collision-detection, physics, tiles
---


# Question
Title: Using the DTLS protocol for multiplayer games
I am considering using the DTLS protocol for my online multiplayer game. For those who don't know, it is essentially a port of TLS to UDP datagrams.

According to this paper, the main overhead of the protocol is in the handshake phase, which took 950 ms in their tests. However, this study (broken link; see copy on archive.org) indicates that during actual encrypted transport, there is often less than 1 millisecond of delay.

This sounds like a godsend for realtime games. It is a low latency, highly secure encrypted channel that operates over UDP. It provides reliability and protection for the handshake phase, then steps out of the way. Yet, I have never heard of it being used in a game before, even though the RFC spec was written in 2006 and it's implemented in OpenSSL.

Why doesn't every game use it?

# Answer
Why doesn't every game use it? Firstly, I doubt most people have even heard of this protocol. Network security is not well-known among game developers and this is a fairly obscure variant anyway. Secondly, not every game uses UDP. Thirdly, performance is a concern. A fifth of a millisecond delay on every 200 byte packet obviously means you can only handle 5000 packets a second even if your system does absolutely nothing else (which is unlikely). And there's the comparison of write performance - encryption can be more expensive than decryption.
> 4 votes

# Answer
What would the benefits be?

Do not mistake obfuscation as a method of security in multiplayer games. Being able to intercept/inject traffic is not normally a concern, as a client should not be able to modify gamestate beyond normal parameters (aka cheat) anyway. If you're encrypting traffic as a means to avoid this then you're probably writing your netcode wrong, and need to move more of the simulation serverside.

So.. in answer to your question - security of this sort does not usually matter in games.

Sorry if I perhaps misunderstood. Maybe you could outline why you think games *should* use this. You may then find an answer to your question (if this is not it)
> 2 votes

---
Tags: networking, security
---


title: DirectX 2D Sprite Texture

text:
# Question
Title: DirectX 2D Sprite Texture
I am trying to make DirectX display a sprite from a sprite sheet I found on the internet but it doesn't seem to be displaying the texture in the correct position as I am specifying it.

```
D3DXVECTOR2 scaling = D3DXVECTOR2(1.0,1.0);
D3DXVECTOR2 center = D3DXVECTOR2(64,64);
D3DXMatrixTransformation2D(&mat,NULL,0.0,&scaling,NULL,rot,&position);
sprite->SetTransform(&mat);
sprite->Draw(zombieTexture,&srcRect,NULL,NULL,0xFFFFFFFF);

```

`srcRect` is defined as follows:

```
srcRect.top = 384;
srcRect.bottom = 512;
srcRect.left = 512;
srcRect.right = 640;

```

which instead of giving this texture:

It gets this one: (ignore the rotation)

What am I doing wrong?

# Answer
> 0 votes
I'm guessing a bit here, but unless the coordinates are just wrong, this is probably why they are off.

One thing that can happen when you specify coordinates in pixels rather than as 0-1 UV coordinates is that if the texture is resized the coordinates go wrong.

By default the D3DX image loading functions will resize images under some circumstances. For example if they exceed the maximum supported texture size, or the dimensions aren't powers of two.

The solution is either to resize the texture, or use D3DX\_DEFAULT\_NONPOW2.

---
Tags: 2d, directx, textures, sprites
---


# Question
Title: Best resources for Canvas Html 5 development
I am at a competition at work for who can make the best canvas game. Theme is a top down shooter... Winner gets dinner for free.

Anyways I have been looking around looking for some good resources on game deving on the canvas. Any body got any good ones?

# Answer
> 4 votes
This won't be specific to top-down shooter, but totally canvas for sure.

These two should be good to start with.

Anyways, Canvas is simply a "graphics" renderer, the game logic behind can be anything gamedev related, you just gotta write in JS and display through Canvas API.

Whether these two are "best resources"... Depends, because, there is no such thing as "the best".

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


# Question
Title: Is it possible to render to multiple devices / monitors in XNA?
As the title.

If so, how?

As well as wiring it up correctly, how should I manage syncing GPU resources and update/draw steps?

# Answer
You can have a look at this article:

http://glassarrow.blogspot.com/2009/02/xna-c-how-to-create-full-screen.html

And to these discussion :

http://forums.create.msdn.com/forums/p/10227/53871.aspx

http://www.gamedev.net/topic/568847-fullscreen-over-multiple-monitors-in-xna/
> 3 votes

---
Tags: xna, multiple-graphics-devices
---


# Question
Title: Tic Tac Toe, Reinforced Learning and Hash Tables - Don't understand how to create a game
For my data structures course, we were asked to create Tic Tac Toe(3x3)that:

1) Has two player - dumb and smart(computer plays both sides)
2) Dumb player - "X" , always makes first move, and all of his moves are random.
3) Smart player - "O" relies on reinforced learning. Basically, he looks through the hash table(transposition table) created from the different game states learned from prev games and finds good move. Project specifications page has no information on the implementation of the "intelligence"

I don't understand how to handle 3). At what stage of the game, board's hash needs to be inserted into table ? How Smart player decides on his next move ?

Thanks !

# Answer
> 2 votes
You can find something about your problem here. It's some theory about similar project (Reinforcement Learning in Tic-Tac-Toe Game and Its Similar Variations) as you are solving.

# Answer
> 1 votes
I don't know what your course requires, but I can think of a simple approach. You need records of game states, moves, and wins. So the smart player looks up the current game state in the record of past games and makes the move that led to the most wins. (Apologies if this is too obvious.)

---
Tags: ai, reinforcement-learning
---


title: Algorithm for Randomized Weather

text:
# Question
Title: Algorithm for Randomized Weather
I'm having a hard time modeling weather. Modeling a single aspect is trivial - some sinusoidal pattern + random noise. However more than 1 is blowing my mind. I cannot have wind, falling leaves, rain, and snow all to be random. Simple collisions like rain and snow should never happen.

On top of this I'd like an "intensity" level for maybe each. But this can come after the main logic.

Weather is stored in MySQL.

All your suggestions are welcome, but please don't suggest pinging some zipcode and pulling weather from there.

---

Utilizing suggestions from, actually, all answers below I've come up with this *not-to-scale* distribution:

Each feature will be computed with a random noise, and the combination of the 3 will produce overlay effects.

**(temp \< 0) and (humid \> 65) =\> snow**

# Answer
> 9 votes
What about splitting the the weather into more detailed parts?

```
Precipitation - none/light/moderate/heavy
Wind - none/light/moderate/heavy
Type - rain/hail/snow

```

You can still store this in a single SQL column if you want by making it a simple enum with 48 (4\*4\*3) possible values (removing any strange conflicts you don't like).

# Answer
> 7 votes
It sounds like a Hidden Markov Model might be useful to you. These define certain states with statistical probabilities of transitions from one state to each of the other states based on relative frequency in observations.

You can define some weather states for instance 'rainy' and 'sunny' and probabilities of transitions from rainy to sunny and sunny to rainy and calculate for instance the probability that it will soon be raining based on your observation of if it's currently sunny or rainy. The Wikipedia article explains this but this tutorial (PDF) shows a more practical approach.

If you're modelling lots of different weather patterns it would be difficult to model them independently with this pattern, but you can define weather such as 'FogRain' or 'WindSnow' 'SunWind' 'Sun' for instance and have probabilities for each. These probabilities could even be modified based on the in-game month for example. There is a small issue to be aware of though that the size of your probability matrix will increase by n^2 as you add more weather types as each needs to have transition probabilities (even if they're zero) to the others.

# Answer
> 4 votes
In short..

I'd be thinking this through science.

As we all know, snow is rain and vice versa, except they have different solid states due to temperature changes.

Temperature changes can be associated to winds.

A quick Google for "what causes wind" gave me an answer from Answers.com:

> "The pressure gradient force, which arises from the uneven heating of earth's surface. Once it is in motion, the Coriolis force arises from Earth's rotation to deflect it (right in the northern hemisphere, left in the southern hemisphere)."

Aye, not the best source for scientific questions, but it gives the idea.

So, theoretically, you only need wind now. It could be random, or, might as well be somehow scripted to you environment which heats due to some events.

Take wind now, apply to your current position, and randomly or through a scripted way, make clouds out from it. The denser the cloud, the more the probability and density of rain. If temperature is low enough, rain becomes snow. Move the cloud around and make it "not so dense" with that wind.

As for the display, that's up to you, just cache the states of the falling particles, `if rain -> use water drop texture` and `if snow -> use snowflake texture`. Use the wind to make these particles move according to wind direction (yeah, you should store this one too, somewhere) to make it a little more realistic.

And with this you can expand upon everything. Like, if there is snow falling and the snowflakes fall near some kind of heat source, change particle texture to rain again.

Lots of possibilities actually, this is just a simple concept.

P.S. As for the hail, look what makes those, expand the concept for such environment.

Have fun, good luck.

---
Tags: algorithm, random, user-experience
---


title: 2d engine/library for android in C#

text:
# Question
Title: 2d engine/library for android in C#
I'm looking for a good 2d engine or library (that supports physics) for Android. I have a restriction - language should be C#. It's not a requirement to use Mono Droid, but it seems that it is an only way.

What can you suggest?

# Answer
> 0 votes
Velcro Physics (formerly Farseer Physics) is probably the best 2D physics engine for .NET.

If XNA level library is enough you can try MonoGame.

If you want to go even more high level then try Unity.

I wouldn't be surprised if running physics via Mono on Android will turn out to be slow. Some people have issues in iOS with the older version of Farseer. There should be improvements on this side in Velcro Physics.

I would recommend to try some very similar sample first to check if it is possible to get desired performance.

# Answer
> 0 votes
There is a C# wrapper for the box2d engine: http://code.google.com/p/box2dx/

---
Tags: c#, 2d, android, physics
---


# Question
Title: 3D open source physics engine suitable for mobile platforms (Android and iOS)
I have made some research and found that bullet, ode, newton and some others are open source physics engines that should be portable enough (but I have never tried to comile/use anyone of them on phones). I am writing my games for mobile platforms in C++, so the engine should be C or C++. I need a fast engine, since mobile platforms have limited resources. I need a free engine. A good design would be nice to have too.

What engine is best suited for my task? What I really would like to hear from you is your direct experience.

Documentation and support (for example, forum or an IRC channel) is a really important aspect to take into consideration.

# Answer
> 4 votes
Bullet Physics is the choice I'd go with if you absolutely require opensource. It's pretty much THE choice in your situation. If not, physx and havoc both have non-commercial licenses.

Here is a more complete list http://www.gamedev.net/topic/475753-list-of-physics-engines-and-reference-material-updated-7-march-2011/

---
Tags: open-source, mobile, physics-engine
---


# Question
Title: How can I create a curved line composed of images?
I have 50 little images. All are connected each other, as in a line, sort of like a cord. I want to move one of the node images and have the rest follow along like a cord, so they become a curve.

# Answer
> 1 votes
try using multiple CCBezierBy/CCBezierTo instances with a CCSequence instance for all of them.

when initializing all the images have same position! and that's the starting position of your curve. then adjust position of images which come in front of others by calling `[CCSequenceInstance step:some_value]` in which some\_value increases for the images that appear sooner.

you can also add this CCSquence instance to list of images actions in some update loop (and not during initialization) to make them appear in some particular order.

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


# Question
Title: Can XNA's content pipeline be used to load C# source files?
I am wondering if its possible to use the XNA Content Pipeline to load C# files?

I'm working on a game and am currently writing a FSM. I would like to be able to load states from the content pipeline, but the states would be written in C# and must use my interface.

Anyone know how to do this?

# Answer
> 4 votes
It is possible to create a custom importer/processor for C# files. It's also possible to dynamically add content, although it takes a good bit of work.

Unless you really **need** to load in classes dynamically rather than include them in the project itself, don't do it. Your brain will thank you later.

# Answer
> 2 votes
XNA's standard set of importers and processors does not include anything for processing C# files specifically as content, so off-the-shelf, the content pipeline can't do what you want, unless you leave the files as unprocessed text. You can, however, extend the pipeline should you so choose.

However, doing so would probably be a waste of time. The content pipeline is intended to provide build-time transformation services to non-code assets to prepare and optimize them for use at runtime (dynamically adding content at runtime is possible, though a bit tedious, if I recall).

You're talking about executable code in your C# files, and since the content pipeline's transformation services are a build-time operation there will be no functional difference between abusing the content pipeline to hold your C# files and simply adding those same C# files to your main game project, as Drackir suggested in his comment.

In fact, even if you leave the files as unprocessed source code or write a custom content manipulation step to compile them somehow, you'd be faced with the fact that many of the APIs available to compile code, or execute compiled code, at runtime aren't available on the non-desktop platforms -- so if you intend your XNA project to run on those, you almost certainly can't use the content pipeline.

---
Tags: xna-4.0, xna-content-pipeline
---


title: Isometric Building Placement

text:
# Question
Title: Isometric Building Placement
I have my isometric world represented by isometric tiles. If I were to allow the player to place buildings on any of the tiles how would I get this funcitonality to work?

I was thinking if I could add a MouseListener to the images?

# Answer
I would highly recommend not using the MouseListener on the images for one main reason: The graphics should only be a visual representation of what's happening in the game. Using the graphics to control the game creates high coupling between the graphics and the game, which will make it hard to modify or improve later down the road.

I would recommend using math to convert the mouse position to a game position like this article describes: http://www.tonypa.pri.ee/tbw/tut18.html
> 5 votes

---
Tags: isometric
---


# Question
Title: Does the latest DirectX SDK support both Direct3D 9.0c and 11?
1) What is the latest version of DirectX SDK?

2) For my purposes I need DirectX 9.0c SDK and DirectX 11 SDK. Do I need to install these libraries separately or last DirectX SDK package contains both of versions?

# Answer
> 4 votes
The latest SDK version, as of this writing, is the June 2010 SDK. It contains what you'd need to build against both 9.0c and 11.

---
Tags: directx, directx11, directx9
---