# Question
Title: How can I calculate where my camera can be to avoid showing something outside a region?
I have a landscape model, which goes from the coordinate -45, -45 to 90, 90.

The edge of the model just cuts off and i would like to somehow stop the screen from ever passing these points. Basically sticking a boundary so that you can't see off the side. The game is always in top view, with the camera directly facing down.

However the problem is that the player can zoom in and out, obviously you have a wider range of view when zoomed out. (There is a limit to how far you can zoom out, you couldn't zoom out say, so that opposite sides of the map are seen at once).

I am assuming using something like Viewport.Project or Unproject, which changes screen coordinates to 3d space and the other way round, could somehow help me in the situation.

My initial idea may lag too much, which would be a while loop saying "While projection of screen point.X is less that -45, add 1 to the camera.X" etc.

Does anyone have any ideas for this? To sum it up, i need to find a way of stopping anything outside the area of -45, -45 to 90, 90 from being shown on the screen.

Thanks for any help!

# Answer
> 1 votes
So after a bit of mucking around i sat down and took a different approach to the problem. Now I have it all working, and have put loads of comments in so hopefully anyone else with the problem will be able to use this as well. The only things that need to be changed to put into your own project, is: filedOfView, minZ, maxZ, minX, maxX and groundElevation.

```
float fieldOfView = 45; //field of view set for your projection (in degrees)

float minZ = -40; //minimum Z boundary
float maxZ = 85; //maximum Z boundary
float minX = -42; //minimum X boundary
float maxX = 85; //maximum X boundary

float groundElevation = 12; //elevation of boundaries. (The boundaries on Y:0 will have a totally different result to the boundaries on Y:30). In this case, this is the height of the LOWEST point of terrain that touches the edge.

float AR = GraphicsDevice.Viewport.AspectRatio; //Aspect ratio of screen

float perspectiveRatioY = (float)Math.Tanh(fieldOfView); //Ratio of camera height to distance along the Z axis
float perspectiveRatioX = perspectiveRatioY * AR; //Ratio of camera height to distance along the X axis

float maxZoomOut = Math.Min(((maxZ - minZ) / 2) / perspectiveRatioY, ((maxX - minX) / 2) / perspectiveRatioX) + groundElevation; //furthest distance possible to zoom out.

camPos.Y = Math.Min(maxZoomOut, camPos.Y); // adjust camera as to not go further out than possible

float camHeight = camPos.Y - groundElevation; //subtract ground elevation to basically allow us to deal with Y:30 and Y:0 in the same way.

float groundDis = perspectiveRatioY * camHeight; //distance shown from the middle of the screen to the top of the screen (on the height of Y:groundElevation)
camPos.Z = Math.Max(groundDis + minZ, Math.Min(camPos.Z, maxZ - groundDis)); //work out the min and max Z coordinates, and move the camPos.Z within (could be done with the clamp method).
groundDis = perspectiveRatioX * camHeight; //See 2 lines up, this works out for X though instead of Z
camPos.X = Math.Max(groundDis + minX, Math.Min(camPos.X, maxX - groundDis)); //See 2 lines up, this works out for X though instead of Z

```

# Answer
> 2 votes
```
// 'Camera' is an object containing the position of the camera
// 'A' is the angle shown in the picture above
// wallHeight is an optional variable giving the height of a surrounding wall that you could not see through

// The gradient m
float m = Math.Sin(MathHelper.ToRadians(A))
        / Math.Cos(MathHelper.ToRadians(A));// Here A is the angle 'A' in the image above

float c = wallHeight;// Not necessary, but if you have a wall around the map you can go higher.

// x is the point furthest away from the center
float x = ( Math.Abs(Camera.X) > Math.Abs(Camera.Z) ? Camera.X : Camera.Y );

// y = mx + c : x = (y - c) / m     You can also make use of the second formula later if you need to reverse the process.
float y = m * x + c;

```

This code (which needs optimizing) will give you the maximum height you can go according to the x and z coordinates of the camera.

# Answer
> 2 votes
I wrote something just for this a while ago, *but for a 2D camera*. I haven't tried adapting it to use a 3D camera, but since your game is always top down, I think it can be considered as a 2D camera too, so the concepts should be similar enough. Hope it's useful:

http://www.david-gouveia.com/limiting-2d-camera-movement-with-zoom/ (Video Here)

It's basically a way to extend your usual Camera class in order to add `Rectangle Limits` property that specifies a region that the player can never seen beyond. This is done by validating the camera's Position and Zoom values whenever they change in accordance with the Limits property.

Start by reading the article for the entire solution, download the sample at the end and play with it. See how it could be adapted to your project. It's relatively simple, just two new methods and a few property changes.

As usual, for future reference, I'll leave the most relevant bits here too:

**Step 1)**

Add a `Rectangle? Limits` property to the Camera class:

```
public interface Camera
{
    public Viewport Viewport { get; }
    public Vector2 Position { get; set; }
    public float Zoom { get; set; }
    public Matrix ViewMatrix { get; }
    public Rectangle? Limits { set; }
}

```

**Step 2)**

Create methods to validate Zoom and Position of the camera. This is where you might need to change something to work with a 3D camera, so I'll also leave a general description:

```
private void ValidateZoom()
{
    if (_limits.HasValue)
    {
        float minZoomX = (float)_viewport.Width / _limits.Value.Width;
        float minZoomY = (float)_viewport.Height / _limits.Value.Height;
        _zoom = MathHelper.Max(_zoom, MathHelper.Max(minZoomX, minZoomY));
    }
}

```

Validating Zoom is all about the camera's "size", the extent that it can see. You basically find out what is the smallest amount of zoom the camera can have before it sees too much, and clamp it there.

```
private void ValidatePosition()
{
    if(_limits.HasValue)
    {
        Vector2 cameraWorldMin = Vector2.Transform(Vector2.Zero, Matrix.Invert(ViewMatrix));
        Vector2 cameraSize = new Vector2(_viewport.Width, _viewport.Height) / _zoom;
        Vector2 limitWorldMin = new Vector2(_limits.Value.Left, _limits.Value.Top);
        Vector2 limitWorldMax = new Vector2(_limits.Value.Right, _limits.Value.Bottom);
        Vector2 positionOffset = _position - cameraWorldMin;
        _position = Vector2.Clamp(cameraWorldMin, limitWorldMin, limitWorldMax - cameraSize) + positionOffset;
    }
}

```

Validating Position requires basically comparing the camera's position against the corners of our limiting range. Since the limiting range is defined in world space, I get the camera's corner position in world space by multiplying Vector2.Zero by the inverse of the View matrix.

**Step 3)**

Apply the validations to the setters:

```
public Vector2 Position
{
    get { return _position; }
    set
    {
        _position = value;
        ValidatePosition();
    }
}

public float Zoom
{
    get { return _zoom; }
    set
    {
        _zoom = value;
        ValidateZoom();
        ValidatePosition();
    }
}

public Rectangle? Limits
{
    set
    {
        _limits = value;
        ValidateZoom();
        ValidatePosition();
    }
}

```

---
Tags: xna, projection, screen, view
---


# Question
Title: Software/Hardware options for game music
I have some friends who want to make the music for a game I'm developing. We have no idea where to start. I've seen software like Reason (way too expensive at $450). I've also seen stuff like GarageBand for $15. I'm happy to pay up to $50 for software, and I've seen some good quality free software like lmms. I just have no idea what each of them are good for. I'm also thinking of getting a cheap midi keyboard, since that'd be a million times easier than clicking a mouse trying to get the right notes in the right places. So,

1) What hardware is recommended for simple background music

2) What software is recommended for simple background music

3) Where can I direct my friends for learning more about music creation on a computer

I know that I'm being really general, and some people might want to know the "type" of music or what instruments will be used. I have no idea, so I'm just speaking basically.

# Answer
If you're a beginner, I would say the following is required:

* Computer
* $100 midi keyboard from best buy
* Garage band
* very good headphones for mastering
* Watch a bunch of youtube videos of people writing piano rolls and mixing in garage band

If you're just learning digital sound, I wouldn't rush out and buy logic, protools, and reason with $1000 studio speakers. Start out using garageband. Learn to create midi rolls, learn different ways of looping and mixing waves.

Obviously you aren't going to get near as much control using garageband, and you won't have near as many samples to work with unless you buy them. My sound guy went to college for audio engineering and still uses garageband for prototyping his ideas so it's probably a good place to be for digital audio beginners.

Note: this is all second hand knowledge, as I'm a developer on a developer's site, I'm giving you what I know ;)
> 7 votes

# Answer
If you're willing to put the time in you should take a look at Reaper , it a fully featured music production suite, and it's free for personal use, very powerful software. It's fully VST compatible so you can add other software instruments as you need them. Personally I use an oxygen 8 keyboard, I don't play keyboards/piano so that is sufficient for my purposes. I do most of my music programming in the matrix/piano roll editor anyway.

http://www.kvraudio.com/ is a good resource for finding VST instruments.
> 0 votes

---
Tags: assets, music, hardware, asset-creation, midi
---


title: Storing large layered tilemap

text:
# Question
Title: Storing large layered tilemap
My game consists largely of "sea" tiles and areas of tiles to form "islands". Each "sea" tile is exactly the same.

The map is initially large and going to get larger. I'm trying to reduce the map size since, the majority of it is the same.

My initial thought: Store just the islands with their locations within the map. The map consists of, total map size and islands only.

Any other suggestions or perhaps how I could implement the above whilst still being able to use a\* pathfinding?

# Answer
Can you have a separate tile map for each island and just store where that tile map should be located?

Then you could render the ocean by finding the top left most visible tile by doing math.floor(visibleArea.left / tilewidth) and math.floor(visibleArea.top/ tilewidth) and drawing the water texture for every tile for as many tiles as fit vertically + 1 and horizontally + 1, as long as the Y value was under the water level.

