# Question
Title: Pathfinding for a lot of units, mostly random movement
I'm using a uniform cost eight-directional grid as a map, with buildings that represent unpassable terrain - the map tries to simulate a top-down flat city. I'm trying to fill the city with randomly walking citizens, and with player units with controlled paths.

So far, for the random walking I've just chosen a direction and set a direct line on it ( using berensham's line algorithm), until the unit strikes a wall, but even this slows down the game with 200 units, and that's before more complex routes are looked for by the player.

So, I need:

1. An algorithm to quickly compute a lot of simple routes.
2. A good pathfinding algorithm - so far I've read about HPA\* and A\* with JPS, but to both I haven't managed to find an implementation, which is a problem because the articles are a bit too theoretical for me.

For illustration, the situation is somewhat similar to the movement in Atom Zombie Smasher - there are uncontrolled civilians that walk randomly / run away from a threat, and few player units that walk on prescribed paths, only in my game the player can't affect the path mid-walk.

So, to summarize - I'm looking for a system for pathfinding for a couple of hundred of units which is as quick as possible.

# Answer
> 4 votes
You may want to look at flocking systems. This way you can just calculate paths for a few objects and have others follow them instead of the path.

You can also check out this link to help you create a basic implementation of the A\* path-finding algorithm.

# Answer
> 2 votes
If the civilians just need to walk around randomly, I wouldn't have them "think ahead" at all. Simply pick a random direction for each civilian and have him walk in that direction until he bumps into something or a certain amount of time passes. That makes it a simple "for p in players: p.pos += p.direction" each frame, which you're doing anyway, with no complicated algorithms. Direction would just be a vector/2-item list representing a move in one of your eight directions.

Of course, that won't work for your soldier units if the player is going to set patrol routes. A\* is the algo of choice, though I'd only compute one route a frame. Just set up a queue of routes to be computed and grab the top-most one each frame to maintain performance.

Amit's Game Programming has some great links to A\* articles which will help you grasp the theory. This one is especially good. Surprisingly, though, the Wikipedia article on A\* has the best pseudocode!

# Answer
> 0 votes
I can't understand how moving 200 units around could slow down any modern system... I guess you need to revise your algorithms.

How much it "slows down" of course depends on the frame rate or logic tick-rate. I don't see an advantage for most games (e.g. RTS) of running at a tick rate of \> 20/sec. If you want to render more frames than that, you can just use interpolation (which is a good idea anyway, it frees your logic speed from your rendering).

You say "using bresenham's line algorithm", but this is for drawing pixels in lines. Is your game really entirely tile-based - can characters never occupy spaces between tiles?

Normally I'd be tempted to just set a destination for each character, and walk towards it in a straight line (turn towards it, then walk straight), then set another point. Doing this is a very simple piece of vector maths.

But that pre-supposes that your characters can actually be at any point in space.

---
Tags: c#, path-finding, rts
---


# Question
Title: Distribute XNA as a standalone zip or exe (no installer needed)?
I want to know how would I distribute my XNA such that it won't distribute as an installer/setup files? I just want a zip of files such that when the user can run instantly after extracting into a folder. I am making a small prototype of some functionalities, and I would like my co-workers to visually see it so that we can communicate better. However, this must means I must frequently release my projects (as I update it frequently), so I want to know a way to produce easy-to-launch distribution.

I tried to turn Build option in Visual Studio to Release, and try copy and zip all the files inside Release folder. However, when I zip it and send to my coworkers, they said nothing comes up after they open the exe.

# Answer
Your co-workers need to have the .Net Framework 3.5 and the XNA Framework 4.0 installed. I don't think there's an easy way around that. Get them to install these first, then you can distribute the exes in a zip file with no problems.
> 5 votes

---
Tags: xna, distribution
---


# Question
Title: Can you access Kinect motion sensing from XNA?
As of 2010 with the release of XNA 4.0, if I buy an Xbox 360 with Kinect will I be able to access its motion sensing data with the XNA game I'm developing? Or is this only restricted to C++ developers with a devkit?

# Answer
> 17 votes
> "The non-commercial Kinect SDK for Windows will be released this spring, Microsoft said, and a commercial version is planned for a later date. The company said the SDKs will include support for audio, the Kinect API and direct control of the sensor."

That being said, if you don't want to wait, there's a lot of work being done on several fronts with support for a number of languages (C++, C#, Java, JavaScript, ...) under Windows, Mac and Linux.

For the freshest 0-day Kinect hacks, read KinectHacks and FreeNect

If you want to get started writing code, have a look at these:

* Code Laboratories released **CL NUI Platform drivers** for the Kinect, which also includes samples in several languages including C#. The latest 1.0.0.1210 seems to not work ATM, so maybe stick to the older version (1.0.0.1121).
* I got started in minutes using the KinectTouch C# project together with CL NUI drivers.
* For motion detection, check out the **haar detection** function inside **OpenCV** or the cross-platform .Net wrapper Emgu CV. Included are about 20 detection algorithms (XML files) for detecting e.g. hands, eyes, upper-torso, etc. A tool is also included to make your own. Google *haar detect* for more info.
* The OpenKinect project is in charge of **libfreenect** and has sample source code to get you started. AFAIK you will have to use libusb-win32 to interface to the Kinect (which I was too lazy to get working in C#).
* OpenNI just released an updated driver with Kinect support including sample source code for **skeleton tracking** using their **PrimeSense PSDK**.

# Answer
> 9 votes
http://www.computerandvideogames.com/article.php?id=258873?cid=OTC-RSS&attr=CVG-News-RSS

Looks like for the moment it's only for select Microsoft partners.

# Answer
> 2 votes
**Kinect for Windows SDK Version 1** is now out (since February 2012) and includes commercial support, raw sensor streams, skeletal tracking, and a number of other improvements:
http://www.microsoft.com/en-us/kinectforwindows/

# Answer
> 1 votes
I asked the Team XNA about this a few weeks ago and they told me that currently that will not be available via the XNA Framework.

I´m sure they´ll open the Kinect development some day, I just don´t think that will be soon.

# Answer
> 1 votes
Latest news is that Microsoft will be coming out with a no0n-commercial version of an SDK for Kinect in Spring.Below is the link from Microsoft.
http://research.microsoft.com/en-us/news/features/kinectforwindowssdk-022111.aspx

# Answer
> 1 votes
This question is tagged Xbox360. While the current version of the SDK (v1-M6) is compatible with XNA, it is windows only, sadly you will have to wait for XBox support.

# Answer
> -1 votes
It should be able to now. They have devolped a driver pack and they did it with Windows 8 in mind. I can't think of what it's called but if you go to Microsoft Dreamspark it's in there. I just saw it earler hope that helps.

---
Tags: xna, xbox360, motion-control
---


# Question
Title: Tile map/terrain implementation with differing heights of neighbouring tiles
Ahoy!

I'm looking for some information about tile maps, or rather, what a specific type of tile map is called.

I'm interested in the kind of implementation used in rollercoaster tycoon, or the transport tycoon series of games and have been looking into vector field terrain and height map terrain but i'm not sure they're suitable for what i'm looking to develop.

It's been a struggle to find any decent info as most people refer to it as an isometric tile map, but I'm looking to create something in 3D with a fixed orthographic perspective. I understand that the underlying storage of the tile map has nothing to do with how it is rendered but i'm not looking to create a 2D tile map like old school pokemon/zelda games, more along the lines of diablo with the capability to include overhanging cliffs and sloping terrain.

I'm just trying to find the right terms to search google and stackoverflow for resources to help me decide which path to proceed.

So far i've managed to flesh out a basic tile map without using the height/y component stored in a VBO and rendered as a wireframe. This looks fine so far but I envisage that I will encounter problems when trying to manipulate a single vertex to create cliffs and slopes without affecting a neighbouring tile.

Is there a specific type of implementation I should be looking into? I thought i'd cracked it when I found a fair amount if info on vector field terrain but i'm not sure this would yield the correct results either.

If anyone can shed some light on this for me please, the help would be greatly appreciated :)

**Update**

I've included an image for further clarification as to what i'd like to achieve:

Image borrowed from How to create tilted (height) isometric tiles

This image shows the type of terrain i'd like to generate but doesn't include the "cliffs" or overhanging terrain types i'm interested in modelling. It does however raise a few other questions I hadn't considered, namely;

* How would 'layers' such as the water (top left of the image) be handled to include the visible ground underneath the water?
* How would the "edges" of the map be catered for so that the earth/mud is rendered to depict the world as a non-flat entity?
* Could the underlying storage for this kind of terrain be used to model physics such as a ball rolling down a hill or movement speeds of a player traversing a slope?

I had an idea in that each tile of the terrain could be modelled with 8 vertices where the 4 main vertices cover the actual tile itself and the remaining 4 vertices are used to model the sides/walls of each tile. The two problems I see with this implementation is that a) the world map is essentially doubled in size and b) given that not all tiles will include "walls", some tiles will end up with redundant vertices which are not used.

I'd like to create a terrain editor which allows for each tile to be deformed as well as including the ability to change the terrain during game play. This in itself poses additional questions such as; Can a VBO be used to store and render the terrain whilst being modified on the fly and also, is it possible to modify vertices without affecting neighbouring tiles?

I'm under the impression that i'm either over-complicating things or running into analysis-paralysis in that i'm neglecting to write any code to solve the problem without having a clear idea of how I would achieve what I want.

Again, i'm really just looking for a shove in the right direction with this. Is there a specific type of tilemap/terrain implementation that would cater for a 3D map to be deformed by both a map editor as well as during gameplay or do I have to roll my own, so to speak? I'm not trying to reinvent the wheel here but I am struggling to find any resources given that I'm not sure what to be searching for.

If anyone can provide any info, resources or snippets of code, that would be hugely appreciated as i'm eager to get my hands dirty and start producing something other than the flat wireframe I currently have.

Thanks for reading!

# Answer
> 2 votes
If I were you I'd look into voxels, more specifically Minecraft-type cube rendering. Unlike heightmaps, they can handle overhangs, caverns, buildings with multiple floors, etc.

You'd store your terrain in a 3D array of integers, where numbers are mapped to a certain type of terrain: 0=air, 1=dirt, 2=water, etc. Then, to create the mesh to render, you'd create the faces of a cube for each non-empty voxel.