Then you just need to render any visible islands.

So you memory foot print should be your textures and as many tile maps as you have islands. Which should be a lot smaller then one huge tile map of the whole world.

Edit: Wow totally missed the "Any other suggestions or perhaps how I could implement the above whilst still being able to use a\* pathfinding?" sorry for the useless answer hopefully the below should help.

There are two ways to represent graphs. Adjacency graphs and edge vertex graphs. I prefer adjacency graphs for tile maps because you don't actually need to maintain an adjacency list just grab any of the the 9 surrounding tiles straight out of an array or generate them.

Point being for A\* on a tile map you don't actually need a data structure containing the adjacent vertices since you can easily calculate it (assuming the graph would have a vertex for every passable grid tile would be adjacent to all possible vertices that are touching it).

You simply have to generate the adjacency list for every vert you pull a off the open list excluding any nodes on the black list or that are impassible. You can assume that all nodes are passable unless the vert is within an area that contains an island, in which case you will use the data from the tilemap to exclude any impassable tiles/verts.

Only real downside of this is that the graph is very dense. However, I doubt this would be an issue because from how I understand you game to be very little wasted effort on branches being explored that will dead end.

More simply you can just make a bee line for any targeted tile when in the water and then use A\* to navigate any islands you come across. There's only two cases I can see here

Case 1: You want to get to a tile on current island

Use A\* to get from the first tile in the tile map you hit to the target tile.

Case 2: You want to get to a different island

Use A\* to get from the current tile to the tile on the tile map that is closest in real space to the tile you want to get to.
> 1 votes

---
Tags: tiles, memory-efficiency, tilemap, storage
---


# Question
Title: Are there established conventions for naming "directions" (width,height) in 3D?
I want to create a 3D game world where the players can modify the environment. I would like to bring it to the point where a power-user could even create "game objects" inside the application using some kind of *very simple* 3D modeling UI. So I decided to write this UI first, as I can then use it to create the game content. I spent some time in the last two months trying to learn Blender, and decided that this was a total overkill for what I want to create.

Anyway, I have the classes representing the 3D "concepts" mostly worked out, but I have problems with the "unwrapping" code, that is, mapping the graphic primitives, triangles and rectangles, to a texture file.

The 3 points representing a triangle are in 3D, but I need to work in 2D for the texture mapping. How should I best choose which of the 3 points to use as the "origin" of that triangle in the texture file, and how do I define some "reliable" concept of width and height that make sense, when I am in 3D?

I can think of several methods, but if one is most commonly used, I would like to know, so that my code also make sense to other people.

\[EDIT\] It seems I did a very bad job of explaining what I want. I understand how unwrapping works. I sweated blood going through a Blender unwrapping tutorial. But now I'm trying to write code that can automatically create a basic unwrapping of simple objects (boxes, wedges, pyramids, ... and composition thereof). My idea was to group primitives that are 1) in the same plane, and 2) touch each other in (flat) "boxes" and map those boxes to the first free spot on the texture file that is big enough (under the assumption that all primitives have the same scale). Far from optimal, but good enough to get going. Later, the user could have refined the unwrapping as necessary, for example, by mapping several "boxes" to the same coordinates, if they look the same. The box would have a width and a height, and the unwrapping would map the "origin" of the box (say top left corner) to the coordinate in the texture file where it should be mapped.

But, for me, width is the length is along the X axis, and height is the length along the Y axis. So how do I decide what is the width and the length when the box is in the X-Z plane, instead of the X-Y plane, for example? And which vertices is the "top left" when all vertices have the same "Y" or "X" coordinate (but vary in Z)? Unlike the real world, there is no "obvious" "up and down", "left and right" ... in computer 3D. Anything can be in any direction. Things don't "fall down" because there is no down.

Hopefully I now made clear my problem. How can I consistently define "top", "left", "width", and "height" when I am in 3D, instead of in 2D, and when a primitive might, for example look like an horizontal line from user point of view because it stretches in Z (which traditionally "comes out of the monitor") instead of Y?

My code can only make sense if I can define all concepts clearly, and unequivocally. I first need a way of defining those concepts that always apply, for any 3 points in 3D space. Only then can I look at any piece of my code, and decide whether it is correct or not. What I cannot define clearly, I cannot program correctly.

What I really want to know is what I asked in the title. I only talked about unwrapping to explain *why* I need to know this.

# Answer
What you speak of is called "unwrapping". This is the process of generating UV coordinates for your mesh, so that it will allow UV mapping.

UV coordinates are in the range of `0..1`, where `0, 0` is the top left of the texture and `1, 1` is the bottom right of the texture.

The process of unwrapping a 3D mesh to a 2D surface is something tricky. Imagine a cube. In order to unwrap it, you would have to cut/separate some of the edges, as shown in the following image (from Wikipedia):

Finding these cuts (seams) is something that is usually done by artists, as there's no algorithm that creates good cuts for every type of mesh.

The most primitive approach of unwrapping would be to simply project every triangle to 2D. You can even have overlapping UV coordinates, so every triangle could have UV coordinates of `(0, 0), (1, 1), (0, 1)`. That would look horrible though... a slightly better approach would be to have coordinates that correspond to the triangle size. But that will still result in visible texture seams at the edge of every triangle.

If you just have basic primitives like a triangle or rectangle, then generating the UV coordinates should be trivial. You can project the primitive to 2d (by looking from the surface-normal) and calculate a (2d) bounding-box of the vertex coordinates. The longer side of the bounding box will map to 0..1. Then every vertex will get it's UV coordinate proportionally to the bounding box size.
> 8 votes

---
Tags: 3d-meshes
---


# Question
Title: How do you triangulate a 3D point from a pair of stereo images?
I'm working with a stereo pair of photos, and trying to obtain a set of 3D points from matching points on these 2 images. How exactly is the point triangulated? Do you throw a ray from the camera pinhole centerpoint? Or do you throw a ray perpendicular to the photos?

**Edit:** I'm also looking for code examples, that document the simple linear/polynomial math involved. Currently I'm simply using 3D line/line intersections to find the point. (actually line/plane intersections) I'm sure this is not accurate and the calibration data of the camera should also be used. Although I don't know how. For instance, with the points on the photos known, should I be drawing the 3D line from the camera pinhole 'origin', or is there a better way? Should I be taking the lens distort into account, or something fancier? The calibration data I have is as follows:

* ix, iy -- Image sensor width and height, i.e. the dimensions of the photograph.
* fx, fy -- Focal length in x- and y-dimensions measured in pixels.
* cx, cy -- Principal point coordinates, i.e. coordinates of lens optical axis interception with sensor plane.
* skew -- Skew transformation coefficient.
* k1, k2, k3 -- Radial distortion coefficients.
* p1, p2 -- Tangential distortion coefficients.

# Answer
> 1 votes
The first image is more correct, because image on the photo is perspective rather than orthographic. It can be orthographic on macro photos. Possibly it depends on what type of lens do you use.

---
Tags: 3d, mathematics
---


title: How can I simulate shattering glass?

text:
# Question
Title: How can I simulate shattering glass?
I need to make a simulation with stone thrown through a glass window. How can I accomplish that?

I mean, I was thinking about making a 3D model of a stone and glass in 3D Studio Max 2012, shatter the glass and export both to XNA 4.0 as .x models. Then in XNA make the animation - writing my own physics engine. Is it possible that way? Is it possible to destroy the glass in XNA after impact or should I do it in 3DS Max? By 'destroying the glass' I mean disconnect some previously shattered glass bits from each others, because depending on the start-speed and weight of the stone and resistance (hardness?) of the glass (all user-defined) the bits will disconnect from each other in different ways.

# Answer
> 5 votes
Voronoi shatter is one approach that creates fairly realistic shatter for eg. toughened glass which has the remarkable ability to shatter into small, typically convex fragments due to structural changes to the glass during manufacturing. Also, given you have a pane of glass, you will only need 2D Voronoi implementation, not 3D.

# Answer
> 3 votes
Automatically generating shattered pieces from an initially-whole mesh is pretty tricky, I would think. If you're just interested in simulating the dynamics of the shards as they fly through the air, collide etc. then I'd start with a pre-shattered mesh, using breakable constraints or something to hold the pieces together until they're pulled apart with enough force.

# Answer
> 3 votes
Make an unshattered pane and a shattered pane. When you get the collision turn off the unshattered version and start using the shattered pane.

If you are throwing one stone (of a somewhat consistent size) at a window then you can get a long way with your 3d model of the broken pane (model the shards in place in the pane and then run a simple physics simulation on each of the shards to simulate them falling/flying). Unless the camera is very close (or in slow-motion) you shouldn't need to do collisions between the pieces - just with the surrounding geometry (ground plane?). Don't forget to spray some particle effects for the cloud of smaller glass particles that accompany the shatter.

If you make the broken pane with the assumption that the stone is hitting the center then you can scale the pieces based on the actual hit position to get a pretty good looking break for most hits.

# Answer
> 2 votes
If you download the Bullet Physics Library it has a sample that includes shattering glass, and you would need something like bullet in any game with shattering glass.

Edit: Bullet would be a great demonstration to model your own engine after.

# Answer
> 1 votes
Thank you really much for your answers and priceless help. I finally managed to build the project. I tried all your sugestions and in the end chose partly my own way for this simulation.

I used bulledsharp (bullet physics wrapper for c#) for physics engine, but it is important to use the most recent one, compiled by yourself with bulletsharp source from sourceforge svn as well as fresh bullet physics sources itself. Not the one precompiled .dll's, available to download from websites. The version precompiled was too old for me and did not include some precious features developed further. What I also learned is that for simple simulations where you do not need advanced graphics it is better to use older 3dsmax, ie 2011 (not the most recent 2012), to develop model etc. Mainly because there are more plugins and exporters. Whats more it is really helpful to check out the tutorials in all available frameworks (sharpdx, xna, xna4, slimdx, c++ and other).

Finally, my approach was to build the glass wall using really small cube pieces. Of course to make the simulation run you must have really powerful machine. In case you have something less powerfull you can use bigger cubes. It is important to make all the cubes created with sleeping island state. Now, every piece have his representation in two dimentional array of floats. The number there indicates what is the connection strength between two cubes. When the stone is thrown, and collsiion is detected, the force is being computed for each cube in the wall (including stone mass, and velocity, cube mass and size and distance from the center of collision) and subtracted from the array in the circle-like pattern. Those cubes which after subtraction has zero or less connection strength are made active. This causes the cubs to move.

This is it. Thanks for your help.

---
Tags: xna, physics, xna-4.0, 3dsmax
---


# Question
Title: How can I organize code for views efficiently?
I'm making a video game for the Android platform and I need advice on the overall set up of the activities and views in the code. I don't need actual code, psuedocode will do, but actual code always helps. I will basically have the following:

* A surface view that draws bitmaps in a 2d scene and rearranges them according to what ever is happening on the screen.
* A main UI interface that needs to be shown on top of the surface view at all times that has buttons like the attack, defend, hotkeys and so on.
* A start menu as a seperate activity that the user can choose options like volume, orientation, graphics quality, save & exit and so on.

Also I want dialogs throughout the games that pop up when interacting with NPCs and these dialogs need to display pictures as well.

That pretty much encompasses the first version of the game. I will add complexity to it maybe later on down the road but for now I would just like a general plan of how to set all of this up in a functional way. Again code would be nice but I really just need an idea of how to efficiently do these things without wasting memory resources and utilizing the Android APIs capabilites with smart programming methods.

# Answer
On my personal projects, usually any menu out of the actual game (like start menu, options etc...) are done using basic XML layout provided by the Android API.

For in game UI (including dialogs and popups), I mostly make it inside my canvas, which let me integrate it inside the game.

But I guess that uising a frame layout, you could use native buttons and interface element on top of your surface.

About the NPC dialogs, I know that Replica Island using an separate Activity to diplay a popup (you can check out their source code, it's made by an engineer from Google and it's open source)
> 3 votes

---
Tags: 2d, java, android, algorithm, game-loop
---


# Question
Title: How does a wow server handle which player position to set to each nearest players?
I already understood how game developers could create very large game levels, bypassing the floating point precision limit.

This was my very first mind boggling question, and I understood it when I read how some programmer told the story of some dungeon PC game.

My question is more related to game networking, more precisely wow.

There are no interruptions in the game level (apparently I think).

Since the viewing distance is much smaller than the world size, and since there are a lot of players, you can't send all players positions because it would require too much bandwidth; so you have to only send the nearest players positions, among a pretty big list of connected players.

Those servers are almost always online, with a large number of players (only doing quests or idling into cities, since I guess dungeons and raids must be hosted on dedicated servers), and they must find a solution to save as much bandwidth as possible.

So at one point the server has to determinate which players positions it has to send to which players, and when it has to stop sending it.

I was wondering about how the server does this, because to me it seems to have O(n^2) or even an O(2^n) complexity. How do they do it ? Do they fragment into virtual tiles so they only check players in the nearest tiles ? Do they calculate this not so often so that the server can handle it ?

A continuous online persistent world is quite awesome, but technically I don't really know how they do it.

# Answer
> 5 votes
This is really a data structure issue, in that you need a quick way of looking people up based on position.

Analogy: If you were to try and find a psychology book by Freud in the library, you wouldn't look at every book in turn. Instead, you'd go straight to the psychology section. And once you were there, you wouldn't start at A and look through each book until you found it: you'd go to the 'F' section and look there. This requires the library to have decided on a couple of criteria - subject area and alphabetisation - to order their books. Then, armed with that information, you can find the books you want without having to look at every other book in library.

So how can we do this for geographical positions, given the knowledge of an initial position? It turns out there are several ways:

* Sort all objects by one of the coordinates. You still have a long list of N objects, but you can jump somewhere in the middle based on the coordinate in our original position, and from there can quickly narrow the search down. This would be a bit like the library ignoring subject areas but sorting everything by author. It's not ideal, but it works well enough in many situations. Most small games can perform well enough with this method.
* Store objects in a tree structure. You can divide up all the possible positions, eg. into 2 halves, and then subdivide them further, continuing until you have very subdivisions that are small enough to be manageable. You can search the tree quickly because every position comparison lets you rule out half of the objects. If you created a binary tree based on one coordinate then you essentially have the same system as the previous idea, except that the structure is explicit in the tree instead of implicit in the way you search the list. More usefully, you could create a quad-tree that is divided up by 2 coordinates and eliminate 75% of possibilities with each decision, and if you need all 3 coordinates, an oct-tree works for that.
* Store objects in a hash-table. A hash treats an input value as a way of indexing into a large structure. Normally you want each input value to generate very different hashes, but in our case we want some coherence between adjacent values so that objects near to each other tend to get hashed nearby. So you might take 2 coordinates and divide them by 50 and discard the remainder to get a hash value - this means that objects within that 50x50 area will be hashed under the same value. This in turn means that you may only need to check that box and the ones around it to quickly get a list of all nearby characters.
* Store objects in a grid. If you divide your world up into arbitrary zones or tiles of a predictable size, you can easily find nearby objects by first determining the zone to start from, and then getting all objects in that zone or in adjacent zones within the range of interest. To determine which grid square a position is in is a case of dividing the position coordinates by the size of the grid. You can easily see that this is basically the same as the previous method and that the way to determine the grid square is a hash function, and the grid squares holding objects are the hash table.

Any of these approaches would work for most games. Although the tree approaches look elegant, usually a 2D grid is sufficient, with it being very easy to write and test, and having good lookup speed. For smaller games it's often not necessary to implement any spatial database at all, or to stick with the sorted list.

# Answer
> 2 votes
Get on a long flight path, with a Hunter who can track is best. Watch NPCs around you come into existence and disappear behind you.

WoW is apparently working with little chunks like @thedaian says. All the server has to do is subdivide everyone into chunks, much much faster than N^2, close to linear. And these chunks are quite small, the amount of the NPC world that exists for you can be felt even when running around on the ground.

google "space partitioning" to find various ways that these chunks are done, though I expect that WoW took the easy way and just laid down a 2D grid manually. The advantage to the manual way is that special areas like cities can be tuned for performance, so remember that "easy" is not "bad!"

# Answer
> 0 votes
In case of cities and dungeons, I know that the server split it in sections. In stormwind you don't receive information about players in other districts. In the past you could see that with the glitch that allowed you to go under the terrain in stormwind. You could only visually see the players in the same district above you.

Outside I think the server has no option other than separate players by their distance, and there's a lot of ways to do that

# Answer
> 0 votes
A scene graph, and likely not too much of a complicated one..

When you think of graphical rendering you are sending hundreds of thousands of vector values to figure out which parts of which models you are rendering on the screen. And this happens 30+ times a second depending on the game and the hardware.

Translate that to the number of people per-zone in WoW and you are talking about having to handle a scene graph of a few thousand entries at most. The hardest place would be in the cities where people gather to trade and the like, but as pointed out by Papavoikos they are further broken down into which district in the city you are in.

In either case, the number of elements you are dealing with, connected players in your region, is never all that high as compared to things like rendering that are doing the exact same sort of calculations, which objects with positional data am I near?

Hope this helps.

---
Tags: networking, mmo, coordinates
---


# Question
Title: How do you calculate if a line is facing a curve?
Given the 2 points describing a line segment, and the 3 points describing a quadratic bezier curve, how do you calculate if the line is facing towards or away from the curve?

The line has a fixed length, and is stored in 2D as x1/y1 and x2/y2. The curve is a quadratic bezier curve, and is stored as x1/y1 (control point), x2/y2 (bezier point), x3/y3 (control point).

# Answer
> 2 votes
First of all we need to know how a beizer curve is generated. according to it's wiki page, a `Quadratic beizer curve` is a function of t stated as follow:
In this formula t is a variable between zero and one and all other parameters are vector values (it means B(t), P0, P1, and P2 have values for x and y in 2D world).

the next thing you should know is how to define a line based on two given points. again we can see in beizer wiki page that lines are some special kind of beizer curves with only two control points and no beizer point. and their formula is again defined using parameter t as follow:
again t is a scalar value while p0, p1, and L(t) are 2D vectors.

Now we want to know if our beizer curve collides with the ray started with an specific point in an specific direction. to do so we need to solve This equation:

* in this formulas t and t' are unknown variables and all the others are known
* P0, P1 and P2 are representing Beizer curve while P'0 and P'1 are endpoints of the line.
* we can't assume `t=t'` in most cases. and it's also possible to get two values for both t and t'. having two results only mean the line has two intersection points with the curve and it's nothing to worry about.

solving that equation is almost easy but the results of the equation will tell us about collision states:

if in a results we get `t<0` or `t>1` it means the ray does not collide with the curve itself but with it's trails which is a point we are not interested in.

if in a results we get `t'<0`: it means the line collides with the curve in the opposite direction.

if we get `t>0`: it means lines collides with the

# Answer
> 0 votes
A quadratic bezier curve is (obviously) a quadratic function. A line is a linear function. So to find any intersection points you have to solve a system of equations like this:

line-function = bezier-function

If you get any solutions (functions intersect) you calculate the distance between intersection point and start/end point of your line and you should know if the line is facing towards or away.

---
Tags: mathematics, geometry, beziers, curves
---


# Question
Title: loading images to the backbuffer / direct3d / c++
i think i just found the solution. 1) the problem is that backbuffer surface and source surface are of different formats - that is why exception was thrown. 2) the image path needed double slash `"C\\......."` ;)