This tutorial is a great explanation of how to do this in C++ using Ogre3D. I presume you'd have to go a little more low-level in OpenGL.

After creating the cubes, you'd want to smooth the edges to create the kind of fluid terrain shown in your image. I believe PolyVox (also in C++) does this; you could take a look at their code. I think you basically do in 3D what the image shows in 2D: average the surrounding cube positions to know where to place each vertex.

**EDIT:**

* Generate the faces for the cubes adjacent to water as if the water tile was empty, and render the water faces transparently.
* Faces on the "edge" can be generated just like regular faces, if you consider voxels outside the world to be empty.
* Physics: You can probably feed the rendered mesh to your physics engine as a static object.
* Map editor: You'd want to edit the underlying voxel data, not the mesh itself! (The mesh should mirror the data, so editing the voxels should produce changes in your mesh.) You might want to look up Model, View, Controller (MVC) if you're not familiar with it.

If you have more questions, feel free to leave a comment. Welcome to gamedev.SE!

# Answer
> 6 votes
This: http://30.media.tumblr.com/tumblr\_m06qv6OREt1r2qjpao1\_500.png is an example of a map I've done some time ago.

I had a XML representing the map and different types of tiles. Each type would have a few attributes:

* Height
* Position
* Merge Type: Which kind of merging this tile would do, `ALL` (if it should merge to any tile around it), `EQUAL` (only merge with tiles of the same type), `NONE` (never merge).
* Merge Height: The max height for slopes (good for overhangs), let's say you want a tile to merge only with tiles on the same height or a difference of 1, the value would be one.

I would then read all the tiles and create them in the scene. First only taking in account the position. Each tile had to know it's neighbour so I had to go through the map twice, once to create everything, and once more to move each vertex to the right position.

Though my models are hexes, the concept is the same, you would need a cube to represent your tile, you would then move the base vertices to the lowest level and 'smooth' the top of the cube with the cubes around it. You would also check if two sides of the cubes were merged so you can just remove that side from the cube (if they are not merged it's probably a cliff or something).

About physics, depends on your goal. If you're doing something like rollercoaster tycoon you don't really need them. You could just check the player height between each tile and decide the walking speed. You could do the same for a object that moves by itself (like the ball), you could check the tiles around (or the current tile angle) and decide a direction/speed. If you need realistic physics (like gravity, friction, etc) you would have to use a physics engine, and you could use the cube 3D representation in the engine.

Layers are also possible, but you would need something like minecraft (with smoothing on the cubes in the highest layer). If you only need layers for water, you can have a "water spring" on a tile and have your code fill every space around it that is at the same height or lower (a recursive solution would fit here nicely).

A terrain editor would also be simple, if your code is flexible enough, you can apply the transformations to a single tile (the one you're changing), or to a list of tiles (if you're using a 'brush' to select and move them). The same code can be used to modify the terrain on the game. And yes, you can change the vertices on the VBO, it's also possible to change vertices without affecting other (it also depends on you coding like that).

---
Tags: opengl-es, terrain, tilemap
---


# Question
Title: How do I check to see if a tile corner is visible in 2d space?
I am trying to implement fog of war, and I have run into trouble. I want to check to see if the player is able to see the corners of each tile within a certain radius, however I am unsure how to check if the vision of the corners is to be obstructed or not. Is there a quick way to do this? I used a system of drawing a line and checking if the tiles the line is on are solid blocks in a rougelike, but I am unsure if this method would be suitable, as it is possible to see parts of a tile, unlike in a rougelike where it's a yes or no type thing.

For example, the black tile is obstructing the view partially of the white tile.

The red lines signify that the player is able to see the corner, while the blue signifies they can't (as the black obstructs it).

# Answer
> 3 votes
To flesh out Nick's answer a bit: the core concept behind the DDA algorithm (which works just as well in three dimensions) is that for each axis of your grid you keep track of the next 'crossing point' for that axis in terms of your line parameter; each step of the algorithm consists of finding which axis has the next crossing point (which is a simple compare in two dimensions), taking the appropriate step, and updating the next-crossing values for each axis.

The line here can be written as '(x,y) = (x0,y0)+t\*(m,n)', where m=x1-x0 and n=y1-y0. If the dimensions of a grid cell are gx and gy, then dx — the distance (in terms of the t parameter) that it takes to cross one grid cell — can be found with a bit of quick algebra: from the pair of equations x = x0+m*t, (x+gx) = x0+m*(t+dx) we get gx = m\*dx, or in other words dx=gx/m. Likewise, dy=gy/n. The algorithm keeps track of next\_x (the distance to the next red point along the line) and next\_y (the distance to the next blue point along the line) and updates them every time it hits another crossing, so the central loop looks something like this:

```
while ( cur_t < t_max) {
  if ( next_x < next_y ) {
    cell_x++;
    cur_t += next_x;
    next_y -= next_x;
    next_x = dx;
  } else {
    cell_y++;
    cur_t += next_y;
    next_x -= next_y;
    next_y = dy;
  }
  // Process the cell (cell_x, cell_y)
}

```

Note that this code is missing a lot of the details - it doesn't tell you how to initialize next\_x and next\_y, for instance. There are ways of eliminating most of the divides, making it easier to handle special cases like vertical and horizontal lines. Whether you increment or decrement cell\_x and cell\_y depends on which quadrant your line is in - note that for my example line, you'd actually be *decreasing* cell\_x each tick, since m (x1-x0) is negative. You also have to decide how you're going to handle cases where your line goes precisely through the corner between cells, rather than transitioning on an edge; there are lots of small details that can go wrong, and it needs a lot of testing. Still, hopefully this will give you a picture of what the core idea of the algorithm is.

# Answer
> 1 votes
John Amanatides & Andrew Woo's DDA (Digital Differential Analyser) algorithm provides what you need. I'm on mobile so tedious to grab the link without closing this page. DDA is O(n \*m) where n is the number of tiles to be walked along a ray/angle, and m the number of angles.

If you need to check whether smaller parts of the tile are visible further (finer detail), you can split each tile into a separate grid and perform DDA checks at that level as well.

The only substantially different alternative I can see is raycast scanning (line-line intersection checks) which is O(n * m) with n being the number of tile edges within the area of interest, and m being the number of discrete angles you test for in each circular sweep (implying that even with this approach, there still exist issues of resolution). Since there are multiple edges to each tile, DDA can be seen to be more efficient.

One final approach that comes to mind is to adapt raycasrt scanning by setting an individual ray angle up for each individual grid intersection within your limited area of interest. This way you can determine exactly where occlusion occurs within you grid (since occlusion lines always pass corners) although you would need to substantially restrict your area of interest lest the number of interstitial points defining your ray angles were to get out of hand.

---
Tags: 2d, tiles
---


title: Render a polyline with rounded joints

text:
# Question
Title: Render a polyline with rounded joints
I have a list of points (3D) and want to draw a line connecting all points with a specified width. The line should be rendered in OpenGL (using OSG) as triangles. The real challenge of this task is to make the line look "pleasant" for the user; meaning the joints should be round.

It should be similar to this:

Is there any library which brings this functionality?

# Answer
I'm not sure you should go through the burden of using a library just for rounded joints. You could draw thick lines with discs at the intersections, i.e.:
> 6 votes

# Answer
In the CAD world a rounded corner like you describe is called a **Fillet** while a hard angled transition is called a **Chamfer**. Since you are dealing with lines, which is a CAD specialty, see if anything here: Discussion on CAD libraries has something you can use.
> 0 votes

---
Tags: opengl, 3d, geometry
---


title: Minecraft custom name laucher

text:
# Question
Title: Minecraft custom name laucher
I'm trying to create a custom name laucher for Minecraft. I run an offline server and was wanting to give some of my friends a laucher to use so they can play. I have done this before with a batch file. Now I'm using JavaUI and I'm trying to start Minecraft from the Java program. I have yet to get Minecraft to pop up.

Here is the code i am using:

```
if (e.getSource() == app.startNorm){
    List<String> command = new ArrayList<String>();
    command.add("java");
    command.add("-jar");
    command.add(System.getenv("APPDATA") + "\\.minecraft\\bin\\* -Djava.library.path=\"" + System.getenv("APPDATA") + "\\.minecraft\\bin\\natives\" net.minecraft.client.Minecraft CustomNameHere");
    try{
        //line below wont work
        ProcessBuilder builder = new ProcessBuilder(command);
        Process proc = builder.start();
        app.setSize(500, 300);
        app.process.setVisible(true);
        app.memory.setVisible(false);
        app.start.setVisible(false);
        InputStream in = proc.getInputStream();
    } catch (IOException e1) {
        //always get dialog, when not never see minecraft pop up
        JOptionPane.showMessageDialog(null, "There was a problem with starting Minecraft");
    }
}

```

I was hoping someone could show me how to get this, or any other way to lauch Minecraft from inside my program.

# Answer
> 4 votes
I made something similar in the past, here is the code i used:

```
Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c java -jar filename.jar");

```

or

```
rt.exec("cmd /c filename.exe");

```

---
Tags: java, minecraft-modding
---


# Question
Title: How can I add a parallax effect into my side-scrolling game?
How can I add a parallax effect into my side-scrolling game? I read a lot about parallax scrolling so I know what the logic is and what parallax is but I can't create a dynamic parallax effect.

I have draw and update functions like this:

```
void UpdateBackground(Background &back)
{
    back.x += back.velX * back.dirX;
    if(back.x + back.width <= 0)
        back.x = 0;
}
void DrawBackground(Background &back)
{
    draw_bitmap(back.image, back.x, back.y, 0);

    if(back.x + back.width < WIDTH)
        draw_bitmap(back.image, back.x + back.width, back.y, 0);
}

```

So this draws a parallax effect with two background objects but it draws it statically. I'm creating a 2D side-scrolling game and I'm translating my character and my camera position along x axis. So I have to translate my parallax effect with my camera but when I add to background `position.x` it doesn't work. How can I solve this?

# Answer
Parallax backgrounds are divorced from reality, you don't need velocities and directions. What you do need is to base the background's X on the camera's position and modified with multiplier to offset the background more slowly so it looks like it is very far away. Different layers of background can look closer by making this magic number bigger, so instead of 0.1f for far away use 0.3f for up close, etc...

An example might look like:

```
void UpdateBackground(Background &back, float cameraX)
{
    back.x = cameraX * 0.1f; // magic number to make the background move slowly
    back.x = fmod( back.x, back.width );
}

```
> 5 votes

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


title: Scrolling Text in jMonkey

text:
# Question
Title: Scrolling Text in jMonkey
I am looking for a way to include scrolling text boxes in a jMonkey game. I have, of course, looked around online and could not find any examples or libraries that fit.

My goal is to have "quests" pop up for the user in small graphical boxes, containing quest text. The quest text might be longer than the quest box (which was easy enough to generate in jMonkey), so I am left with the problem of generating scrolling text boxes.

Before I set off on a long venture to properly adjust, indent, and scroll text inside boxes, I was wondering if any knew of existing examples or libraries. I have a hard time believing I'm the first person to using jMonkey that needed scrolling text or quest functionality.

# Answer
> 1 votes
The Nifty GUI library is a pretty nice one. It plays nice with JMonkey (as well as others) and is fairly easy to use. Just this morning I set it up to reload the XML file with the click of a button. This allows me to rapidly prototype my GUI by modifying the XML and reloading without needing to restart my game. It also supports custom loaders, so you can ensure all your content gets loaded the way you want, or even support user generated mods to the UI. All-in-all, it's flexible and powerful.

---
Tags: jmonkeyengine, text, quests
---


title: Advice on OpenGL 2.1

text:
# Question
Title: Advice on OpenGL 2.1
I'm looking to finally get into OpenGL to bring some game ideas of mine to life! As I want to aim for lower class systems I'm probably looking at OpenGL 2.0/2.1 using JOGL (as I know Java the best).

Could anyone suggest some good books or resources as the books I have found so far talk about OpenGL 3 or 4! I read that the OpenGL Superbible is a good book and it seems the fourth edition covers OpenGL 2, can anyone recommend this? Obviously I would have to convert the examples in any book to use JOGL as I assume most books are C/C++.

I know I probably should be learning 3 or 4 as there are lots of changes, but I'm not looking for cutting edge graphics, just simple things (plus I would like to port to Mac / Linux as it is Java).

# Answer
> 1 votes
Start with a game engine. You very likely won't wan to start with straight up gl. It will take for ever to actually see anything, on top of the fact that you will have a lot of rewriting to do for sequels. Look at JMonkeyEngine or something similar.

Here is a list of engines (not exclusive to java). http://en.wikipedia.org/wiki/List\_of\_game\_engines

# Answer
> 1 votes
I've had horrible performance experiences with JOGL, LWJGL always performed better, was more consistent, and reliable (also more actively developed).

---
Tags: opengl, 3d, java, jogl
---


title: Client Server UDP Jumping

text:
# Question
Title: Client Server UDP Jumping
I don't really think this is an issue with the fact that UDP can drop packets (I'm using Lidgren and using ReliableInOrder), but basically, in my game, the client send the input keys (if forward is prsesed, backward is pressed, etc)