================================= I have been googling for a while but still cant come up with a solution to the problem - `D3DXGetImageInfoFromFile` function just doesn't load any images.

it compiles perfectly well, but throws an exception when it comes to the `D3DXGetImageInfoFromFile` function.

Here is the complete listing:

```
//================================================================================================================================// including stuff //=================//

#include <windows.h>
#include <string>
#include <d3d9.h>
#include <d3dx9.h>
#include <d3dx9tex.h>

//================================================================================================================================// handling windows //================//

HINSTANCE hInst;
HWND wndHandle;
bool stopEverything(false);

//================================================================================================================================// handling directx needs //==========//

LPDIRECT3D9                 pD3D;                       // the Direct3D object
LPDIRECT3DDEVICE9           pd3dDevice;                 // the Direct3D device
IDirect3DSurface9           *Surface = NULL;            // image surface
IDirect3DSurface9           *BackBuffer = NULL;         // back buffer surface

//================================================================================================================================// declaring functions //=============//

bool initWindow(HINSTANCE hInstance);
bool initDirect3D(void);
void cleanUp (void);
void render(void);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

//================================================================================================================================// code starts here //================//

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    if (!initWindow(hInstance)) return false;

    if (!initDirect3D())
    {
        return false;
    }

    MSG msg;
    ZeroMemory(&msg, sizeof(msg));

    while(msg.message!=WM_QUIT){
        if(PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
         {
             TranslateMessage (&msg);
             DispatchMessage (&msg);
         } else {
             render();
         }
    }

    return static_cast<int>(msg.wParam);
}

bool initWindow(HINSTANCE hInstance )
{
    WNDCLASSEX wcex;

    wcex.cbSize             = sizeof(WNDCLASSEX);
    wcex.style              = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc        = WndProc;
    wcex.cbClsExtra         = 0;
    wcex.cbWndExtra         = 0;
    wcex.hInstance          = hInstance;
    wcex.hIcon              = LoadIcon(0, IDI_APPLICATION);
    wcex.hCursor            = LoadCursor(0, IDC_ARROW);
    wcex.hbrBackground      = static_cast<HBRUSH>(GetStockObject(WHITE_BRUSH));
    wcex.lpszMenuName       = 0L;
    wcex.lpszClassName      = L"DirectXTemplate";
    wcex.hIconSm            = 0;

    RegisterClassEx(&wcex);

    wndHandle = CreateWindow(L"DirectXTemplate", L"DirectX Template", WS_EX_TOPMOST | WS_POPUP | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, NULL, NULL, hInstance, NULL);

    if (!wndHandle) return false;

    ShowWindow(wndHandle, SW_SHOW);
    UpdateWindow(wndHandle);

    return true;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_DESTROY:
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

bool initDirect3D(void)
{
    pD3D = NULL;
    pd3dDevice = NULL;

    // create the DirectX object
    if(NULL == (pD3D = Direct3DCreate9(D3D_SDK_VERSION))) return false;

    std::wstring wsPath = L"C:\wood.bmp"; // path to the image
    D3DXIMAGE_INFO Info;

    if (FAILED(D3DXGetImageInfoFromFile(wsPath.c_str(), &Info)))
    {
        MessageBox(NULL, L"You're a terrible programmer!", L"ERROR", MB_OK);
        stopEverything = true;
    } else {
        pd3dDevice -> CreateOffscreenPlainSurface(Info.Width, Info.Height, Info.Format, D3DPOOL_SYSTEMMEM, &Surface, NULL);
        D3DXLoadSurfaceFromFile(Surface, NULL, NULL, wsPath.c_str(), NULL, D3DX_FILTER_NONE, 0, NULL);
        pd3dDevice -> GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &BackBuffer);
    }

    // fill the presentation parameters structure
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp, sizeof(d3dpp));

    d3dpp.Windowed          = TRUE;
    d3dpp.SwapEffect        = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat  = D3DFMT_X8R8G8B8;
    d3dpp.BackBufferCount   = 1;
    d3dpp.BackBufferHeight  = 480;
    d3dpp.BackBufferWidth   = 640;
    d3dpp.hDeviceWindow     = wndHandle;

    // create a default DirectX device
    if (FAILED(pD3D -> CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_REF, wndHandle, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &pd3dDevice))) return false;

    return true;
}

void render(void)
{
    // check to make sure you have a valid Direct3D device
    if (NULL == pd3dDevice) return;

    pd3dDevice -> Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 0, 255), 1.0f, 0);   // clear the back buffer to a blue color

    if (SUCCEEDED(pd3dDevice -> BeginScene()))
    {
        if (stopEverything == false)
        {
            pd3dDevice -> UpdateSurface(Surface, NULL, BackBuffer, NULL);
        }

        // end the scene
        pd3dDevice -> EndScene();
    }

    // present the back buffer contents to the display
    pd3dDevice -> Present(NULL, NULL, NULL, NULL);
}

void cleanUp (void)
{
    // release the device and the Direct3D object
    if (pd3dDevice != NULL) pd3dDevice -> Release();
    if (pD3D != NULL) pD3D -> Release();
}

```

# Answer
Your D3D device needs to exist before you can load the image and create the surface.
> 0 votes

---
Tags: c++, directx
---


title: Recreating assets after onResume()

text:
# Question
Title: Recreating assets after onResume()
After onPause is called for the GLSurfaceView the rendering surface is destroyed, along with all the textures, shaders and the like. On onResume() should the surface not be recreated and GLRenderer onSurfaceCreated called? However that is never called. I am using render when dirty.

# Answer
If you use this modified version of GLSurfaceView your rendering surface will not be destroyed:

http://replicaisland.googlecode.com/svn/trunk/src/com/replica/replicaisland/GLSurfaceView.java

As far as graphical context (OpengGL ES context) is concerned there is a myth surrounding this issue, that it's destroyed when onPause is called. No that is quite not true. Your context stays alive as long as there is still memory left for other contexts to be called upon.

For example if you have 3 games each requiring around 100 MB of RAM, they can all run at once on a Samsung Galaxy S2, which has around 800+ MB, depending on the manufacturing model. **However** on low memory devices you should implement a texture + shader load/unload method.
> 1 votes

# Answer
I believe this is something the android framework does, as some devices / GPU's can't support multiple GL states and clearing any `onPause()` allows other apps to use openGL.

I just accept that and reload textures etc `onResume()`. If you keep your textures as bitmaps in memory as well as all your vertices etc, you should be able to minimise the amount of time it takes to reload after resumption.

Then again, I don't extend GLSurfaceView and do all my rendering in `GLSurfaceView.Renderer`

EDIT: Actually, check the answers for this question
> 0 votes

---
Tags: android, opengl-es2
---


# Question
Title: What sorts of stats do games companies track when people play their games ?
I've seen interviews with certain games companies where they talk about getting stats back from their users, particularly with games on facebook. This data allows the companies to monitor and adjust the difficulty of levels, see what's keeping people engaged etc. I am just wondering exactly what sort of data would they be collecting? How common is this practice and would developers of Android and iOS games be involved in similar practices?

# Answer
> 5 votes
It's most common for developers to track simple usage. That is, how often people play a game, how long they play it per sitting, how often they return to it, and which features of the game they use the most.

For games in which the player character can die, they often track where deaths happen. For puzzle games, they track puzzles which people skip, or simply stop playing at. All of this is aimed at identifying awkward spots in the difficulty curve.

I have personally worked on games where we tracked almost every choice that players made during the game. We didn't do this in order to track individual users, but rather to notice the larger trends. As an example, one game I worked on was a game where at the start of the game, the player was given a selection of five cars to drive. They could pick any those five cars, for free. And we tracked which of those five cars users selected. What we learned from that tracking helped inform our user interface designs for future games.

You can safely assume that every game which has any online component will be tracking this sort of data (this includes everything using GameCenter or Crystal or OpenFeint or etc). You can also assume that every game from a major publisher/developer will be tracking this sort of data, even if they don't use one of those services.

# Answer
> 3 votes
The question really isn't "what stats to track", but should be thought about in terms of "what problems might come up".

As an example:

* "funnel" stats, how far users got in the installation process, tutorial process, etc.
* monetization stats, what types of users bought what kinds of things, and what other options
* virality stats, how often users "shared" things with their friends, what kind of things they shared, and which ones were effective at getting their friends to come back to the game.
* how often your users ran out of "energy" (in those kinds of games)

At least in the Zynga-style Facebook world, the goal of stat tracking is to improve your game over time so people stick around longer and buy more things. Stat tracking is a means to an end. If you don't have good visualization software or ways of comparing correlated data, then just grabbing raw stats is kind of meaningless. Likewise if you don't have directed questions you're trying to get objective answers to, your stats don't really have any context.

Funnel stats in particular are a good one to look for. If you notice that 10% of your users don't finish a particular tutorial step, then maybe that part of it needs to have some design time put into it. If you have a lot of people leaving before the game finishes loading then you know you need to get your file size down. That kind of thing.

Another popular thing to do to use stat tracking effectively is A:B testing. Let's say you want to make change X that should improve some metric Y you care about. For the majority of users, leave the game the same. Introduce the change to a small percentage of your users (but large enough to be statistically significant), and compare results. If your change X increases metric Y, then you start rolling it out to more and more people. If it doesn't, you revert it. This is useful to get tuning for costs right.

# Answer
> 0 votes
Ever wondered why there are so many useless, but progress-indicating ingame achievments like "played through the second level on any difficulty setting".

Steam Achievements for example pose a horrific opportunity for gamedevs to track their products usage. So for a real time answer just browse any achievements page for a game.

---
Tags: statistics
---


# Question
Title: Binary operation for fast 3D game engine
I had a thought while ago. I read about bitBoard and I was curious, could be the concept be applied in 3D?

What I mean is to use a 3D matrix of boolean value, which correspond to the voxels. So that one could use the and, or, not, ecc bit operations to calculate if a position for example is occupied or not.

for example let's consider the two objects (represented by 1's):

```
 object1              object2            result: no collison
 0000000000           0000000000         0000000000
 0001110000           0000000000         0000000000
 0001110000     &     0000000000    =    0000000000
 0001110000           0000000011         0000000000
 0000000000           0000000011         0000000000
 0000000000           0000000000         0000000000

```

would it be useful? Are there already games that uses this trick?

# Answer
> 1 votes
It could be useful under the right circumstances, a CPU can do operations like that really fast, and a GPU can blaze through them.

However, you must realize the limitations of this method, when you say 3D I don't think it's applicable to your situation. 3D matrices grow awfully large for relatively little side length, straining memory and requiring so many of those fast operations that the end result is pretty slow. Apart from that, there is no efficient way of rotating such matrices.

In total, I can't think of anything more complicated than a Mario style game which would be suitable for such a method.

---
Tags: collision-detection
---


# Question
Title: What is road map for Windows 3D game development in C#
I used WPF 3D to make a demo program a while ago. I'm now want to give some other things a shot but find working in WPF 3D ... confining. I have looked at Managed Direct3D but read that it's dead. I have looked at wrappers for OpenGL but they seem to be work in progress or documentation/tutorial sparse. XNA seems like a decent platform but I have a feeling there is something better.

Does anyone know of a road map for C# 3D game development on Windows platform?

# Answer
It looks like XNA is fading on the Windows platform. I would take a hard look at both SlimDX and SharpDX.

With that said, both probably aren't as beginner friendly as XNA.
> 2 votes

# Answer
Good question. The unofficial word is that everything changes with Windows 8, Silverlight+WPF pretty much dead, probably XNA too. D3D+.cpp stays, HTML5+.js is the new favourite. Deep silence about the rest. I don't want to spread the FUD and I really hope someone have concrete info about the future of game development in C#.
> 1 votes

---
Tags: xna, c#, 3d, windows, wpf
---


title: Design criteria question kids games

text:
# Question
Title: Design criteria question kids games
I am currently designing a game for small kids that have not yet learned to read and would like to get some opinions, and views, on scoring?

Given that these (hopefully) will be small children that cannot yet read or children that have just learned to read, between 2 - 5 maybe what about scoring, do you think that is needed?

My idea was to avoid both any character at all and only use pictures. However, if scoring is implemented there re always other ways to do that i guess with colors, bars etc.

Would someone nice just elaborate a bit on general design criteria's for this type of games and applications with this target audience?

# Answer
I am not an expert on the subject, but I do have a 4 year old son.

The most important thing for him in a game, seems to be characters, colors, and sounds. The game also needs to be quite simple. He prefers playing games on a touchpad screen, as the interface is the easiest for him to use.

At his gaming maturity level, scores are irrelevant. What is most important is to provide a good feedback, preferably a visual feedback, that will indicate if you are doing what you are suppose to do in order to win the game.

Keeping score can be as simple as making it to the second level. A simplified explanation of what I mean could be changing the background color from Red to Blue after a goal is accomplished. The next time they play, they will start understanding that they are starting off on Red and need to make it to the Blue.

The main thought is that you need to entertain. A scoring system is typically used to promote competition in your gaming experience.
> 4 votes

# Answer
It's unclear if this is going to be a single or multi player game. If it's single-player, @Jon's answer stands.

If it's multi-player, and some kind of scoring is really required, you could represent it with bigger crowns, higher piles of cake, and so on.
> 0 votes

---
Tags: game-design
---


title: Quarter turn sprite sheets?

text:
# Question
Title: Quarter turn sprite sheets?
I'm having trouble finding sprite sheets that have the characters turn in 8th movements, so that you can see back, front, left, right, and in between. What would be a good *term* to search for when trying to find these kind of sprite sheets?

# Answer
I just typed in "8 directional sprites" in google images and got some relevant results.
> 2 votes

# Answer
You can google "isometric character sprite"
> 0 votes

---
Tags: sprites, assets, isometric, spritesheet
---


# Question
Title: cocos2d looks like it is well supported and widely used, are there other good choices?
I've been googling a bit and looking for ios game frameworks. It looks like cocos2d has the mindshare, and it looks like it has an active community. It also fits my budget ($0.00), as this is really more for fun than anything else.

Are there other open source alternatives worth looking at?

To be a bit more specific on criteria, I'm interested in the following.

* ios
* open source
* well used (i.e. used on more than a few games)
* active community
* should provide benefits over just doing it 'on your own'

# Answer
> 0 votes
As far as I know, Cocos2D should fit your criteria very well. So it may well be a good idea to look into it a bit further, and only look for something else if you really dislike Cocos2D for any reason.

---
Tags: ios, open-source
---


title: Exporting Blender bones

text:
# Question
Title: Exporting Blender bones
I wrote an exporter for blender models that works great for meshes. I'm attempting to extend that to bones defined in blender. However I haven't found good information for exporting bone data. How can I access bone data? I'd like access all the vertices that the bone affects, the weight of each vertex and the matrix. Do I need to export anything else for skeletal animation and dynamic dismemberment?

# Answer
> 7 votes
My suggestion is honestly just to find a format that Blender will export its bones as well, and then look through the script of that format exporter. I was doing something similar and realized how much of a pain it was to find a good resource on exporting bones.

But here's this specification that helped me a lot, on armature modules

# Answer
> 8 votes
@Michael directed me to an excellent resource for exporting bones from Blender. It provides all the information I needed. It's actually already built into Blender, it's the DirectX Model Format.

Go to user preferences, addon section, "Import-Export" category and install "DirectX Model Format (.x)". Then use File-\>Export to select the newly added format.

This format exports not only the mesh information (vertices, triangles, quads, textures, etc), but also exports armature information, including the armature structure (parent/child relationships), transform matrices, which vertices are included in each bone and even the bone weights for each vertex. Animation sequences are exported too.

All in a human readable ASCII format, so it's easy to write an importer. Beautiful.

# Answer
> 2 votes
The IQM (Inter-Quake Model) format has a set of Blender exporters that will export skinned meshes with blend weights and the armature. Look to http://lee.fov120.com/iqm/ for documentation and code. You could also look at the Doom 3 format MD5 exporters.

---
Tags: animation, blender, scripting, skeletal-animation
---


# Question
Title: Ragdoll on alive creatures: has somebody already implemented it?
I find that a dead creature falling realistically is boring.

I wonder, has any game implemented an animation system where the model moves depending of the muscle forces and the velocity of the limbs, but calculated ingame ?

It is much faster to have determinate animation data which is loaded and is just read sequentially, but it looks much "static".

Since I hear a lot about procedural generated data, one could generate a body with its own animation depending of the weight of the bones.

I'm not talking about a real-life robot simulation where the bone is standing, auto-adjusting some angles to keep balance, but something more intermediate and more pre-calculated.

The forces vary slightly between steps (some random on a float so vary plus or minus 10%), so the trajectory of the limbsvary between steps.

It would require a lot of adjustement and preconfiguration, but it would look much less deterministic.

# Answer
> 9 votes
NaturalMotion's Euphoria engine simulates a "motor nervous system" to do procedural animations. It's been used in a couple games, notably GTA4 when pedestrians are hit by cars.

It's still considerably more expensive than static animations, and you'll rarely see more than a few models animated at a time with such a system.

# Answer
> 5 votes
To see this done in an extreme way, check out the game "QWOP", where the player is 100% ragdoll and you use key commands to move the legs.

http://www.foddy.net/Athletics.html

# Answer
> 5 votes
I worked with an engineer who spent an entire year implementing ragdoll support in a AAA game for when a living character gets knocked down. After all of that, they ended up cutting it completely. It was the right decision: it looked horrendously artificial and shattered your suspension of disbelief.

It's hard to underestimate how fantastically sharp our brains our at discerning realistic human behavior and when an animated model steps just outside of that, it's in serious uncanny valley territory. Remember the horror show that was Polar Express?

# Answer
> 2 votes
At lest some of the Unreal games use ragdoll figures, but they are only visual, the game mechanics rely on simple physics.

# Answer
> 2 votes
A fine point to address is the fact that purely ragdoll physics takes far too much realism AWAY from the game, causing players to lose interest easier due to realizing that it is indeed a game, and not feel as if it's another world. On the other hand, you can add lots of realism to a game by using procedural animation techniques based on ragdoll physics. So all I'm really saying, is make sure you know where realism meets comedy, and where to draw the line between what is realistic kinetics and what is just taking ragdoll physics too far.

An easy way to help explain it would be this article I found a long time ago, that describes the ragdoll physics and creation themselves, as opposed to the procedural animation side: PyODE ragdoll physics, a Python and ODE implementation.

I don't quite know an awesome resource for the implementation of the procedural animation myself though, sorry.

# Answer
> 0 votes
You can see if there's any information out on "Die By The Sword," which was all procedural animation, and its successor "Draconus." Also, I believe that "Spore" is all procedural animation.

In any case, it's very CPU intensive and difficult to tune procedural animations which is why you don't see everyone jumping on the bandwagon.

---
Tags: physics, procedural-generation
---


title: Why does UDK require .NET 4.0?

text:
# Question
Title: Why does UDK require .NET 4.0?
UDK engine requires that end-users install .NET 4.0, but what about Windows XP users?

Is there any way to get rid of that requirement, by perhaps disabling certain features?