Now, when lag occurs, it's not noticeable at all if the packet that says "I'm pressing forward" right now is behind schedule, because I have interpolation. However, it's really annoying when you press the space bar (jump button), and nothing happens because the packet was dropped and Lidgren needs to resend it.

How can I fix this? Please keep in mind that the server controls all position data to prevent hacking, so I can't just make jumping client-sided and send the position.

Thanks!

# Answer
Your client should always assume the server will OK the input. The server should only send corrective position/orientation when the client seems to have moved suspiciously. Hopefully I didn't misunderstand how your client and server are communicating.
> 3 votes

---
Tags: xna, c#, networking, multiplayer
---


# Question
Title: Is there a problem with using a 2D square grid for your world map?
I'm making a game with a 2D square grid for my world map. It wraps around, so when you reach all the way north you start out in the south again, and when you go all the way east you wind up in the west, etc.

Would this method have any flaws? I'm under the impression there might be flaws around e.g. fast travel.

# Answer
Using squares for a map that's supposed to represent a planet, just be careful you don't end up representing a toroid. When I was first trying to think of a tile system where the user walks over the top and bottom and both sides were wrapped thinking to myself that that would work fine only to have my cousin point out this obvious defect in my plan XD.

In the end I settled with top and bottom being blocked and wrapped on the sides. That's the only issue that I've bumped into with squares, even though it's not dependant on squares, just one of those things that might not be immediately apparent.
> 4 votes

# Answer
One inherent problem is that if you allow diagonal moving, like a bishop in chess, the unit will move further than a unit moving orthogonally.

This might be a problem if you combine your grid movement mechanics with other mechanics that use "as the crow flies" distance.

So for example, if you are running away from a unit who shoots x meters, and you can move y squares per turn, you would get further away if you move diagonally.

If your grid is 1 meter, moving orthogonally you will move 1 meter, but moving diagonally you will move 1.41 meters.
> 1 votes

---
Tags: 2d, maps
---


# Question
Title: Is there a way to setup an Android game project with a large assets during development to allow for fast testing/iteration?
I'm working on an Android port of an iOS game at the moment. I am using the Android NDK only (android\_native\_app\_glue) in Eclipse (CDT + ADT). I am using the Android emulator, API 15 (but we are targeting API9+) as we do not yet have an Android device. The game has about 200-300mb of assets and I'm unsure of how to include them properly or how to get into a fast testing/debugging cycle with assets attached.

As it stands I am linking the assets folder in my Android project to the resources folder that contains the game assets. This works but the problem lies in the fact that when I build it takes about 9-10 minutes for the 200mb .apk file to be installed onto the emulator. This is simply unacceptable when things need to be tested quickly.

If I strip the assets out of the project, it installs very quickly. Because of this I am stripping out the bulk of the assets at the moment to do my testing but when it comes to the long run I need a better solution.

My question, is there a way to setup an Android game project with a large asset collection during development to allow for fast testing/iteration? E,g. fast deployment or updating of .apk to allow for quick testing.

# Answer
> 4 votes
If your assets don't change frequently, then upload the the assets to some folder on sdcard. Then read your assets from there.

And if you assets change, you can easily make small script/batch file that uploads only modified files. Then run this script each time before running your app.

---
Tags: android, assets, testing, configuration, ndk
---


# Question
Title: How does an AI determine the bearing to follow within a nav mesh?
I've done some reading on nav-meshes, and I understand how to generate a path of polygons to reach a goal. However, what I don't understand is how you determine the bearing to follow within each polygon. Without a central node to aim for, what do you aim for? I suppose you could cast a ray to the goal and then head to the point where that ray crosses into the next cell - but that would only work if that next cell is actually on your path. If your ray doesn't cross the edge into the next cell, do you instead plot a path to whichever corner of the edge is closest to the goal? I think that would get you the path shown in the 3rd diagram, but would it work in all cases?

http://udn.epicgames.com/Three/NavigationMeshReference.html

# Answer
> 3 votes
You say you know how to generate a path of polygons to reach the goal. Then you must also know the edges you will cross, and may use this to build an actual walking path. A simple way of doing that would be to use the center of each edge as a waypoint, which gives you a functional but not very pretty curve to follow.

There are a few different ways to make it prettier. I usually "relax" the curve (not sure what the correct terminology is here) by, going backwards from the goal, moving the waypoints along their corresponding edges to minimize the distance to the next waypoint. I.e. the last node before the goal is moved to minimize the distance to the goal, the next-to last is moved to minimize the distance to the last waypoint, and so on...

Finding the point with the minimal distance is equivalent to projecting a point (the goal/next waypoint) onto a line segment (edge). Stack Overflow has a few answers on this, Shortest distance between a point and a line segment for example.

Note: this assumes that all navmesh polygons are convex (which they should be and hopefully are) because then we can exploit that, by definition, all paths between to points on the edge are entirely inside the polygon. Meaning we don't have to care at all about making sure the path is valid when moving the points on along edges (this time assuming obstacles are handled elsewere).

---
Tags: ai, path-finding, navmesh
---


# Question
Title: Character jumping movement in isometric tile
When I want to draw my character moving from one tile to another, I would find the displacement vector between two tile's drawing offset and let the character walk in a linear line toward that direction until it complete this displacement vector. Now, I want to make my character jump from higher/lower tile to lower/higher tile. I have a drawing location (x,y) for the texture, start and end. However, I want it to motion like a projectile, not a linear line. Therefore, given 2 point, start and end point, how would I motion my character in a jumping motion form (maybe it's a parabolic form)?

# Answer
From what I gather, your character movement is on tiles only, and you have a fixed animation length, something like a Tactics game?

What I would then do is to simulate a stationary jump, and combine it with the existing walking logic. Implement a simple gravity system, if you haven't already. When you want the character to jump, you simply give him an certain upward velocity vector negative to the gravity vector, and on each frame, subtract the gravity vector from a character's speed vector, until the character hits the ground again. Now you have a natural-looking parabolic jump made easy, because that's basically how it works in real life (under Newtonian laws).

Now, to jump from tile to tile, the moment you start jumping, apply the forward (horizontal) movement as you already can do. Displace the character sprite by the same vector as without jumping, and at the same time, also displace him according to a static upward jump, depending on his current upward vector. The jump and move displacement should combine to a natural-looking forward jump without fancy algorithms.

Of course, you need to take into account the height difference between the starting and end tile. If the character jumps up, you need to give him enough initial velocity to get there, enough to reach a height of, say, the difference + 1 height units. When jumping down or on even ground, jump up 1 height unit before falling down. So now the duration of the jump animation depends on the height difference.

Next, you need to make the duration of the forward movement dependent on the duration of the vertical movement. A long vertical jump takes a longer time to complete than a short vertical jump across the same horizontal distance, obviously, so your forward movement must not be constant, or you will typically overshoot. For a spot landing, it must always match the duration of the jump\*. If you haven't already, you therefore need to extend your movement function with a duration parameter.

\*Exception 1: For simulating a cool "slide" after landing, don't simply end your animation with a stop, but take the idea of gravity further by implementing a friction vector, which is basically "gravity for horizontal movement". Give your character a vertical and a horizontal movement vector. Ignore gravity while the character is on the ground, and ignore friction while the character is airborne or walking. Apply friction to the horizontal velocity as soon as the character lands from a jump, so his horizontal movement will continue, but slowing down until it reaches zero.

\*Exception 2: If you want to simulate a jump against a wall, just reduce the upward and forward component velocity to zero the instant you hit a wall, and then let gravity do its work.
> 4 votes

---
Tags: xna, isometric
---


# Question
Title: Events and objects being skipped in GameMaker
**Update:** Turns out it's not an issue with this code (or at least not entirely). Somehow the objects I use for keylogging and player automation (basic ai that plays the game) are being 'skipped' or not loaded about half the time. These are invisible objects in a room that have basic effects such are simulating button presses, or logging them.

I don't know how to better explain this problem without putting up all my code, so unless someone has heard of this issue I guess I'll be banging my head against the desk for a bit **/Update**

I've been continuing work on modifying Spelunky, but I've run into a pretty major issue with GameMaker, which I hope is me just doing something wrong.

I have the code below, which is supposed to write log files named sequentially. It's placed in a End Room event such that when a player finishes a level, it'll write all their keypress's to file. The problem is that it randomly skips files, and when it reaches about 30 logs it stops creating any new files.

```
var file_name;
file_count = 4;
file_name = file_find_first("logs/*.txt", 0);
while (file_name != "") {
    file_count += 1;
    file_name = file_find_next();
}
file_find_close();

file = file_text_open_write("logs/log" + string(file_count) + ".txt");
for(i = 0; i < ds_list_size(keyCodes); i += 1)
{

    file_text_write_string(file, string(ds_list_find_value(keyCodes, i)));
    file_text_write_string(file, " ");
    file_text_write_string(file, string(ds_list_find_value(keyTimes, i)));
    file_text_writeln(file);

}
file_text_close(file);

```

My best guess is that the first counting loop is taking too long and the whole thing is getting dropped?

Also, if anyone can tell me of a better way to have sequentially numbered log files that would also be great. Log files have to continue counting over multiple start/stops of the game.

# Answer
> 0 votes
Though I am unsure why, my non-loading objects problem was solved by closing Game Maker, going to sleep, then opening it again.

Hopefully, it doesn't come back.

---
Tags: game-loop, game-maker
---


# Question
Title: How to test a turn-based ios Game Center game with 2 devices?
This might well be a very dumb question, but here goes anyway, I'm planning my turn-based ios game center game, obviously I know I'll need 2 iDevices to test it on, but how would I test the online turn-based play between the devices? As I'm to understand it, if the 2 devices are local (i'e close to each other) they automatically revert to a local communication method? is it possible to force them to communicate online so I can test that part of the project?

# Answer
With GKTurnBasedMatch all communication is done between the device and the game center serves only, there's never any direct communication between two devices.

You don't actually need two devices, you only need two different game center *accounts*. (Although testing with a single device would be a pain.)
> 1 votes

---
Tags: ios, testing, turn-based, game-center
---


title: Angle range detection

text:
# Question
Title: Angle range detection
I'm trying to make game like **portal** which players can transform between two holes.
My problem is, how to detect if player's have the right angle to the hole. (hole has an angle to a direction, if player's angle to hole meet the right direction can do transform)

Pseudo code:

```
var range=30;
 if(collission){
     if(abs(ball.getAngle()-player.getAngle())<=range){
            ball.doTransform(player);
     }
 }

```

below is some situation:

```
ball.setAngle(20);
player.setAngle(30);
abs(ball.getAngle()-player.getAngle()) ==10 //ok
player.setAngle(350);
abs(ball.getAngle()-player.getAngle()) ==320 //not ok
ball.setAngle(350);
player.setAngle(20);
abs(ball.getAngle()-player.getAngle()) ==330 //not ok
ball.setAngle(120);
player.setAngle(100);
abs(ball.getAngle()-player.getAngle()) ==20 //ok

```

and anybody can help me to figure out the right condition so that ball can transform player? thanks!

# Answer
If I understood your question correctly, you're trying to see whether two known angles match within a tolerance 'range', but subtracting them gives unwanted results when the 360° branch cut is traversed, e.g. the difference between 350° and 10° should show up as 20° instead of 340°.

One possible solution is to replace the abs-function with a function that adds 360° when the angle is below -180° and subtracts 360° when the angle is over 180°. The result is always in the range of -180° to 180°, the sign indicating left and right.

Pseudocode

```
take360(angle) {
  if(angle>180) { return(angle-360); }
  if(angle<-180) { return(angle+360); }
  return(angle);
}
var range=30;
  if(collission){
    if(abs(take360(ball.getAngle()-player.getAngle())) <= range){
      ball.doTransform(player);
    }
  }

```
> 3 votes

# Answer
It's hard to understand what you are trying to do, but probably the answer is to use direction vectors instead of angles.

If you specify the directions as vectors, a simple dot product will tell you how the directions relate to each other. The dot product results in a range of values from 1 to -1: if the dot product is 1, they are facing exactly the same direction; if it is -1, they are facing exactly opposite directions. Thus you are looking for a dot product that is negative within some threshold.
> 4 votes

---
Tags: mathematics
---


# Question
Title: Android app: adding background, styles, custom buttons
I am still fairly new to programming in general and android specifically. I am working on an app that currently runs fine and does everything its supposed to do, but its only a skeleton of the app I would like to make. Right now, my TextViews, Buttons, etc are all arbitrarily placed just so I can see them and use them to develop the app. I am now getting to the point that I have to create the background, colors, etc and I'm not even sure what the correct terms are to search the forums and tutorials on how to do it.

I'm not looking to do anything fancy like 3D graphics, but I would like my game to look more professional than Barcode Beasties . Maybe something closer to this .

What are the views/styles that they use and could you help me out with a bit of the correct terminology so I can figure out what I have to learn to do this? What do I need to do to get my app that consists of standard views to the next level?

# Answer
First step is to give your different views a background: `android:background="@drawable/mypicture` in the XML layout

You can also make any view into a button by giving it an `onClick` attribute (or doing `findViewById().setOnClickListener` in your code), so you don't necessarily have to use buttons to do things (in fact I don't use buttons at all)

There is a guide about styling and themes here: http://developer.android.com/guide/topics/ui/themes.html

Finally, to give views those nice rounded corners without the background images getting all horribly stretched, check out nine-patch images http://developer.android.com/guide/developing/tools/draw9patch.html

I hope that helps / I've not been patronising
> 1 votes

---
Tags: android
---