# Answer
UDK requires the .Net framework *for the map editor* \- I assume if you don't package the map editor with your game you can skip this requirement; however, the UDK runtime installer will download an install .Net automatically (*"The UDK will install .NET Framework 3.5 Service Pack 1 if you don't already have it"*) - so you will need to install the UDK yourself (which is probably illegal). In other words you probably can't legally skip the .Net requirement. Overall this is not a problem for Windows XP users - and the .Net web installer that the UDK uses usually only downloads ~50MB (as opposed to the full installer which is well over 200MB).

The reason it works on iOS and so forth is because Epic Games have written a specific runtime that supports those targets; which obviously don't have the .Net framework requirement.
> 3 votes

---
Tags: udk
---


# Question
Title: Player moving up, is he jumping or climbing?
In a 2D physics-based platformer game that has ladders in it, how do you determine whether the player moving up is caused by a jump or him climbing a ladder, such that you know what animation to play?

And in general, obviously the direction vector is not enought to determine the animation to play: how do you also determine the cause of the movement (so you know the correct sprite to use)?

# Answer
I have a personal logic issue on a regular basis that you seem to be expressing here. It's that sometimes you're looking at the logic and programming from the wrong direction entirely. In this case, you seem to not be realizing that from the beginning you know which is happening, because of the logic code. You should already know, programmatically speaking, whether he's on the ladder or not.

Think about it (as I said, I often have this problem). The games logic should know you're on the ladder, supposing that you're being a smart programmer. For a better explanation, I have a file archive type, and wasted about an hour of a day trying to figure out how to get the size of the data and I never once stopped to think that, when I load in the file, I now know its size :P.

The reason why this relates so exclusively, is that you're looking at it as "Now that I'm in the air, how do I figure out if I'm on a ladder or jumping?"... When you should really think "I'm about to get in the air, but by which method FIRST, so that I can use it for the animations use."
> 15 votes

# Answer
The physics system neither knows nor cares why the player is moving in a particular direction. It is your game that caused the physics system to move the player that way, and it is therefore the responsibility of your game to keep track of that. The player entity should have some state on it that will tell if it is jumping, climbing, running, etc. You shouldn't be trying to figure this out based on what happened with the physics system.
> 6 votes

# Answer
Seems that what ever event that is triggered on the collision that sets the players vertical velocity could also be used to set a flag specifying what animation to use.

If you are using a 3rd party library that is too restrictive with what info it gives you it would be possible to surround the ladder with a rectangle and if the player moving up and contained in that rectangle then do the climbing animation.
> 2 votes

# Answer
When setting the jump velocity also set the characters state to STATE\_JUMPING. Doing this you always know in which state the player is in and can act accordingly by checking the players state.
> 1 votes

---
Tags: physics, sprites, movement, platformer
---


# Question
Title: Should I scrap my own leader board and go for the Facebook built in one?
Currently I'm rolling my own score and leader board functionality in my FB canvas game.
In my game, users can see what score they have, in addition I have a public leader board where everybody can see all scores from all other users.(I also have possibility for each user to set themselves as anonymous in the leader board, if desired)

But now I started thinking; why do I have my own leader board system? Facebook has this scores API and I started play around with it. It, of course, integrates well with Facebook, scores and achievement showing up in the ticker and what not.

But it seems that I can't let each user see a public leader board in much the same way I currently have it. But it do let the users see their friends score.
Let's face it, this is all what FB is all about, right? Friends.

So the question is; should i scrap my own leader board and go for the Facebook built in one (and skip the public part of it)?

My gut feeling says yes, but I wanted to hear what other thinks.

# Answer
I think there are two basic problems with a global leaderboard:

1. Cheating.
2. And from a design standpoint, what does it do for the game experience? I would argue it actually detracts from a player's experience, unless a global ranking is somehow achievable. When I finish playing a game for the first time, have a couple hundred points, and then get shown that the top 10 people all have scores above a million, it's not a motivator for me; it's discouraging. It's like an impossible goal. It benefits those 10 people's egos, and detracts from everyone else's sense of accomplishment.

Limiting the leaderboard or high scores table to only friends, though, negates both of these elements. As a player, if I cheat, I know that I'm just doing it to show off to my friends, so I have less of an incentive to cheat (and if I do, you the game designer don't care because it's not globally visible). And it's likely that my friends are of a similar skill level to me, so I feel like I can beat their scores if I try hard enough - and indeed I probably can. Which then motivates my friends to play the game some more to try and beat my score. Which creates more traffic to your game, which is what you want.
> 15 votes

# Answer
I'm a bit late to this question as I've only just started considering the same question myself. I've just launched a game on FB which we created a global leaderboard for, but it also has the option to display just the friends scores. The FB score and achievements API does look good, but I know for my own game (puzzle game) people absolutely want to see who is scoring well in the game across the network, and also what scores are possible. Also if you just make it friends only than unless each player has LOTS of friends who are all playing it, their leaderboard is going to look pretty empty, which I would argue discourages people from playing, for me the more scores people see being posted the bigger inventive for them to do well themselves.

The ideal solution is a global leaderboard and a local one.
> 3 votes

---
Tags: facebook, leaderboards
---


# Question
Title: How should I check if a player has completed an achievement?
I'm making an MMO game and I just got to a point where I need to implement achievements... How do I do that? The most straight forward thing to do would be to run this once every 100ms,:

```
for a in achievements
    for p in players
        if a.meetsRequirements(p) then p.completeAchievement(a)

```

But that just raises even more complications. For example, how do I check if the achievement has actually been completed? Do the players have custom properties on themselves just for a specific achievement? I did this kind of thing with quests, because they are mainly "collect 100 wood", so active quests on a player check that. Also, there must be a better time to check it, this would periodically slow my server down, I think.

# Answer
What you do depends on the nature of the achievement. Unless your achievements all fit a simple pattern (collect X number of Ys), you're going to have to special-case them to some degree.

Using a message-based communication system, you can provide hooks that makes the special-case coding localized. You can have certain actions fire messages to listeners who register themselves. Then your achievement code/script can just register itself with the appropriate listeners and do whatever testing is necessary to fire off the achievement.

You would have messages for the typical events you might want achievements to listen for. Things like "player has acquired item X" or "entity Y killed entity Z". This way, you can track things like how many Z's that the player has killed.

That's probably the best you can do for a system for achievements. It centralizes the code as much as possible, and puts the onus on the listeners for the actual achievement detection.

Also, it should be noted that, for centralized achievement systems (X-Box Live, Steam achievements), progress towards achievements is typically stored on the server. So for accumulation achievements ("perform task X Y number of times"), the achievement script just detects when X has been performed and bumps the server's count. For other kinds of achievements ("perform task X"), the server achievement is binary: either you have done it, or you haven't.
> 23 votes

# Answer
Depending on the nature of your achievements you could also introduce some kind of "marker achievements".

If you have for example 3 consecutive achievements:
Wood 1 - Collect 100 wood
Wood 2 - Collect 500 wood
Wood 3 - Collect 1k wood

Then it would make sense to just register an OnChange event for the first achievement until the player completed it. Upon completion you can register the next achievement object.

This of course requires design (or calculation) of an achievement dependency tree.
> 3 votes

---
Tags: architecture, software-engineering, mmo, strategy, achievements
---


# Question
Title: What is the best framework to develop games for Android?
I have an Android 2.2 device and I want to try to develop games for it.

I have three questions:

1. What is the best frame work to develop games.
2. Are there any good JavaScript ports or frameworks that let me develop to JavaScript and then to compile to Java ? ( or something like that )
3. Where do I start to learn how to develop for the Android?

# Answer
There are various tools you can use to make games such as marmalade or unity3d for android

However, the android UI system is the main barrier preventing you from just porting something across from java or c++ or whatever else. In any case, some stuff is just easier to do using the android framework rather than manually doing yourself in opengl-es or with your own drawing code (such as displaying and updating a text-string score)

Generally, I'd suggest having a play with making some simple apps that explore different UI elements of android, as well as following some of the tutorials on the ***ANDROID DEVELOPERS WEBSITE***. Then look more closely into whether it is easier to port some game over, use one of the above mentioned tools or try and do everything yourself using the android framework and java/c/c++

Also, android 2.2 you can use opengl-es 2.0 if you decide on 3D games. Otherwise higher api level will only impact on the game if you are trying to do something really specialist that only comes with a later api level
> 2 votes

---
Tags: android, java, javascript
---


# Question
Title: Alpha blending not rendering properly XNA 4.0
I'm trying to render a tree made out of 2 rectangles intersecting in the center at a 90degree angle. The texture has an alpha channel but which ever rectangle gets rendered second causes a weird problem with the transparency.

Here is my rendering code:

```
public override void render(GraphicsDevice gd, Camera camera)
{
    RasterizerState rs = new RasterizerState();
    rs.CullMode = CullMode.None;
    gd.RasterizerState = rs;
    gd.BlendState = BlendState.AlphaBlend;

    effect.CurrentTechnique = effect.Techniques["TexturedNoShading"];
    effect.Parameters["xWorld"].SetValue(Matrix.CreateTranslation(position));
    effect.Parameters["xView"].SetValue(camera.getViewMatrix());
    effect.Parameters["xProjection"].SetValue(camera.getProjectionMatrix());
    effect.Parameters["xTexture"].SetValue(m_texture);

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Apply();

        gd.Indices = m_indexBuffer;
        gd.SetVertexBuffer(m_vertexBuffer);
        gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m_vertices.Length, 0, m_indices.Length / 3);
    }

    rs = new RasterizerState();
    rs.CullMode = CullMode.CullCounterClockwiseFace;
    gd.RasterizerState = rs;

    gd.BlendState = BlendState.Opaque;
}

```

# Answer
It looks to me like depth write is enabled when you draw the trees. The problem is that whichever quad draws first lays down depth as if the whole quad was opaque, when it's not, due to the alpha-blended texture. When the second quad draws, parts of it are culled away that should be visible.

There are a few possible approaches to fix this, each with its own pros and cons:

* Disable depth writes while drawing alpha-blended geometry. This will fix one artifact while creating another: then the quads will blend together in whatever order you draw them, rather than in back-to-front depth order. Therefore you will have to sort objects and quads back-to-front yourself and draw them in the right order every frame to get correct results. This is expensive and is not always possible to get right, such as when you have intersecting quads.
* Switch to using alpha test instead of alpha blending. This makes every pixel either completely opaque or completely transparent, depending on whether its alpha is above or below a certain threshold, say 50%. You will get correct depth sorting but all the vegetation will lose the soft edges and have hard, pixellated edges instead, which looks worse (although antialiasing can be applied to these edges).
* A combination of both of the above: draw the geometry with depth write enabled and a fairly high alpha test, such as 80%, then draw again with depth write disabled and using normal alpha blending. You'll get correct depth sorting for the pixels that are above 80% alpha, which is most of them, plus the soft edges that alpha blending gives you, but if you look closely there will be artifacts where the soft edges are not depth sorted correctly, causing hard edges to reappear. These artifacts may not be very noticable, though, depending on your scene.
* Use a full-powered order-independent transparency technique, such as depth peeling. You can read about these on the web; just search "order-independent transparency". These tend to be very expensive, but they will give you correct sorting for every pixel with full alpha blending support.
> 5 votes

# Answer
Your problem lies in the Z-Buffer. When you draw transparent polygons, depth writing must be disabled to achieve correct transparency, or the polygons must be ordered back-to-front so they correctly overlap. But, since you are drawing a concave object (one plane intersects the other) and it has transparent and opaque sections, both of these methods can't be used.

What you are looking for is Alpha Testing, a GPU mode that performs the same operations as Depth Testing, but based on the pixel's transparency, not depth. By the syntax of your code, I assume you are using Riemer's tutorials, and he has written one about alpha blended billboards. That tutorial was made for XNA 3.1, and since RenderState.AlphaBlendEnable was removed in 4.0, you must use your own alpha testing shader or use the default one.
> 5 votes

# Answer
Thanks Nathan and r2d2rigo, the alphatest did the trick. And for the googlers the code that worked is:

```
    public override void render(GraphicsDevice gd, Camera camera)
    {
        AlphaTestEffect e = (AlphaTestEffect)effect;

        RasterizerState rs = new RasterizerState();
        rs.CullMode = CullMode.None;
        gd.RasterizerState = rs;

        e.View = camera.getViewMatrix();
        e.Projection = camera.getProjectionMatrix();
        e.World = Matrix.CreateTranslation(position);
        e.Texture = m_texture;

        foreach (EffectPass pass in e.CurrentTechnique.Passes)
        {
            pass.Apply();

            gd.Indices = m_indexBuffer;
            gd.SetVertexBuffer(m_vertexBuffer);
            gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, m_vertices.Length, 0, m_indices.Length / 3);
        }

        rs = new RasterizerState();
        rs.CullMode = CullMode.CullCounterClockwiseFace;
        gd.RasterizerState = rs;
    }

```

effect is an AlphaTestEffect that was cast to an Effect and back to an AlphaTestEffect
> 2 votes

---
Tags: xna, xna-4.0, blending
---


# Question
Title: can't get File Open screen to appear in Blender? (screenshot attached)
Just starting out with blender. Did something and now I can't work out how to get the basic File Open screen to appear. Have been trying for a while.

Anyone able to tell me what to do to get back to the basic File Open screen, i.e. the one at http://wiki.blender.org/index.php/Doc:2.6/Manual/Data\_System/Files/Open

Here's what I'm seeing:

# Answer
> 1 votes
This isn't really the place for this question. It's not really related to game dev. However, I'll try to help.

Under the file menu is an option called Load Factory Settings. I'd try that. If you can't get to the file menu, in the top left of your screen shot, under the red close button, there's a little cube. Click that cube, then select the "Info" menu. That should allow you to access the file menu. Otherwise, instead of the "Info" menu, open the python console and enter the following:

```
bpy.ops.wm.read_factory_settings()

```

Then, to save those settings so you don't have to reset to the defaults every time you start Blender. Go to File-\>Save User Settings. Or press Ctrl+U. This should save the factory default settings over your settings that went awry.

---
Tags: blender
---