# Question
Title: First person camera is somehow "magically" expanding
I'm making a first-person game, and I've gotten the camera done (modified version of Lloyd Goodall's code), but whenever I scale an object, it doesn't appear bigger, but the speed of movement seems to have slowed down (of course, I know that this is because of the size, but I'd rather want to see the objects scaled up). Here is my code:

```
    Prism rect = new Prism(new Vector3f(1f, 1f, 1f), new Vector3f(1,1,1));
    try {
        rect.setTextures(new TextureArray(
            tl.loadTexture("default_dirt.png")).getTextures());
    } catch(Exception e) {
        e.printStackTrace();
        Errors.exit(Errors.EXCEPTION);;
    }

    Camera camera = new Camera(0,0,0);
    float dx;
    float dy;
    float dt;
    float sensitivity = 0.07f;
    float speed = 0.07f;
    // Generate the frames
    Mouse.setGrabbed(true);
    while (!Display.isCloseRequested() && !input.isKeyDown(input.ESC)) {
        dt = getDelta()/10;
        dx = Mouse.getDX();
        dy = Mouse.getDY();
        camera.incYaw(dx * sensitivity);
        camera.decPitch(dy * sensitivity);
        float dist = speed*dt;
        if(input.isKeyDown(input.JUMP)) {
            camera.up(dist);
        }
        if(input.isKeyDown(input.SNEAK)) {
            camera.down(dist);
        }
        if(input.isKeyDown(input.FORWARD)) {
            camera.forward(dist);
        }
        if(input.isKeyDown(input.BACK)) {
            camera.back(dist);
        }
        if(input.isKeyDown(input.LEFT)) {
            camera.left(dist);
        }
        if(input.isKeyDown(input.RIGHT)) {
            camera.right(dist);
        }
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
        GL11.glLoadIdentity();
        init3DGL(width, height);
        camera.look();
        rect.render();
        init2DGL(width, height);
        try {
            HotBar health =
                new HotBar(50, Tile.loadTexture("default_dirt.png"));
            health.render();
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
        Display.update();
        Display.sync(30);
    }
    Display.destroy();

```

So I guess my question is: How do you keep a camera at a certain size?

# Answer
You don't show how you adjust the scale, so this is speculation.

If you scale an object relative to the camera (or its initial position) as center point, there will be no visual change but speed of motion will necessarily be slower relative to the scale of the object, so your results are to be expected.

To strengthen the impression of size, add other things which provide a scale to compare to, such as:

* Other objects of known size.
* Camera's height above the ground/horizon; it should be at a realistic eye level for your character/vehicle. To establish a ground plane, create a textured plane and possibly also a horizon gradient.
* Distance fog or blur partly obscuring the object will convey largeness.
* Texture features on surfaces; objects viewed at a distance should have finer/softer grain whereas close-up ones show detail. If you want to present an object at two different sizes and have it look different, *don't* just scale the texture coordinates up.
> 4 votes

---
Tags: camera, lwjgl, first-person-shooter
---


title: D3D11 Multiple Render Targets

text:
# Question
Title: D3D11 Multiple Render Targets
I wanted to try rendering to multiple render targets as a first step to deferred shading, but I'm getting somewhat peculiar behavior where the contents of all render targets are the same as the first one.

So far all the render targets have the same format.

The relevant snippets from the shaders are:

```
//geometry rendering
struct PS_OUT {
    float4 diff : SV_TARGET0;
    float4 norm : SV_TARGET1;
    float4 spec : SV_TARGET2;
    float4 uv   : SV_TARGET3;
};

PS_OUT PS(PS_IN input)
{
    PS_OUT output;
    output.diff = mytexture.Sample(mysampler, input.uv);
    output.norm = input.normal;
    output.spec = float4(input.pos.xyz, 1);
    output.uv = float4(input.uv, 0, 1);
    return output;
}

//"compositing" with fullscreen quad
Texture2D diff;
Texture2D norm;
Texture2D spec;
Texture2D uv;
SamplerState mysampler;

PS_IN VS(VS_IN input)
{
    PS_IN output ;
    output.pos = float4(input.pos,1);
    output.uv = float4(input.uv, 1, 1);
    return output;
}

float4 PS(PS_IN input) : SV_TARGET
{
    float4 diffuse = diff.Sample(mysampler, input.uv.xy);
    float4 normal = norm.Sample(mysampler, input.uv.xy);
    float4 specular = spec.Sample(mysampler, input.uv.xy);
    float4 uvw = uv.Sample(mysampler, input.uv.xy);

    return normal;
}

```

Sorry for the long post.

Now, the weird part is, if I return any of the sampled colors alone, like for example the normal, the first G-Buffer "channel" gets drawn to the screen instead. (Even if the normal channel is the only one I sample).

However, if I return this instead: `0.0001*diffuse + 1.0*normal + 0.0001*specular + 0.0001*uvw` then it does return the actual normal channel.

This `0.000*diffuse + 1.0*normal + 0.000*specular + 0.000*uvw` however results in just the diffuse being drawn again.

There are no Info or Warning or Error messages from the debug layer, turning the debug layer off doesn't change anything either.

Could the HLSL compiler possibly be optimizing the Sample calls away since the result is not used, and then removing the texture objects alltogether since they are not sampled from?

PS, if you think seeing how I create and assign the render targets etc will help, I will add it. I just didn't want to make the post any longer.

# Answer
> 3 votes
> Could the HLSL compiler possibly be optimizing the Sample calls away since the result is not used, and then removing the texture objects alltogether since they are not sampled from?

Yes, this is exactly what it will do. Shader compilers are *very* aggressive about optimizing away unused code, parameters, and objects.

If you're binding the textures by index in your C++ code (e.g. diffuse to texture 0, normal to texture 1, etc.) that would explain this behavior. When `diff` is not used, the shader compiler will likely assign `norm` to texture 0.

There are two ways to fix this. You could provide explicit bind points (registers) in your HLSL, like:

```
Texture2D diff : register(t0);
Texture2D norm : register(t1);
Texture2D spec : register(t2);
Texture2D uv : register(t3);

```

This tells the compiler to always assign `norm` to texture 1, even if `diff` is unused, for example.

Or, you could use the D3D11 shader reflection API (or the Effects 11 API, if you're using it) to look up the shader parameters by name; then you can find out which bind point the compiler assigned to each texture parameter, and bind the correct texture to that register.

---
Tags: c++, directx11
---


# Question
Title: Snake game - collision detection causing new position of apple to be rendered multiple times
I have a collision method implemented through the use of slick2d. When ever the snake collides with the apple, it causes the apple to be rendered in multiple places before the snake moves further along.

```
    if(checkCollision() == true){
        x -= 1;

        snakes.add(new Point(x, y));
        locateApple();
    }

```

And heres the locate method to move the apple in a random position:

```
public void locateApple() {
       int r = (int) (Math.random() * RAND_POS);
       applePoint.setX((r * DOT_SIZE));
       applePoint.setY((r * DOT_SIZE));

   }

```

This is in my update() method, which is probably causing the problem, how can I run this code only once? SO that once it collides, it moves the apple in a new position with out executing multiple times.

# Answer
> 0 votes
One way would be to keep track of the collision state for the current *and* previous frames, and only trigger a collision when there is a collision on the current frame, but there was *no* collision on the previous frame.

This way, once a collision has been triggered, there will need to be at least one frame of non-collision before it triggers again. Simply put:

```
bool previouslyColliding = false;
bool currentlyColliding = false;

public void update()
{
    currentlyColliding = checkCollision();
    if(currentlyColliding && !previouslyColliding)
    {
        // Handle collision here
    }
    previouslyColliding = currentlyColliding;
}

```

*If* that doesn't solve it, it's most probably because of a problem with `checkCollision()` returning true when it shouldn't.

# Answer
> 1 votes
Although you're not giving too much info I guess this is happening:

```
Update 1:
the apple collides with the snake
the apple is removed
a new apple is placed at X
Draw 1:
the apple is drawn at X
Update 2:
it turns out that there was already something at X so the apple immediately collides
the apple is removed
a new apple is placed at Y
Draw 2:
the apple is drawn at Y

```

*Repeat until the new apple is placed on a free position*

The chance of this happening is getting more and more likely as the snake grows, so you might see your apple flash at 3,4,5 places before it finding a free spot.

If this is the case David Gouveia's answer is not sufficient. To solve this you should modify your findApple method to only place it on a free position.

---
Tags: java, collision-detection, slick
---


# Question
Title: Child transforms problem when loading 3DS models using assimp
I'm trying to load a textured 3d model into my scene using assimp model loader.

The problem is that child meshes are not situated correctly (they don't have the correct transformations).

In brief: all the `mTansform` matrices are identity matrices, why would that be?

I'm using this code to render the model:

```
void recursive_render (const struct aiScene *sc, const struct aiNode* nd, float scale)
{
    unsigned int i;
    unsigned int n=0, t;
    aiMatrix4x4 m = nd->mTransformation;

    m.Scaling(aiVector3D(scale, scale, scale), m);

    // update transform
    m.Transpose();
    glPushMatrix();
    glMultMatrixf((float*)&m);

    // draw all meshes assigned to this node
    for (; n < nd->mNumMeshes; ++n)
    {
        const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]];
        apply_material(sc->mMaterials[mesh->mMaterialIndex]);

        if (mesh->HasBones()){
            printf("model has bones");
            abort();
        }

        if(mesh->mNormals == NULL)
        {
            glDisable(GL_LIGHTING);
        }
        else
        {
            glEnable(GL_LIGHTING);
        }

        if(mesh->mColors[0] != NULL)
        {
            glEnable(GL_COLOR_MATERIAL);
        }
        else
        {
            glDisable(GL_COLOR_MATERIAL);
        }

        for (t = 0; t < mesh->mNumFaces; ++t) {
            const struct aiFace* face = &mesh->mFaces[t];
            GLenum face_mode;

            switch(face->mNumIndices)
            {
                case 1: face_mode = GL_POINTS; break;
                case 2: face_mode = GL_LINES; break;
                case 3: face_mode = GL_TRIANGLES; break;
                default: face_mode = GL_POLYGON; break;
            }

            glBegin(face_mode);

            for(i = 0; i < face->mNumIndices; i++)// go through all vertices in face
            {
                 int vertexIndex = face->mIndices[i];// get group index for current index
                 if(mesh->mColors[0] != NULL)
                     Color4f(&mesh->mColors[0][vertexIndex]);
                 if(mesh->mNormals != NULL)
                     if(mesh->HasTextureCoords(0))//HasTextureCoords(texture_coordinates_set)
                     {
                         glTexCoord2f(mesh->mTextureCoords[0][vertexIndex].x, 1 - mesh->mTextureCoords[0][vertexIndex].y); //mTextureCoords[channel][vertex]
                     }
                     glNormal3fv(&mesh->mNormals[vertexIndex].x);
                     glVertex3fv(&mesh->mVertices[vertexIndex].x);
             }
             glEnd();
        }
    }
    // draw all children
    for (n = 0; n < nd->mNumChildren; ++n)
    {
         recursive_render(sc, nd->mChildren[n], scale);
    }
    glPopMatrix();
}

```

What's the problem in my code ?

I've added some code to abort the program if there's any bone in the meshes, but the program doesn't abort, this means : no bones, is that normal?

```
if (mesh->HasBones()){
    printf("model has bones");
    abort();
}

```

Note: I am using openGL & SFML & assimp

# Answer
> 2 votes
I figured it out

the problem is in the line:

```
m.Scaling(aiVector3D(scale, scale, scale), m);

```

this line makes m always equals to Identity because it generates a Scaling Matrix instead of scaling the matrix "m"

i got my code from assimp examples : https://github.com/assimp/assimp/blob/master/samples/SimpleTexturedOpenGL/SimpleTexturedOpenGL/src/model\_loading.cpp

I sent them the fix https://github.com/assimp/assimp/pull/5

---
Tags: c++, opengl, models, model-loader, assimp
---


title: How do I keep an MMO synchronized?

text:
# Question
Title: How do I keep an MMO synchronized?
I'm making a 2D, top down MMO game. ATM I can connect a player to a server and they get the map data from a DB. They can move around and hit some stuff and if they move near a viewport edge, the server sends new data etc.

Even a few players can do this, but since I don't have an, lets call it, "update manager" which tells the players where they are and the DB that the map has been altered. It's just a read only game at the moment.

My idea is, to tell the server where a player is and how big his viewport is. Then if any other player is in this viewport, the server will distribute the updates to each other player.

So I wouldn't have to tell the whole world what's going on.

The problem, however, is the ping.

If I have a ping of ~300ms, every other player would probably "jump" over the map, and not move smoothly. I could keep this synchronized with vector clocks, but it would still lag.

Also, how to keep the players from cheating? All ideas I got, don't really work. The only "safe" thing seems to be to calculate the game on the server and client, then throw away all data when the calculations are wrong. But this seems rather excessive to me.

--- Edit ---

Ok, I had some ideas after I read the comments.

1. I will send an absolute state to the server for ever game entity I have. This state object will consist of the position, orientation, speed and an "action", which can be anything someone can do.
2. I'm gonna keep the clients seperated in "small" arrays, each representing a area of the map. So I can calculate which client is near or in my viewport and needs to get my information.
3. I have to find out if it's possible to get a timestamp of the request, to use it for sanity checking, so no player can send me actions from an invalid time-range to get his actions evaluated before the other players.
4. Only only updates from other clients and errors from the server get sent to the client, if everything is ok the server just takes the informations.

# Answer
> 6 votes
You have identified the key problems. Your "bounding box" solution to what-to-update seems fine. You may want to make the update box a little wider than the view box, so that actors outside the view are already available if your player starts walking.

The usual solutions to jumping are:

1. Some assumptions, e.g. other players keep moving in the same direction until the client knows otherwise. This allows the client to project what will happen, providing smooth movement of the other players.
2. Interpolation / gentle catch up: when the client is told that a player should be 5 squares away from what the client currently sees, instead of jumping him to that position, he is slowly animated to his new projected position over time. So clients **will** see false information, but activity will appear smooth to them, which is the important thing! If the player is very far away from his correct position (e.g. \>15 squares), then jumping him to the new position may be preferable.

You got the right idea about cheating. Only the server should decide what really happened, with the information he has. The clients must defer to whatever the server says, and throw away any wrong information they have.

For this reason, sometimes crucial feedback such as death-animations, frag count, player health, are not automatically updated/projected on the client; instead the client must wait for updates/triggers from the server, before such things are shown. The delay this necessarily causes is seen as a better payoff than showing the client false information.

So animations such as small explosions of a projectile can be shown, if they are identical whether or not they hit a player. But animations describing a hit on a player might be better off delayed, if it is important to players that these are always correct.

# Answer
> 2 votes
The viewport technique is a primitive form of what's called "area of interest filtering". You can Google that for a variety of more advanced variations that may work better for you.

For the second problem, there are a number of tricks you can use to alleviate it. The first is what JoeyTwiddle mentioned: interpolating positions.

However, doing only that will not be enough. You'll end up with constant lag in position.

The next thing you can do is predictive updates. If the server has measures a lag of 50ms, then the serve would send a position for 50ms in the future rather than the current position. Combine with interpolating.

The server can also send both a velocity and a position to the client, and the client can perform its own movement updates, periodically being corrected by the server. Again, combine with interpolation. You also need a bit of work to make sure that you dont send a velocity right before the character stops moving, causing the client to overshoot position; accounting for lag helps here too.

---
Tags: networking, mmo, synchronization
---


# Question
Title: Drawing over objects occasionally leaving relics behind
I'm drawing a large number of bouncing shapes similar to an old 1990s screensaver. I'm just doing this to study (but not hopework) For some reason my object clearing (simply blitting a black shape over the prior position) is missing parts of the shapes and leaving fragments behind. I could just black the whole screen between each draw cycle and avoid this, but I want to draw over the individual shapes. Why is this periodically missing parts of the shapes?

```
    from pygame.locals import *
    import pygame as pg
    from random import randint as ri
    import time

    pg.init()
    display_size = (800, 600)
    canvas = pg.display.set_mode(display_size)

    canvobj = []
    running = True

    class circle:
        def __init__(self, xpos, ypos, rad):
            self.type = 'circle'
            self.color = (ri(1,255),ri(1,255),ri(1,255))
            self.posit = (xpos, ypos)
            self.radius = rad
            self.speed = (ri(-5,5),ri(-5,5))
            self.bounce = 0
        def topygame(self):
            return (self.color, self.posit, self.radius)
        def clearit(self):
            return ((0, 0, 0), self.posit, self.radius)
        def moveit(self):
            self.posit = (self.posit[0]+self.speed[0], self.posit[1]+self.speed[1])
            return (self.color, self.posit, self.radius)

    class rect:
        def __init__(self, x, y, width, height):
            self.type = 'rect'
            self.color = (ri(1,255),ri(1,255),ri(1,255))
            self.posit = (x, y, width, height)
            self.speed = (ri(-5,5),ri(-5,5))
            self.bounce = 0
        def topygame(self):
            return (self.color, self.posit)
        def clearit(self):
            return ((0, 0, 0), self.posit)
        def moveit(self):
            self.posit = (self.posit[0]+self.speed[0], self.posit[1]+self.speed[1], self.posit[2], self.posit[3])
            return (self.color, self.posit)

     def addobjs(num, iterable):
        for x in range(num):
            iterable.append(circle(ri(1,800),ri(1,600), ri(1,50)))
        for x in range(num):
            iterable.append(rect(ri(1,800),ri(1,600), ri(1,100), ri(1,100)))

    def clearobjs(obj):
        if obj.speed[0]==0 and obj.speed[1]==0:
            obj.speed=(ri(10,20),ri(10,20))
            obj.bounce=0
        if obj.posit[1] < -100 or obj.posit[1] > 650:
            obj.bounce += 1
            obj.speed = (obj.speed[0], -obj.speed[1])
        if obj.posit[0] < -100 or obj.posit[0] > 850:
            obj.bounce += 1
            obj.speed = (-obj.speed[0], obj.speed[1])
        if x.type == 'circle':
            pg.draw.circle(canvas, *(x.clearit()))
        if x.type == 'rect':
            pg.draw.rect(canvas, *(x.clearit()))
        if x.bounce > 4:
            canvobj.remove(obj)

    def moveobjs(obj):
        if x.type == 'circle':
            pg.draw.circle(canvas, *(x.moveit()))
        if x.type == 'rect':
            pg.draw.rect(canvas, *(x.moveit()))

    starttime = time.time()

    while running:
        pg.display.flip()

        if time.time()-starttime > 1:
             starttime = time.time()
             addobjs(ri(1,3), canvobj)

        for x in canvobj:
             clearobjs(x)

        for x in canvobj:
             moveobjs(x)

        for event in pg.event.get():
            if event.type == QUIT:
                running = False
                break
            else:
                pass

        pg.time.delay(30)

    pg.quit()

```

# Answer
> 2 votes
Sounds like your shapes have anti-alias around them and plotting black shapes with anti-alias would only semi remove the anti-alias portion of the screen. The way anti-alias work is to read on screen pixels, and apply black to that pixel as a percentage (and not pure black) which is then plotted back to screen. This forumla would leave the kind of behavour you describe.

Your solution is increase the size of the shape a couple of pixels when it comes to wiping them out or turn anti-alias turn off altogether.

If you open up an art package and plot a white anti-alias circle on a black background and then plot a black anti-alias circle of the exact same size in the same position as the white circle, you will see the same issue in that it is not able to fully remove the white circle.

---
Tags: python, pygame
---


# Question
Title: Specific Physics Lessons and Reference for Game Development
What "Physics stuffs" should I learn in game developments? I'm reading about Verlet Integration, and I'm wondering what other lesson should I learn and if there are available resources can you please provide some link or anything. Thanks.

# Answer
It's a very open question. Here are a few references I've found great for writing my always in progress engine :)

Online references:

* Indie Game Developer WildBunny has some great physics tutorials: Link He focuses on Flash but his code is quite clean and easy to port to other languages.
* Chris Hecker has put online versions of his Game Developer articles (C++). It includes a few that are great. I like his style: Link

Books:

* Physics for Game Developers \- This one was one of the first books that explained physics specifically for games. I find it's ok. I think the code is in C or C++.
* Game Physics Engine Development \- This one is great, very comprehensive but like all the books from this publishing company its big! It might be a little overkill even.
> 3 votes

---
Tags: android, game-design, physics, game-mechanics
---


# Question
Title: Game programming: common methods and design patterns
I begun writing a very simple game engine so that I can learn OpenGL 3.x better but since my inexperience and my sparse knowledge of how a 3D game should be designed, I usually get into problems where I realize that I should have designed my classes differently. Other problems I'm facing is how to keep track of time in a concise manner in the game and update movement as needed and how to tell the renderer that it needs to redraw. Also I keep needing to make Get and Set functions for passing various flags from one object to another, is that a bad practice?

So, as the title says, I'm interested in any books or articles/tutorials and source which could help me out and would explain some common design patterns in game design (i.e. game state handlers, fonts etc).

Btw, I'm still using freeglut, would you recommend I move to a better windowing system before progressing or after I get a better grasp of OpenGL?

# Answer
I'll write a proper answer since i was at your stage about 2 months ago.

> I begun writing a very simple game engine so that I can learn OpenGL 3.x better but since my inexperience and my sparse knowledge of how a 3D game should be designed, I usually get into problems where I realize that I should have designed my classes differently.

Don't worry about it. With your lack of experience, you'll never be able to think about all of the possibilities and ways a given class will be used in your engine. It's best if you consider the main features of the class, implement it and restructurize later. Don't try to overthink things, you'll be wasting your time at this stage. My first game was a complete mess, i'm sure it was the case for most people.

> Other problems I'm facing is how to keep track of time in a concise manner in the game and update movement as needed and how to tell the renderer that it needs to redraw.

What you need is the knowledge on what a game loop is. **This** is a good place to start. Once you start writing more complex code like handling physics then you might want to consider loops with variable frame times, but start small. A simple fixed frame game loop should suffice you for now.

> Also I keep needing to make Get and Set functions for passing various flags from one object to another, is that a bad practice?

This is more of a software engineering question. With time you'll see which data you need to protect and which is safe. It's probably best if you just implement a feature and then see what's not exposed outside of it and can be treated as public data.

It's all a matter of experience. You'll write a camera class, then you'll see what functionality you want from it beside the transform matrices. If you want any immediate tips, i'd have to say, implement bare bones, extend later.

**Articles and Books:**

* Game engine development

These books talk about the architecture of modern game engines and pipelines. They'll give you a good overview on the underlying technology. I recommend the first book if you have to choose, it's less "biased" towards certain technologies, though in the end you proably want to get through both since they're great sources of knowledge.

http://www.amazon.com/Game-Engine-Architecture-Jason-Gregory/dp/1568814135

http://www.amazon.com/Game-Coding-Complete-Third-Edition/dp/1584506806

* OpenGL

http://ogldev.atspace.co.uk/index.html

http://www.arcsynthesis.org/gltut/index.html

http://www.opengl.org/sdk/docs/man3/

* GLSL

http://www.lighthouse3d.com/tutorials/glsl-core-tutorial/glsl-core-tutorial-index/

http://www.opengl.org/sdk/docs/manglsl/

* Collision Detection

http://www.peroxide.dk/papers/collision/collision.pdf

(I'm linking this because i found it hard to find articles on how proper 3D collision detection is done.)

There's more books, but by the time you're done with this (especially Game Engine Architecture), you'll know better what you want.

> Btw, I'm still using freeglut, would you recommend I move to a better windowing system before progressing or after I get a better grasp of OpenGL?

WinAPI, if you feel that you have time and will to learn Windows programming (if you're developing for Windows). FreeGLUT is fine for learning, but eventualy you'll want more functionality. Though, if you want to go the completely other route you can launch OpenGL with libraries like SFML or SDL. Stick with FreeGLUT, unless you're stubborn like me. I went straight for WinAPI.
> 11 votes

---
Tags: c++, architecture, methodology
---


title: Get Final output from UDK

text:
# Question
Title: Get Final output from UDK
( sorry for my bad english in advance :D )

I'm trying to get a .exe setup output, from my UDK !( with my own maps and scripts which I made within MyGame) I tried UnrealFrontEnd! But It made a setup , that after installation I can see my .udk maps, my packages and etc. But It's not a real output that I can show to my customers. I don't want, other can use my resources !

So... How can I get a binary-like output from UDK as a real Game-Output ? ( like what we see in all commercial games ) Is there any option in frontend that I missed ?

# Answer
It takes some time to setup, but afterward building new version is pretty straightforward.

First, update config file UDKGame\Config\DefaultEngine.ini or DefaultEngineUDK.ini.

There are 4 sections you need to update: \[Engine.ScriptPackages\], \[UnrealEd.EditorEngine\], \[Engine.StartupPackages\] and \[Engine.PackagesToAlwaysCook\].

**\[Engine.ScriptPackages\]**
Add here lines for all new script packages like this:

```
[Engine.ScriptPackages]
+NonNativePackages=UTGame
+NonNativePackages=UTGameContent
+NonNativePackages=NewScriptPackage

```

If you do not use classes from UTGame and UTGameContent then it\`s safe to remove them from config.

**\[UnrealEd.EditorEngine\]**
You need to add there lines for script packages. That settings is used to include scripts for compiling step, so there are high chances that settings are already done.

**\[Engine.StartupPackages\]**
Add lines for content packages at this section. You need to add here only packages that need to be loaded all time, e.g script packages, font packages. Also include here packages resources from are referenced dynamicaly via **DynamicLoadObject()** method. Otherwise such packages will not be cooked.

**\[Engine.PackagesToAlwaysCook\]**
You need to add here packages that are not referenced from other packages but still need to be distributed, e.g. entry level map.

After this setup fire up UDK Frontend and run build cycle - recompile, cook, package. After this you will get installer with cooked game. That game only has executables, configs, maps, separate texture file and Startup.upk package with all other resources.
> 1 votes

# Answer
Here is a link to the discussion about the license of ue3 and how it works, if you are still not clear about how you will make a standalone game using udk then comment to my answer.

http://forums.epicgames.com/threads/718894-What-kind-of-licensing-is-required-to-get-access-to-the-udk-source-code?s=6cdd2818f53ab93ac44eb32b52a9db6f

Check out this reply to above question by one of the users in the epicgames forum.

http://forums.epicgames.com/threads/718894-What-kind-of-licensing-is-required-to-get-access-to-the-udk-source-code?p=27145813&viewfull=1#post27145813
> 0 votes

---
Tags: udk, unreal
---


# Question
Title: How to move a sprite in a straight line in XNA?
I'm making a whack the mole like game where 4 enemies come from all 4 directions:

I've got the 4 enemy sprites and all I want them to do is walk accross the x or y axis towards the cow in the centre. When the direction key is clicked they get reset to their orginal position. E.g. If the farmer on the left went towards the cow in the centre you would click left to send him back.

# Answer
You're pretty much asking us to program the entire gameplay logic for you. You should tackle one problem at a time, and post a question for *one* specific problem. I'm just going to answer the question on your title (*How to move a sprite in a straight line*) since that's the more concrete problem.

First define variables for the `position`, `direction` (which should be normalized) and `speed` of your sprite. You probably already have the position since you're drawing the sprite on screen.

```
Vector2 position;       // Position of the sprite, where it is drawn
Vector2 direction;      // Normalized vector pointing in the direction to move
float speed;            // Speed in units (pixels if not zooming) per second

```

Having these three, you can make the sprite move the in the specified direction by doing the following in the `Update` method:

```
float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
position += direction * speed * dt;

```

For example, to make the sprite move left to right you'd do something like:

```
direction = new Vector2(1,0);     // Points right
speed = 100f;                     // Moves 100 pixels per second

```
> 3 votes

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


title: Box-box contact information

text:
# Question
Title: Box-box contact information
I have two colliding boxes, How i can calculate contact information like (contact normal, contact point and penetration) .

Is there any simple algorithm .

Note: i'm using XNA .

# Answer
I think this topic has been discussed a few times in the "Physics for Game Programmers" tutorial sessions at the Game Developers Conference.

This paper should at least give you some ideas: Contact Generation by Erwin Coumans.

There has definitely been at least one presentation by Erin Catto about how he does it in Box2d, but it's not clear whether the OP wants 2d or 3d. Anyway, his presentations are excellent and at least one of them (the 2008 one IIRC) mentions contact generation between two boxes via clipping: http://code.google.com/p/box2d/downloads/list
> 1 votes

# Answer
Maybe I'm not fully understanding your question, but if you're looking for general info on collision detection Microsoft has two MSDN pages available, one specifically for XNA:

Bounding Volumes and Collisions in XNA

Collision Detection Overview

You could also look at the Box2D physics engine to get more detailed info on the technical aspects.
> 0 votes

---
Tags: 3d, mathematics, physics, xna-4.0
---


# Question
Title: How can I efficiently store tilemaps in work memory?
I've been working on different tile-based projects, but never really bothered with being efficient memory-wise. Each tile was represented by a tile class which would hold the following:

* X and Y ID of the tile
* Solid boolean
* Events for entities when leaving or entering a tile
* Graphic data
* Size

But especially now, when using a component based system where everything is an entity (which has some base functionality which already takes some memory), I've started to run into memory issues.

I started looking at existing tile engines and noticed that a lot of them don't even have a tile class, but just use an array of integers. I figured you could just use the index of the array for position and the actual integer value for the graphics.

But how would store the other data for this tile? With the events for example, would save them externally from the array or something? This would mean that you would need to have a list for every property you want to save, which sounds like a pain in the ass.

It might be good to know how they would have handled this on a more limited platform, let's say the SNES?

# Answer
A tilemap can be represented efficiently as an array of integers, as you noted, where each integer refers to some tile definition object. This is quite similar to palette-based image representation, and both techniques are applicable to memory-constrained systems (such as the SNES\*).

In such a system, a tile class might represent a definition of a tile's properties and not, as appears to be the case in your original a system, an actual tile instance. This lets you entirely remove some data from the tile definition class (X and Y position, for example). It also means you can eliminate data redundancies. If your "regular grass" tile is tile ID 0, and your "solid wall" tile is tile ID 1, you can create a tilemap array of 0's and 1's and still only need two instances of the actual tile definition type.

Because a consequence of this system is that the tile object doesn't contain instance-specific data, if you *need* instance-specific data (such as for event triggers), you can use another data structure that is more suitable for such sparely-populated data. For example, a dictionary-like structure where the key is some hash of the instances X and Y position and the value is an object that represents tile instance data, such as the trigger list or the tile's "inventory" (the items somebody has dropped there, or whatever).

(\*) It is, however, worth noting that older consoles like the SNES and GBA and such had specialized tileset handling systems "built-in." They operated in a similar fashion though.
> 5 votes

# Answer
As far as graphical things go, all you need is an integer and then later have this multiplied by the tile width and height values to get the bit of image from the sprite sheet. You can have -1 represent no tile.

For location, it's place in the array times tile height and width will give you x and y values, then add tile height and width to get the other side of the tile. I use 2D array for this because it makes it simpler to think about.

For being solid or not, I use three layers; background, mid-ground, and foreground. Anything in the mid-ground is collidable. I draw it background, then mid-ground, then entities, then foreground.

Tile width and height values are stored outside of the tile information as well.
> 1 votes

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


title: Farseer: ApplyForce problem

text:
# Question
Title: Farseer: ApplyForce problem
I just tried Farseer and everything is working great. My problem is, that on touch the player should get an force up. Although the touch event works well, the player did not get an force!

Here my code:

```
 public void Update()
    {

        if (acceleration.Y < 0)
        {
            body.Rotation += ConvertUnits.ToSimUnits(0.05f);
        }

        if (acceleration.Y > 0)
        {
            body.Rotation -= ConvertUnits.ToSimUnits(0.05f);
        }

        while (TouchPanel.IsGestureAvailable)
        {
            var gesture = TouchPanel.ReadGesture();
            if (gesture.GestureType == GestureType.Tap || gesture.GestureType == GestureType.Flick)
            {
                Debug.WriteLine("Okey");
                body.ApplyForce(new Vector2(0, -20));
            }
        }
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(playertexture, ConvertUnits.ToDisplayUnits(body.Position),null,Color.White, ConvertUnits.ToDisplayUnits(body.Rotation), new Vector2(playertexture.Width / 2, playertexture.Height / 2), 1f,SpriteEffects.None, 0f);
    }

```

# Answer
Is it only with the tap response that the force is not applied? If you were to just apply a force in the update loop, without conditions, would it be applied? I'm guessing not. Which could be a number of things. Ensure the player body has been added to the physics engine, and make sure the body is set to respond to forces (i.e. with some physics engines, you set the mass to 0 if you want it to be static).
> 0 votes

---
Tags: xna, farseer-physics-engine
---


# Question
Title: Should I use a VBO if the vertex data changes from time to time?
If I have a very large number of vertices, but they're static for about 70% - 80% of their life time, should I use a VBO for them? If so, what usage should I specify? This doesn't sound like a case for `GL_STATIC_DRAW`.

# Answer
> 1 votes
With GL|ES, you have no choice - you must use VBOs.

With Direct3D, you have no choice - you must use vertex buffers.

With OpenGL Core Profile, you have no choice - you must use vertex buffers.

The only place where you have an option to avoid VBOs is in the old deprecated OpenGL API. Which internally is just inefficiently wrapping VBOs on all newer drivers.

The correct usage flag is likely DYNAMIC\_DRAW for your needs. You can (and probably should) just test the different usage flags and see which one performs best for your particular needs. The results can sometimes be a bit surprising, depending on hardware and driver.

# Answer
> 2 votes
Personally I'd say try it and see. You may get better performance during that 70% to 80% of the object's lifetime, you may not, and much of that will depend on how well (or not so well) your driver and hardware handles VBOs used in this manner (and - of course - whether or not this part of the pipeline is actually a bottleneck for you; it may not be, in which cause you'll see minimal, if any, improvement).

Fortunately it doesn't involve major surgery to migrate a program from VBOs to client arrays and back, so it's something you can easily enough test and back out of if it's not working well for you.

Either of GL\_STATIC\_DRAW or GL\_DYNAMIC\_DRAW would be appropriate. Static might just work well because performance during the times when the buffer data doesn't need to be changed may be more important, and you may be able to time updates so that they don't affect performance during the times when it is changed so much.

Remember that they're just hints - your implementation can use them to select the appropriate storage for your buffer, but it is by no means obliged to abide by what you specify - some implementations may just completely ignore them.

Updating a second buffer on another thread while the first is drawing, then switching buffers, may be an option for you here - depending on the target hardware and whether or not you know (or can work out) the new contents in advance.

Looking through the ES2 help pages I see that it doesn't have glMapBufferRange, and that you are required to use glBufferSubData for updating. That's moderately unfortunate as with glMapBufferRange I'd unreservedly recommend it - it really is required to efficiently do just-in-time buffer updates. As it is, you just need to profile and find out - but I think it's worth profiling and finding out.

# Answer
> 1 votes
20-30% of frames is really high number. Remeber that this is realtime rendering so worst case scenario does matter. VBO are really great but only if you never or really rarely(like 0.01% of frames) update them. Just use vertex array and get better worst case scenario.

I literally gained 15ms when swapped from vbo's to va in scene where there was 25 skinned models with my adreno 205 gpu on my huawei.

Tldr: Use profiler.

# Answer
> 0 votes
Client-side vertex data storage is deprecated in all 3D APIs. Use Vertex Buffers.

---
Tags: opengl-es, opengl-es2, vbo, vertex-arrays
---


title: How to save a game state?

text:
# Question
Title: How to save a game state?
So I am currently working on a simple game project that most people start of with: "breakout". part of my goal is to make a gamesave of the current gamestate the simplest way possible.

For example, lets say I lose the game or I want to exit the game. Then later, I want to reload the gamestate to the same position of the paddle, ball and bricks. The only problem is I have multiple forms and I just want to save this specific form in its specific state.

I have an idea on how to approach (I would find a way to save the position of the paddle, ball and the bricks and that exact time) just I have no clue how I would execute it. How can I achieve this?

# Answer
With C# (and many other languages) you can serialize (aka save) the state of a objects directly to a file and de-serialize (aka re-instantiate/load) them later so that you have the same objects with the same state.

This works best if you have a prober scenegraph because this way it will happen almost automatically in C#.

As an example say I have the following scenegraph

```
Root : MyRootClass
-Score : int
-WorldObjects : List<MyGameObject>
--Paddle : MyPlaceClass
--Ball : MyBallClass
--Blocks : List<MyBLockClass>
---BlockA : MyBlockClass
---BlockB : MyBlockClass
---BLockEtc

```

You should decorate all of the above classes (except List and int which aren't yours of course) with the `[Serializable()]` attribute and any fields in them which you do not wish to save or load (say references to a graphics device or something) should be marked with the `[NonSerializable()]` attribute

You can then use the BinaryFormatter to serialize **ONLY** the the root object to a file, since all other elements are referenced by the root object they will also be serialized.

```
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
BinaryFormatter formatter = new BinaryFormatter();
try
{
    formatter.Serialize(fs, root);
}
catch (SerializationException e)
{
    Console.WriteLine("Failed to serialize. Reason: " + e.Message);
    throw;
}
finally
{
    fs.Close();
}

```

In the same fashion you can load the root object again:

```
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
    BinaryFormatter formatter = new BinaryFormatter();

    // Deserialize the hashtable from the file and
    // assign the reference to the local variable.
    addresses = (Hashtable) formatter.Deserialize(fs);
}
catch (SerializationException e)
{
    Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
    throw;
}
finally
{
    fs.Close();
}

```

Now if you're lucky all the objects that you wanted to serialize only references objects that can be serialized, if you're not so lucky you need a way to fix those references. There are multiple ways to do this:

1. Call some custom Reinitialize method that gives the object enough info so that they can reconstructed missing references themselves.
2. Use proxyclasses that themselves can recreated the real object
3. Fix the serializable part of your game to not have these references (probably the best idea)

A good example of references that can't be serialized/deserialized and thus need one fo the above solutions is a references to the graphics device.

Also note that C# can, out of the box, can also serialize to human readable formats instead of just binary, for example INI, XML and JSON. See this for a small reference.

Finally if you're using XNA and what to serialize data on the Xbox or WP7 you should take a look at this resource.

*Note I've added two links to my own blog because they seemed appropriate references however it would be better to replace them with more expert material so feel free to edit them with better links*
> 8 votes

# Answer
If you serialise an object then change its class's definition, you will not be able to recreate that object, meaning changes to your game will invalidate past saves. So whilst serialisation is definitely the simplest method, it has this flaw.

A more robust method for a game that will be changed is a manual sort of serialisation where you determine what variables are important to save, and save them - and when you recreate your objects, create them with those variables. The end result is you don't depend on serialisation, and changes to your class definitions do not invalidate past serialised data, allowing changes to your game to operate on old saves.
> 10 votes

# Answer
You could save the objects to disk using DataContractSerializer. You can then when the game resumes/restarts simply load them up and continue.
> 0 votes

# Answer
The problem with using any "native" serialization capability is that it's very fragile across versions of the program. Saved state from one build is likely to be invalid for the next. It won't be comprehensible by humans or modifiable by anyone, which makes debugging problems with reloading a game a nightmare.

It's a little more work, but many valuable capabilities come from having an explicit representation of the game state, or of the steps (ie: moves) needed to construct that state. You can save and replay games, allow spectators to join at will, reconnect disconnected players, and support multiple platforms with different implementation technology.
> 0 votes

---
Tags: c#, savegame
---


title: Fix my Farseer collision detection code

text:
# Question
Title: Fix my Farseer collision detection code
The collision is not working correctly! The collision is in the "open-word" and not when it collides! Here my code:

Platform code(static):

```
body = BodyFactory.CreateRectangle(world, (float)ConvertUnits.ToSimUnits(textureplattform.Width), (float)ConvertUnits.ToSimUnits(textureplattform.Height),1f);
body.BodyType = BodyType.Static;
body.Position = new Vector2(ConvertUnits.ToSimUnits(Position.X) + textureplattform.Width/2,ConvertUnits.ToSimUnits(Position.Y) + textureplattform.Height/2);

```

Player code(dynamic):

```
body = BodyFactory.CreateRectangle(world,(float)ConvertUnits.ToSimUnits(playertexture.Width), (float)ConvertUnits.ToSimUnits(playertexture.Height), 1f);
body.BodyType = BodyType.Dynamic;
body.Position = new Vector2(ConvertUnits.ToSimUnits(position.X), ConvertUnits.ToSimUnits(position.Y));
body.Mass = 1f;

```

Player draw:

```
public void Draw(SpriteBatch spriteBatch)
{
 spriteBatch.Draw(playertexture, ConvertUnits.ToDisplayUnits(body.Position),null,Color.White, ConvertUnits.ToDisplayUnits(body.Rotation), new Vector2(playertexture.Width / 2, playertexture.Height / 2), 1f,SpriteEffects.None, 0f);
}

```

Platform draw:

```
public void Draw(SpriteBatch spriteBatch)
{
 spriteBatch.Draw(textureplattform, ConvertUnits.ToDisplayUnits(body.Position), colorplat);
 }

```

# Answer
> 1 votes
I think the problem is in you *drawing* code, not in the collision code. So the objects are colliding correctly, but you're drawing them in the wrong place.

Looking at your draw code I notice two anomalies:

1. You forgot to draw with the `origin` set to the center of the sprite when drawing the platform. This is mandatory because `Body.Position` refers to the center of mass of the object, which on a rectangular sprite, is at the center. You already seem to be doing this for the player so I won't bother repeating how it's done.
2. When drawing the player, or any other sprite for that matter, you *shouldn't* convert the `rotation` to display units. Angles don't change no matter what the scale is. You only need to convert positions and widths/heights.

To make things easier, I would recommend writing an helper method for drawing physics bodies. Then reuse this method in every class that needs to draw a body:

```
public static void DrawBody(SpriteBatch spriteBatch, Texture2D texture, Body body, Color color)
{
    spriteBatch.Draw(texture,
                     ConvertUnits.ToDisplayUnits(body.Position),
                     null,
                     color,
                     body.Rotation,
                     new Vector2(texture.Width / 2f, texture.Height / 2f),
                     1f,
                     SpriteEffects.None,
                     0f);
}

```

PS: Where you're setting `body.Position` for the platform, you should apply `ConvertUnits.ToSimUnits` to width/2 and height/2 too, if you want it to behave as you expect.

---
Tags: xna, farseer-physics-engine
---


# Question
Title: Slick2D drawString with coordinates from bottom-left corner
For OpenGL text drawing I use Slick2D library. Default Slick2D `0:0` coordinates are at upper-left corner. But in my project I use bottom-left corner for `0:0`. Is it real to configure Slick2D with bottom-left corner as starting point?

# Answer
I extended `AngelCodeFont` and `Image` classes to implement text drawing I need.

In `AngelCodeFont` I updated `yoffset` for each char:

```
def.yoffset = lineHeight - def.height - def.yoffset;

```

where lineHeight was parsed from `common` line in `.fnt` file.
> 1 votes

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


# Question
Title: Where can I Find Free TOS or Privacy Policy Templates?
I've come to the point in development where I think I should take care of some of the "cover my butt" things. In particular, I'm looking for free samples or templates for "terms of service/use" and "privacy policy" statements.

I actually do have my law degree and know something about IP, contracts, etc. However, it's always better not to reinvent the wheel with these type of industry-wide boilerplate documents.

I couldn't find this answer anywhere on this or other StackExchange sites. Of any legit looking sites, I only found paid templates.

Does anyone know of a good website that offers these templates for free? I can edit a general one if needed, but it would be best to have some already geared towards an online game.

**UPDATE**

Some promising resources I found out there:

TRUSTe Privacy policy generator:

http://www.truste.com/technology/#labs

I think you are supposed to pay to use the TRUSTe seal or something, but that doesn't stop you from using this as a starting point. I guess it might help to read their TOS first (LoL).

Legal River TOS / Privacy Policy Generator:

http://terms-of-service-generator.legalriver.com/

http://privacy-policy-generator.legalriver.com/

For now I'll start with these and rework them for my needs. Would still love to hear if anyone knows of a better one geared towards online games.

# Answer
> 1 votes
Is this useful? http://www.bennadel.com/coldfusion/privacy-policy-generator.htm

Why not just bite the bullet and pay for one? You should know (with a law degree) that you want it to be right.

# Answer
> 0 votes
I paid a lawyer to prepare mine, but I felt everything that was included was just boilerplate with language for my games plugged in.

If I were to do it again I would just collect together a series TOS's from other web sites and business from my country, and re write in plain English each point in those TOS's.

I would say a Free TOS would be worth the money you pay for it, and about effective as something you wrote yourself.

Note: The above is bad legal advice, but IANAL and just saying what I would do next time.

---
Tags: legal, game-industry
---