# Question
Title: Creating a basic character skeleton from code
I'd like to have a procedural system that uses a string of data to create a 3d creature. The way I've thought to do this is to use the code to generate a simple creature skeleton (I'll get to the skin generation when I have time) so I can test different source data's effect on the structure produced.

How can i use a set of data to generate the simple 3d skeleton?

The code would have information used to show what type of bone it was(hierarchy), the bone length, and how the bone was positioned and use this to make the model. (At least in planning, I don't know how to implement it)

Edit: The goal is to create creatures of different forms and skeletons. The creation will be mirrored down the spine so both sides are the same.

I'd like it to be highly adaptable but I'd like to specify a max of 4 legs and 4 arms (8 limb max only 4 on ground for walking). Being able to create a basic structure for humanoids, quadrupeds, and mixes (like a centaur or biped with no arms) is the goal.

I've looked for how to create a model off of the code procedurally, looking at stuff like FRep isosurfaces and metaballs, but I'm stumped on how to make it happen. I decided any progress is better that none, so I'd like to get a generator for something like an animators skeleton example to make sure I can get working structures (and later have something to work with to begin working on the animation algorithm).

Sorry for the lack of information at first, I was trying to keep the question simple. If you have an idea for the creation of the structure(skeleton) or maybe even the form itself I'd appreciate the help. Thanks

# Answer
> 3 votes
If you're providing all the information for the bones, then really this is more of a importer isn't it? The code is not really generating any content, it's simply displaying the content you provide.

Start with the simple case of a single bone. Make sure your code can read the bone specifications and draws the bone correctly (starting out with simple lines would be easiest, perhaps colored differently at each end?). Then move to two bones, ensure they line up the way you want. Then try adding bones that are to be drawn symmetrically. You could probably define these bones to have specific properties like what kind of joint they have, and if they are mirrored across the body. You could do some things to help visualize the data, for example drawing ball and socket joints as a sphere, and elbow joints as a cylinder.

If you're planning on animating this, you'll need to do a *bit* of work there. Likely you'd want to use inverse kinematics. The book Game Programming Gems 8 has a section on creating a "Non-Iterative--Closed-Form--Inverse-Kinematic-Chain-Solver" a mouth full for sure, but nevertheless helpful.

Even with a IK solver, you're going to have a **very** difficult time creating procedurally generated animations for walking/movement. As @Patrick Hughes mentioned, Spore is a great example of this challenge. There's a nice resource called Real-time Motion Retargeting to Highly Varied User-Created Morphologies that should help you start to understand the undertaking you have ahead of you. Make sure you take a look at the PDF linked on that page.

That being said, if you created an animation system that could do this, you'd have no trouble getting a job :).

**EDIT**

I'll add more details on the actual drawing of the bones. First, let me define some of the details you'll have to keep track of, **for each bone**.

* **Bone start position** \- This is a 3D offset from the parent end position. For limbs and such, this would just be zeros, or at least small numbers, but it's better to have this information for things like ribs where the offset could be greater.
* **Bone line equation** \- I recommend starting out with straight lines, but you may want curved bones in the future (ribs, clavicle, etc). This information would include the bone length and direction. You'd use this information for calculating mid-point attachments to this bone.
* **Bone end position** \- This is a 3D offset from this bones start position. You'll need this for the starting point of some child bones. This can just be computed from the start position and the line equation. It's just nice to have to so you don't have to compute it every time you want it.
* **Bone connection type** \- There are at least one of these per bone, it could be a joint or something more solid like the ribs connecting to the sternum. You'll want this information at first to draw what the connection looks like, and maybe eventually to tell your animation system how this bone is allowed to move.

Your bones should be laid out in some sort of tree data structure. With the root bone (generally the hip or base of the spine) being at the root of the tree.

Start with the character position in 3D space. This is the starting point for all the bones, it's the root. Use this position as the offset for your first bone. The way the bones are set up, once you have the first position, you can calculate the start/end of every bone in the system. Once you have all the start and end positions of the bones in your system, you're ready to draw.

I'm going to assume you're starting with straight lines for bones.

Draw in whatever order you want, but you might as well parse the tree you already have set up. So start with the root bone, and draw it. This is as simple as drawing a line from start position to end position of the first bone. If you're not sure how to draw a line in your system of choice, I'd recommend taking a step back and deciding if you're ready for this project.

Continue parsing the tree and drawing lines from the start position to the end position for each bone. You may want to pull this information out into some other data structure for quicker drawing, but that's outside the scope of this answer.

I have to say though, from your responses so far, I think this project may be beyond your current skills.

# Answer
> 2 votes
From what I understood reading your question, I'm assuming you want to procedurally generate a character, given some arbitrary data. Eg. a given username will generate a unique creature for that user.

The way I would go about this is to extract a number from the username (by using something like a CRC sum, or some other form of hashing). Then use that number as seed for a random-generator.

As Byte56 already mentioned in his excellent answer, going for a fully procedural approach is going to be very hard. I think it might be simpler to have multiple basic skeleton setups that can be parametrized. So maybe you have an armature for two, four and six legs with some extreme setups. Eg. a humanoid with very short legs, one with normal legs and another one with very long legs.

Ideally you would have existing animation data for (at least) the extreme cases, so that you can interpolate/morph intermediate states from one extreme to the other.

If you then have a user-name, you would seed the random generator as described above and first do a random roll which basic armature to use. Then perform other random rolls to determine other factors, such as which "intermediate state" to use, "animation speed", "skin color" etc.

Even though this approach isn't fully procedural, it will still generate a unique character for every username (given that you have sufficient base-armatures and variations thereof). As long as you just use this to create creatures using a given input and don't allow the users to add more limbs (like in Spore), the outlined approach should be much simpler to implement than a fully procedural character-generator.

---
Tags: 3d-meshes, procedural-generation, content-generation
---


title: Picking objects with mouse ray

text:
# Question
Title: Picking objects with mouse ray
I simply want to pick a few spheres in my scene using the mouse-ray. I have implemented(copied most of it but with little understanding) a ray-sphere collision code. Also I have implemented the code for converting the mouse window coords to OpenGL coords. And constructed the mouse function. I have a ray class. In other words I have made everything, but sth isn't working...

So, there is the ray-sphere collision code:

```
bool Sphere::CheckRayCollision(Ray mouseRay)
{
     double discriminant, b;

     b = -DotProduct(mouseRay.GetOrigin(), mouseRay.GetDirection());
     discriminant = b * b - DotProduct(mouseRay.GetOrigin(), mouseRay.GetOrigin()) + this->radius * this->radius;

     if(discriminant < 0)
     {
         std::cout<<"disc"<<std::endl;
         return false;
     }
     discriminant = sqrt(discriminant);

     double x1 = b - discriminant;
     double x2 = b + discriminant;

     if(x2 < 0)
     {
          std::cout<<"x2"<<std::endl;
          return false;
     }
     if(x1 < 0)
     {
           x1 = 0;
           return true;
     }

     return true;
}

```

It is within the sphere class. The convertion between window and OGL coords:

```
Vector3d MouseClass::ConvertMouseToOGLCoordinate(int mouseX, int mouseY, int mouseZ)
{
    GLint viewport[4];
    GLdouble modelMatrix[16];
    GLdouble projectionMatrix[16];

    glGetIntegerv(GL_VIEWPORT, viewport);
    glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
    glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);

    //float winZ;
    float winY = float(viewport[3] - mouseY);
    //glReadPixels(mouseX, (int)winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    double x, y, z;
    gluUnProject((double)mouseX, winY, mouseZ,
        modelMatrix, projectionMatrix, viewport,
        &x, &y, &z);

    return Vector3d(x, y, z);
}

```

And the function which checks whether the left mouse btn is clicked and if it is checks for the collision:

```
void HandleMouse()
{
    if(userMouse.IsLeftButtonDown())
    {
        int cursorX = int(userMouse.GetCurrentPosition().GetX());
        int cursorY = int(userMouse.GetCurrentPosition().GetY());

        Vector3d nearPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 0.0f);
        Vector3d farPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 1.0f);

        Vector3d direction = farPoint - nearPoint;
        direction.Normalize();

        positionInWorld = farPoint;

        mouseRay = Ray(nearPoint, direction);
        drawCube = true;
        for(int i = 0; i < 3; i++)
        {
            bool isCollided = sphere[i].CheckRayCollision(mouseRay);
            if(isCollided)
            {
                sphere[i].SetColor(0.0f, 1.0f, 0.0f);
            }
            else
            {
                sphere[i].SetColor(1.0f, 0.0f, 0.0f);
            }
        }
     }
}

```

The 'drawCube' bool var is just for me to show if the convertion func works well and the 'positionInWorld' var is for the cubes coords. The drawing is well, so I think the convertion function works, but I might've done sth wrong.

If anyone can help me sort out why isn't this code working I would be very gratefull! I have been struggling with this for a week and searched everywhere on the Internet and haven't found a solution yet...

Thanks in advance!

**EDIT:**

The picking isn't working here. Pressing the left mouse button doesn't select anything. No matter where I click...

# Answer
> 3 votes
When I was debugging mouse picking in my game, I had it set up to draw a line from my camera to where ever the picking function ended. It lets you know if the ray is going the right direction, and if the ray is ending too soon, or too late.

In your case, I'd have it draw a line between nearPoint and farPoint. Make sure those are the rays you want.

I imagine you'll find that it's not working the way you want it to, and here's why.

```
Vector3d nearPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 0.0f);
Vector3d farPoint = MouseClass::ConvertMouseToOGLCoordinate(cursorX, cursorY, 1.0f);

```

That's **not** the way you want to get the nearPoint. The near point has nothing to do with where the mouse cursor is, it's about where your camera is. I created an answer a while back about picking: https://gamedev.stackexchange.com/a/12370/7191

You may want to look at how I get the ray in world coordinates.

Good luck!

---
Tags: opengl, mouse, raycasting, picking
---


# Question
Title: How do I create good looking plasma explosion effects?
Is this just a billboard quad with a bloom shader?

# Answer
> 10 votes
Although I think this is a very subjective question, the ways I can think of creating them are:

1. As you said, billboarding a plasma sprite and using a bloom shader
2. Creating a particle system and using a bloom shader (will look better than above, but takes more power)
3. Both, which by looking at the picture, I'm inclined to believe is the method used in that game. It uses a main explosion sprite and then some particles with an additive bloom shader for sparks.

---
Tags: opengl, glsl, first-person-shooter
---


# Question
Title: Detecting image curve to move a truck on this surface
I have an image background in surface view

I want to move something according to black surface.But i can not do this using height of this image as it return same height.and one more thing bitmap.getPixel is also not working.and my background is moving.So what is the way to achieve this feat

# Answer
> 4 votes
To answer the question directly - you need to extract the gradient of the surface from the image. The image pixels need to be analysed using an algorithm such as marching squares. However there are two problems with this approach:

1. Image analysis uses up valuable processing resources
2. The result will only be an approximation of the surface

A better solution would be to not use an image in the first place, but to rather keep the path as a vector and use that to render the curve at runtime.

**Update:**

Consider using a pre-existing physics engine, see here for some references: https://stackoverflow.com/questions/1034253/are-there-any-decent-physics-engines-for-android

# Answer
> 3 votes
If I understood right, you need a "raster" background image to display and a gemetric shape that describes that background's silhouette for physical simulations issues.

Looking at your example image I can see a bezier profile so you may store the parameters you used to generate it, along with your image; is up to you to store the rasterized version or use the bezier parameters to generate the displaying image (cpu vs storage trade-off).

The interesting case comes if your background shape does not come from a bezier curve or from an equivalent parametrization: and hand-made artwork for example.

I such cases you may find this paper useful. Here is shown how to get a bezier parametrization from an hand-drawn sketch.

They basically illustrate the process with the following steps:

**1** \- apply a logarithmic transformation to make it easier to extract the edge.

**2** \- erosion - dilatation is used to smoth the image

**3** \- laplacian is applied to find out the edges

once they get the edges, as set of points laying on the shape edge, they start to construct a set of (bezier) curves each of which produces a better edge approximation.

**4** \- the set of edge points are grouped and for each group a regression line segment is computed

**5** \- using the intersection of the line segments in the step **4** a set of bezier 2nd grade curves are computed

**6** \- a method to generate 5th degree Bezier Curve is given: the curve is derived from that obtained in the previous step by letting the derivate and curvature discontinuities be smoothed.

All these steps are obviously computationally relevant and are not intended to be done at runtime.

This should not be a problem since you do not do dynamic backgrounds, if you do so you should have some parametrization and the problem solved in (moved to) an earlier phase of the project.

---
Tags: android, collision-detection
---


# Question
Title: Do you need resource manager for HTML5 games?
Usually, resource manager is needed for desktop/mobile games. But is it needed for HTML5 (browser) games?

Resource manager's main responsibility is to make sure there is no clone of a resource in memory. But in browser, when you request something, the request is usually cached. So when you make another request to the same resource, the resource is not loaded anymore. You immediately get it. (CMIIW).

So, do you need resource manager for html5 browser games?

Thanks.

# Answer
> 6 votes
Unless you go beyond what can reasonably be stored in memory you don't need an advanced resource manager. That is true for desktop games as well, most "small" games get away with just loading everything into memory at launch, and then it's there when needed.

In HTML and JavaScript you don't have direct control of resources in the same way, the browser has a built in resource manager working for you. However, it may be a good idea to help it a bit in order to achieve having all images loaded at launch and preventing them from getting unloaded when not in use.

For this purpose you can create a bunch of image elements and attach the needed images to them, this will cause the images to get loaded and stay in memory. You don't even need to attach them to the document, they can simply exist as virtual entities in your script.

Here is the loading part of a game I wrote. It loads 27 images in the manner described, it continually checks if they are all loaded along with the document body, it displays a counter to the user telling how far the loading has progressed and finally calls a function to render the menu when all assets are loaded.

```
<body onload="bodyloaded=1">
<div id='maindivid'>
<p id='loadtext' style='text-align:center;'>
Loading 0/28
</p>
</div>
<script type="text/javascript">
bodyloaded=0
prlimg=new Array
for(a=0;3>a;a++){
prlimg[a]=new Array
for(b=0;3>b;b++){
prlimg[a][b]=new Array
for(c=0;3>c;c++){
    prlimg[a][b][c] = new Image
    prlimg[a][b][c].src = a+(b+(c+".png"))
}
}
}
function updateload(){
    elementsloaded=bodyloaded
    for(a=0;3>a;a++){
    for(b=0;3>b;b++){
    for(c=0;3>c;c++){
        elementsloaded+=prlimg[a][b][c].complete
    }
    }
    }
    document.getElementById('loadtext').innerHTML="Loading "+elementsloaded+"/28"
    if(elementsloaded==28){menu()}
    else{setTimeout("updateload()",100)}
}
updateload()
</script>
//Further code goes here
</body>

```

See the code in action.

When I look at it again there is a couple of things I could have done differently, but it should suffice to demonstrate the functionality.

---
Tags: html5, assets, resource-management, asset-management
---