# Question
Title: Are there any usable performant path-finding libraries for python?
## This is cross-posted from StackOverflow, please feel free to answer there too:

I'm working on a real-time isometric RPG in python, and wish to target mobile devices as a platform. The main area where I'm having difficulties is with my pathfinding. I have tried a few algorithms including A\* and a few tweaks to better fit the maps I'm using.

I am satisfied with the results of my algorithm - they give the illusion of some intelligence while being deterministic, and being consistent in either direction so that two characters targeting each others' locations will collide in the middle.

My problem is that while the results look good on the PC where I have all the processing power I could ask for, on my mobile it's quite another story, and there is often a second or more delay while the algorithm is calculated. For this reason I am considering writing a library for this with the most performance-intensive code written in C, however if there is an existing solution for this, or a better way I could do this, I would be all ears.

I stumbled across python-pathfinding but this seems to be slower than what I have built myself for my use case.

---

## My use case:

My maps are build from levels, which are surrounded by walls (visible or invisible), and must be linked by doors (visible or invisible).

My current approach is to have two different algorithms:

* Within a room I search individual tiles as nodes, with each boundary as an equal-cost edge, using a depth-first in the direction of the target location
* Between rooms where each door is a node. The shortest possible path through a room (from door to door) is calculated using the first algorithm and stored in a hash table as the edge cost between those nodes. Sets of edges that can be traversed to get from one node to another are then calculated and also stored in the hash table, and it is not permitted to include the same edge more than once in the same path.

I spawn a separate process on start-up that generates a graph for the second algorithm using the first, and this solves many of my issues, rooms tend to be relatively small and so the penalty of on-the-fly path-finding is kept lower than it otherwise could be, and then for longer distances:

* the first algorithm is used to calculate the distance from the current location to every door in the current room.
* the first algorithm is used to calculate the distance from each door in the target room to the target location.
* the output of the second algorithm is used to get the set of paths between rooms
* the cost of these is added to the cost of getting to the first door and from the last door
* the set of solutions is sorted by cost in such a way that the order of paths of the same cost will always be consistent
* the first item in the set of solutions is chosen.

# Answer
**Disclaimer**

I am not a python programmer primarily; I looked briefly for other libs and came across this.

However, that is not the main thrust of my answer: instead it is to challenge whether you need to find another library at all, or whether you in fact just need to optimise what you have. Ultimately, I'm still trying to help you find a solution to your problem.

**First, on simple optimisation issues which may apply:**

I'm not sure which mobile platforms you're targeting, but be aware that any floating point math you are doing in a highly iterative algorithm like A\* may have a major impact on the mobile device's ability to keep up. Considering that processors in modern mobiles are pretty powerful, it is a little suprising that you're having issues with A\*, however this obviously depends very much on what you are trying to achieve. This brings me to my second point.

If you haven't started profiling your code is yet, you cannot know where the bottleneck lies. You cannot just assume you need a different library -- at this late stage, it is far better to assume your code (which you know does what it needs to in the way you want it to) simply has one or two simple failing points causing the bottleneck. It's like a good relationship really -- If you've got something good going already, don't discard it, put the effort in to fix it. You probably understand enough about the heuristics and so on to know how to work in the guts of it.

Lastly, balancing your A\* heuristic value appropriately is critical to achieving optimal performance -- I take it you are already aware of this as it is one of the fundamentals for this algorithm.

---

**Assuming there is no simple way to solve your problem after tackling the above, here is a bolt-on approach to improving pathfinding performance:**

Let's look at this from the top down. Any pathfinding algorithm makes use of a graph. A\* does too -- it's graph is simply a grid of cells, each cell being a 4-connected graph node. Given A\*'s ability to process many, many individual cells, is an excellent and generally highly efficient algorithm. But when it comes to the crunch, A\* still *has to process that many nodes* of the graph. So how do we reduce this count?

The immediate answer that comes to mind is spatial subdivision AKA resolution reduction. Essentially what you want to do is to generalise regions of your graph; visually, this could be compared to halving an image's width and height while using a pixel blending algorithm: each group of 4 pixels will be merged into 1, with that 1 being the result of the colours of those 4. In the case of pathfinding, your would for example merge the positions (and perhaps weights, depending on how you implement this) of your nodes.

The basic principle is this: When travelling to a city in another country, does one say, "I'm going to 11 Hill Street, Yoursuburb, Yourcity, Yourstate, Yourcountry"? No, one says "I'm going to Yourcountry, and only when I get through immigration will I start navigating at a smaller level of detail: City, then state, suburb, street etc." until finally one is navigating on a house-by-house and footstep-by-footstep basis (to whatever level of ultimate detail you want -- in your case, your basic tiles). This effectively reduces the number of cells you need to process.

Spatial subdivision can be eg. a quadtree approach for subdividing 2D planar topographies (as you presently have), or something closer to a navigation mesh, where you greatly reduce the number of nodes but the connections are now arbitrary (more organic) rather than grid-aligned.

PS. As a final note, consider any approach that makes heavy use of precalculation to reduce runtime overheads. Spatial subdivision is just one of these, but if after profiling you see other opportunities for improving performance, precalculation is your friend. It is my trusty pocket knife in all such situations -- the time-for-space tradeoff.
> 2 votes

# Answer
The problem is not about the performance of a path-finding library as such. Path-finding is a specific application of state-space search, and the length of time it takes to search a state-space grows (often exponentially) in relation to the size of that state. Therefore the biggest problem here is how you represent that state, and the second biggest problem is the algorithm you choose to search it. Only third comes the quality of the implementation, typically. No matter how good the library, it can only search the state space you provide it with, and if that space is too large, the exponential growth of the search space will dwarf any other optimisations.

Judging by your last set of bullet points, it sounds like you're needlessly generating more solutions than you need. An algorithm such as A\* will return the best solution first, solving that problem. Given your topology it would seem like you can generate a path that is combined of nodes (for the current room and the destination room) and super-nodes (for the intermediate rooms where you're going from door to door, and where the costs are precomputed). The number of states to be searched here should be fairly minimal and once the result is returned, a post-processing step would expand the super-nodes out into individual tiles.

I'd be very surprised if such a solution didn't perform perfectly well on Python on pretty much any size of map. However, it's also worth making sure you're using the right data structures - if you're testing a list for membership (eg. the typical 'closed' list) then you'd be better off with a set, and if you're looking up nodes by some value, you're better off with a dict or a set than a list. If you really need a queue object, then a collections.deque may be better than a list. And so on.

Finally, sometimes it is faster to replace the typical A\* with something like iterative deepening A\* which, although less efficient on paper, can be more efficient in practice due to requiring fewer memory allocations and expensive queue operations. This is less likely to hold true in Python however because the relationship between pseudocode instructions and low-level operations is not as strong as it is with a typical C implementation.
> 0 votes

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


# Question
Title: Problem with bounding box in model space and intersection with ray
I have a bounding box in model space and I want to intersect it with a ray. I have tried to transform the ray like this. Rotating and scaling works well, but transition does not.

Here is my code:

```
Xbouding = new BoundingBox(new Vector3(50, 10, 10), new Vector3(120, -10, -10));

ray.Position = Vector3.Transform(ray.Position, Matrix.Invert(MathUtil.CreateWorldMatrix(Position, Rotation, Scale)));
ray.Direction= Vector3.Transform(ray.Direction, Matrix.Invert(MathUtil.CreateWorldMatrix(Position, Rotation, Scale)));
float? dist = ray.Intersects(Xbouding);

```

I have this:

I want to know if the ray from the mouse intersects with the boxes shown in the image. Pick works fine unless the model is translated (rotating and scaling works).

Another little question: what does `float?` mean? What's the difference between `float` and `float?`?

# Answer
> 4 votes
Translation should be simple. Take the Ray vector, and simply add it to a vector representing the amount you want to translate by (in each axis). I don't see you doing this in your code.

So a vector (3.6, 7, 9) translated by (-4, 15, 12.2) results in a vector (-0.4, 22, 21.2).

`float?` (or any typename appended with `?`) is what's called a **nullable type**. Without that `?` you would not be able to set the variable to null. Of course, nullable types incur an overhead -- if they didn't, all types would be nullable by default.

# Answer
> 1 votes
Your bounding box, xbouding, is somewhat inside out. Min.Y & min.Z are both greater in value than max.Y & max.Z. That's impossible for a correct bounding box & won't produce expected results because it wont allow the intersection tests to work correctly. Might or might not factor into current issue, but assuredly it will cause you problems somewhere.

try a min of (50,-10,-10) & a max of (120, 10, 10).

---
Tags: c#, xna-4.0, bounding-boxes
---


# Question
Title: How can a game prevent people from running multiple instances of itself?
Starcraft II restricts me from running multiple instances, but if I run the second instance sandboxed in Sandboxie, it works. What might account for this?

How might I replicate this behavior for my own games?

# Answer
> 15 votes
Aside from Starcraft 2, the general answer to this is: Acquire (and lock, if the acquisition itself isn't already equivalent to locking) a specific resource from the operating system. Exit the game if the acquisition/locking fails. Example of such resources are:

1. Specific TCP or UDP ports.
2. Mutually exclusive locks ("mutexes") or semaphores (those two are often related on OS level)
3. Files (log files are often the most obvious choice)

On the top-end, most pain-in-the-ass for the customer way, specialised hardware which (sometimes necessarily, like for some robotic control components) can only be used exclusively by a single thread can be used this way, too.

# Answer
> 4 votes
I recommend the mutex approach, but:

Another method that is often used is simply checking if another process with the same name is running.

The advantage is that it's ridiculously easy - you don't have to worry about file permissions or know what a mutex is. The downside is, you'll get a false-positive if a *different* program called `starcraft2.exe` is running on the machine.

# Answer
> 3 votes
If you are using C++ and the Windows API, one way you can do is using `FindWindow`, where you can pass parameters like the class name and/or the window name. Then if you find a match, just exit your program before you even load or create a window.

---
Tags: software-engineering
---


# Question
Title: Is there an alternative to decals that will let me put bullet holes on a complicated object?
I'm trying to figure out a way to do "bullet holes" but actually apply the texture at the shader level? If I'm dealing with a model which doesn't have a "flat" face I'd like to be able to wrap the "decal" across the model. Anyone point me at a tutorial that will do something similar to this.

# Answer
> 10 votes
"Flat" face is not a requirement for the decals at all. Here is a visual explanation of how you can project a decal geometrically onto a complicated object.

Also there is that one site which gets referenced quite often here, it has a DX 10 implementation of such decals, search for "volume decals".

# Answer
> 1 votes
Check out paged/virtualized texturing system such as MegaTexture. These could be used to replace decals by drawing into the texture pages as they get paged in.

http://en.wikipedia.org/wiki/MegaTexture

# Answer
> 0 votes
What I had been imagining is determining during the "picking" determine the specific position on the model and pass that exact position to the sharer along with a bullet texture to apply. Of course this still results in the issue of "filing across faces. The geometric projection seems the best option.

---
Tags: shaders
---


# Question
Title: Can you help with collision detection and response in a 3D car racing game?
I am trying to implement the collision detection and response in 3D car racing game.

I have a car model, for collision I am assuming my car as a cuboid. my collision detection with walls is quite good and the response is also good. My model has a velocity, position, acceleration and orientation. I am using matrix to save the orientation and position.

My problem is collision and its response with the ground (in my case it's road). When the ground is a simple plane with a constant y-axis, then there is no need for collision detection as there is no force or movement in the y direction. But if my road is not linear, if it has some elevation, then I am having a collision detection problem when it comes to calculating its orientation.

Any help and suggestions will be of great help.

# Answer
It looks like you don't want to use a car simulation middleware, or even a physics engine to model a "classic car" from a box, four spheres and some hinge joints for the suspension. Well then, I guess for a simple solution you could try something like this:

* Take your cuboid's bottom plane.
* Cast 4 rays downward from each of its's corners and find their collisions with road. This collisions will be your "imaginary wheels".
* Now you can make a height check to hold the car at the right distance from the road (the radius of the imaginary wheel), then set cuboid's lower plane's corner coordinates to the new found wheel's positions. It will be a somewhat working solution, but also give a unique feeling of driving a large concrete brick.

+ For a more realistic approach you may want to simulate a spring system at each imaginary wheel to make it a bouncy concrete brick. Maybe you will also replace wall collisions with it.
    + Then you may want to simulate friction of imaginary wheels. To this point your car was glued to the road, but now it will start to roll-over. Roll overs can be battled with artificial anti-sway torque and GTA-like modifying of max correctional torque by the amount of "wheel turn value", so a player would be able to steer out of roll-over. Unrealistic yet funny :)

Things will quickly become more and more complicated here, it won't be easy to make a fun car physics. Nowadays most if not all physics engines have a built-in car class with tweakable parameters, so you may want to look at their sources.
> 3 votes

---
Tags: collision-detection, physics
---


# Question
Title: What is an OpenGL equivalent to ID3DXSprite?
As a Direct3D developer I can use the ID3DXSprite class (in D3DX library) for drawing 2D graphics. What's the best way to implement this functionality in OpenGL?

# Answer
> 4 votes
I think, that if you want to draw just 2D sprite on screen, you can simply draw textured rectangle.

If sprite should be square, you can also draw point with point size set bigger than 1 and some texture enabled. But I don't know, if you can set some texture coordinates in vertex shader (but probably not, because you have just one point). Other way is to split this one point in geometry shader and assign corresponding texture coordinates.

---
Tags: opengl, directx, sprites
---


# Question
Title: Google's ForPlay library, where does it fall down?
ForPlay is lauded as a pretty amazing accomplishment by Google's own. But I'm holding off on making any solid judgements as yet...

I'm wondering if anyone has used this and has found any major flaws? I'd like to know what these are. Considering that the code is written in Java and is compiled for Flash, Android and HTML5 additionally, I'm wondering how it performs on those platforms as compared with games written natively for those platforms -- if anyone has done any comparisons in this regard.

For those who are unaware of what ForPlay (now renamed PlayN) is, see the repository and this video.

# Answer
> 5 votes
I never used it, but one point against using it is certainly that it's currently at alpha stage, there's basically no documentation and Android support is broken.

From the presentation video it seems like audio support/capabilities is kinda bad. Also there's no socket support (yet).

As with every language that provides a high abstraction layer, you're going to sacrifice some performance. In this special case a lot depends on the "compiler" that will generate the native code for the platform. No problem for Android, since Java is already the native language there, the JavaScript compiler seems to be very good, just the Flash output is not at a level that is comparable to a native app.

You'll also have to consider that to create a game that actually runs on all platforms by simply swapping the "main" class (as demonstrated in the video), you're also going to have to restrict yourself to the common capabilities of the target platforms. That might mean that you cannot use multi-touch as a core gameplay element, or keyboard input etc. unless you start to code some platform specific bits. But that's a problem all cross-platform developers are going to face.

These are some "generic" cons to consider. But the project looks interesting and could provide a great platform to deploy to HTML5, Android, Desktop and Flash once it enters a more mature stage.

---
Tags: playn
---


# Question
Title: How do you get an object to orbit around a certain point on a 2d plane?
I had a concept for a game come to me this morning but I can't figure out how I'd go about implementing the movement.

The general idea involves the left and right controls causing a sprite to go round the center of the plane/(or the centre of the game area) in an orbit rather than moving left and right and the up and down will cause the orbit distance to either increase or decrease unless there is something in the way.

The best way I can think of doing this would be to maintain the polar coordinates of my sprite and convert that to Cartesian coordinates for drawing. Would that work? Is there an easier way?

Also how would I go about ensuring that the sprite was rotated such that it was at a right angle to the line from the center point?

Would I be better off implementing this using gravity and a using a repelling force to keep the character at the desired distance? If so How would I go about doing this?

# Answer
Unless you're going to have so much going on that the speed of trig functions is going to be a concern, I think focusing on a Polar system will be sufficient.

Storing the angle and distance-from-center for your sprite (`Theta` and `R`, respectively) will make the logic for moving based on Left, Right, Up, and Down understandable: Moving Left and Right would change your angle while Up and Down change the distance.

To draw the sprite, converting to Cartesian coordinates is pretty straight forward: `x = R cos(Theta)` and `y = R sin(Theta)` (plus some offset to rotate around the center of the screen/playing area/whatever).

Rotation of the sprite would simply be based on the `Theta` you're already storing. Either exactly equal to or plus a constant, depending on the initial orientation of the sprite.
> 5 votes

---
Tags: mathematics, movement, coordinates
---


# Question
Title: How can I identify feature regions in a procedurally generated world?
I'm building an Island. I use the classical heightmap solution : with a hill-building function, avoiding the corners of the map, I make altitude. Then, perlin noise give me some climatic variables to handle the biomes. Now, I'm facing two challenges who are, in some way, connected :

* In Dwarf Fortress, one of the neat aspects of world generation is how the game seems to "know" areas, and give them names, though they are not rectangular shapes. I would like to be able to "recognize" my forests, my rivers, my hills... any idea what kind of algorithm I could use to scan my map and interpret its areas ? And how would you store that ? I'm using a basic C++ graph made out of a vector of vector of "tiles object".
* This Island should be divided in political areas, not only purely natural regions. I could use mountains and rivers to make "natural borders", but my procedurally generated map doesn't garantee I will have nice "enclaves" that would form a kingdom ; I could find myself having a gigantic "ribbon-formed" political areas surounded by micro-kingdoms. Another possibility would be to look for appropriate areas for a city or a castle. Then, "grow" a political area around it. But there again, I'd like to have some well-known algorithms before trying to devise my own.

This question could be interpreted as a bit too vague, so one way of rephrasing it would be : how to partition (without modifying !) a procedurally generated world into areas suitable for gameplay ? Thanks in advance for your help.

# Answer
Amitp suggests using watersheds to define various regions, as explained in his post on polygonal map generation. The watersheds are best seen by generating a map using his demo. The advantage of using watersheds to help subdivide continents is that it provides boundaries perpendicular to the shoreline, while mountains usually provide parallel boundaries.

If I were subdividing geographic regions, I would use a combination of mountains, watersheds, and edge detection on the various biomes on my map.

I'll also point out that political regions generally span many geographic regions. I would generate geographic regions first, then assign each region a desirability rating (is it a coast? is there gold? good farm land?) and travel cost (steep terrain? heavy woods?.) Then using your favorite pathing algorithm, generate a heatmap of travel between desirable regions. These will end up being your roads, and you can build your political boundaries from there. These boundaries will generally have many roads within them, and less roads between them.
> 23 votes

# Answer
To add to Dan Rasmussen's answer:

One of the main reasons I switched from Perlin Noise (this project) to using polygons (this project) is that polygons provide some nice *structure* for assigning larger areas (political regions, forests, deserts, named areas, boundaries, etc.). Starting with the structure and then generating the map is similar to polygon rendering — something that is relatively easy. Starting with the map and then inferring the structure is similar to computer vision — something that is relatively hard, but possible. I want both the structure and the map so I decided to go the relatively easy route of building a map on top of the structure (nodes and edges).

Even then, I found that I wanted larger structures than what I had generated. Watersheds were one attempt to build those larger structures but I need to try more approaches of grouping polygons together. I haven't found something I'm happy with.

I'm not sure how Dwarf Fortress does it. Given how brilliant those guys are I wouldn't be surprised if they have a sophisticated “computer vision” type of algorithm.
> 13 votes

# Answer
For your first question, my best guess would be to use an edge detection algorithm to find the limits of your natural regions (forest, hills, ...). Lots of algorithms exist for this kind of problem.

For the second question, you could use your own idea to spawn a castle (usually on top of a hill for good defense, and near fresh water), then use a voronoi algorithm to have regions around each castle. You can use noise or your biomes limits to make the boundaries more realistic.
> 3 votes

---
Tags: 2d, maps, procedural-generation
---


# Question
Title: Path-finding algorithms for Polar coordinate based maze?
Following on from my question about moving a sprite in a circle, assuming that you have a maze which is shaped like a a set of circles with holes in them and barriers between them.

Location of a sprite is stored in polar coordinates and then translated into cartesian coordinates to be rendered.

I'm going to assume that most path finding algorithms rely on cartesian geometry, is there a path finding algorithm I can use to allow "beasties" to chase my players sprite?

# Answer
Actually, "most pathfinding algorithms" don't rely on any specific set of coordinate systems at all.

Most algorithms, like the most widely spread and probably most popular of them, the A\* algorithm, just rely on a set of connected nodes in a graph and functions which estimate or straight up calculate the cost of moving from one node to another.

The awesome thing about this is that they work anywhere, in any kind of space or structure that you can imagine, as long as you have a way of calculating the cost of moving from one node to another.

As an answer to your question: You can (for example) use A\* and construct your circle-y maze as a graph where the nodes are simply points on the imaginary circles that run through your maze, and the heuristic functions can still be based on the distance between two nodes.

If you wonder what your graph inside a circular maze should look like (*wink wink :P*), here's how I would basically do it (the black dots being the nodes and the lines being the connections between them):

I think my graph even has too many points, since you only need so much that your entities don't run into walls when they try to go straight from one node to another.

The better way to do this would be to use navigation meshes, meaning "surfaces as nodes" instead of just points (in this case a lot faster, since you'd need very few of them) would ). But if you understand how A\* generally works they're not hard to implement at all.
> 4 votes

# Answer
The exact geometry doesn't matter for path-finding algorithms. All that matters are connections between nodes. Applying any traditionally-Cartesian path-finding algorithm to your polar coordinates should be seamless--the algorithm doesn't care whether `x` and `y` are *actually* `angle` and `distance`.
> 2 votes

---
Tags: path-finding, coordinates
---


title: 2D sprites in 3D space?

text:
# Question
Title: 2D sprites in 3D space?
How can I draw a 2D sprite to look like it's at a particular placement in the 3D world?

My goal is to use this as loose items in the world.

Minecraft Example: https://lh6.googleusercontent.com/-HMk5tW\_cI-Y/TiYx71XkwtI/AAAAAAAAAZQ/jeaTfiMW1Ow/2011-07-19\_20.26.18.png

# Answer
You'd render a quad in 3D space, using the sprite as the texture for that quad. You can billboard that quad so that it always faces the player (this is what Minecraft does for its non-block inventory items when they're on the ground, if I recall correctly).
> 9 votes

# Answer
Traditionally, this is done by rendering a single quad with the sprite applied to it as a texture. The quad is generally rotated so that it always faces the player (usually only around the vertical axis).
> 3 votes

---
Tags: xna, sprites
---


# Question
Title: Can you help me find resources for developing a top-down 2D game in Java?
I just started reading about games, and I'm going to develop a game where a person is moving around on a 2D map. My preferred language is Java. Is that suitable to develop games?

I'm going to develop a desktop app and need some help to get started. Can someone please give me some good resources for newbies?

# Answer
Personally I am a big fan of jMonkey Engine.Its a shader based & geared toward high end games productions. jGame & Slick2D are very good for 2d games. ligGDX might interest you. All of these are under very active development.

There is no problem in choosing 3d engines for making 2d games. Just ignore that extra D, unless you have some serious issues with that one.

So, I whole heartily suggest you to start with jMonkey Engine, cause its fun, easy to use, has a very active community and comes with an awesome jMonkey Platform which is build on top of Netbeans platform, where every update & features is just one click away. You might end up in using it with many other projects.

There are other libraries too, but they lack community/development activity.

* Genuts - last update 2004
* PulpCore - last update 2009
* GOLDEN T GAME ENGINE (GTGE) - last update 2010
* Basilisk Game Library - last update 2009

You can write your own engine if want to.Then you should use opengl wrapper library, either LWJGL or JOGL. Lwjgl is more widely used then JOGL.
> 4 votes

# Answer
iamcreasy gave you some great examples of some engines to use for making a game in Java. They will definitely be helpful in your development process.

I wanted to give you a link to a good set of tutorials for 2D games in Java, without any engines. It walks through how to create some of the classics (like Tetris) in Java. The author walks you through them, explains the code, and is in general, a very big help.

You can find the above-mention tutorials here: http://zetcode.com/tutorials/javagamestutorial/

Hope this was a help, and good luck.
> 3 votes

---
Tags: 2d, java
---


# Question
Title: How can I transmit move information from player to player in a web application?
I am trying to create an online chess game using ActionScript and Flex. It works well when I have two players on the same PC, but I want to publish it as a web app. How can I transmit a move or action from one user to another, such that the other user sees what the first one did?

# Answer
You will need some kind of server in the middle to manage the game state and transmit game data to the players.

The server's role is to take a player's move, make sure it is legal, update the board state based on the move, then push that change out to the other player so their game updates.

As far as technology goes, check out SmartFoxServer (http://www.smartfoxserver.com/) - something like it would do very well as your back-end technology.

Additionally, a quick Google search of "open source chess server" shows quite a few of them exist. You might be better off leveraging someone else's work. Remember, the server's job is not just to pass messages between game clients. It also has to confirm that all moves are legal, and that players aren't trying to cheat by sending illegal moves.
> 1 votes

---
Tags: software-engineering, actionscript-3, flex
---


# Question
Title: How can I draw a sprite that inverts the colors behind it for an aiming reticle?
In XNA, how can I draw a sprite on the screen that inverts the colors behind that sprite (i.e. the colors that would appear if the sprite weren't in the way of them)?

I feel this is the best technique for an aiming cursor in a game, but I'm unsure how I can achieve this. I'm open to other ideas for aiming cursors if this is less than ideal.

# Answer
> 9 votes
To do this in XNA, you will need to use a shader. You will need to render your scene to a texture (Or, render just the portion the cursor covers), and then draw the cursor using that texture and a shader that inverts the color. Unless you've already got a deferred renderer, this will probably be more hassle than it's worth. If you do, you can use the existing depth/color buffers, and re-shade the pixels covered by the cursor in your color-inverting shader.

# Answer
> 1 votes
A simple method to reduce the likelihood that your cursor is the same color as your background is to sample the center pixel beneath your cursor, and invert that color. You would draw your entire cursor with that color, or use it to apply a shading.

Or sample say 5 pixels (if it's a cross hair you could sample the center, top, bottom, left, right pixel) and average them, then invert the average.

# Answer
> 0 votes
You can do this by altering the way that you are rendering the game. First render to a texture http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Render\_to\_texture.php.

After you have rendered the frame to the texture you can then edit the colours of the location that you are interested in:

```
Color pixel;
int xlocationOfSprite;
int ylocationOfSprite;
int widthOfSprite;
int heightOfSprite;

for (int x = xlocationOfSprite; x < widthOfSprite; x++)
{
    for (int y = ylocationOfSprite; y < heightOfSprite; y++)
    {
        pixel = bitmap.GetPixel(x, y);

        // Do what ever color manipulation you want

        bitmap.SetPixel(x, y, pixel);
    }
}

```

Then render the modified texture to the screen.

# Answer
> 0 votes
A quick 'n' cheesy way goes something like:

* Enable alpha blending
* Set your source blend factor to one minus dest color
* Set your dest blend factor to one minus source alpha
* Set your blend equation to additive
* Draw the sprite as normal
* Disable any states you need to disable

Just tested this (in OpenGL, not XNA, but the principle is the same) and it works well enough.

---
Tags: xna, aiming
---


title: Using HTML for interface?

text:
# Question
Title: Using HTML for interface?
The game I've been working on uses opengl/sfml for graphics. I'm currently working on the interface and I've found determining all the proper offsets/positioning etc. to be a pain. To make it configurable, I'll likely end up parsing a making a bunch of xml files to parse that tell my program what images to use/where to position them stc. for the interface.

Since I'm going to need to do that anyways, I was curious if it's possible to embed an html renderer into an app, and have it display over graphics drawn in opengl? That way i could theoretically use html pages to design the interface

If it is possible, how difficult would it be and is it a good idea? are there any projects that do this already?

Thanks

# Answer
Try looking at Awesomium \- it wraps the Chromium engine in a 3D renderer and HTML UIs are one of their main selling points.
> 10 votes

# Answer
Also, take a look at libRocket.

It's kind of based on HTML4 but it allows you to extend it rather easily with custom components, if you import a reset stylesheet things like h1 and hr will work, and by default it supports these elements.

there are also samples with a SFML renderer available and it's open source (MIT licence, allows you to use it in closed source projects without problems).

I've not used it with SFML yet myself, but with the Ogre3d samples it was really easy to set up.
> 5 votes

---
Tags: c++, opengl, interface
---


# Question
Title: Separating Sprites from Models with PyGame
So I'm trying to code a game using the Model-View-Controller pattern, and therefore have a need to separate the models for my game objects with their sprite representations. The problem that I'm running into is with PyGame's sprite class. For example, let's take the code below for a Tank object in my game.

```
class Tank(Projectile):
    '''A tank object.'''
    MAX_SPEED = 8.0

    @property
    def MAX_TURN(self):
        return 10.0 - 0.75 * abs(self.velocity)

    def __init__(self, position=(0, 0), heading=0.0, power=100.0, name=None):
        Projectile.__init__(self, position, heading)

        self.gun = Gun(self)
        self.radar = Radar(self)

        self.power = power
        self.name = name

    def update(self, dt):
        super(Tank, self).update(dt) #Just writing this here for illustrative purposes

```

Additionally, in a separate views file, I have the code for the basis of a sprite:

```
class TankSprite(RotatableSprite):
    _image = pygame.image.load('images/tank/body.png').convert_alpha()
    _layer = 0
TankSprite.groups = tank_group, all_group

```

Now the standard solution might just be to merge these two into one, and then use pygame's pygame.sprite.group.update() method to update and draw everything as desired. But with a MVC pattern, I run into a few problems:

* First, there is no way of knowing when a new object is created. For example, when the Tank fires its Gun, its creates a Bullet object. Since the Bullet is a model, there is no way to detect this creation without some awkward View code in the Models.
* Second, I don't believe I can use pygame's collision methods or Group objects, which isn't the worst, but somewhat awkward.

Really, the bullet problem is killing me more than anything else. Any help would be appreciated.

# Answer
As you've written it, your `Tank` is both your model and your controller. Normally, you either have a view controller and a model controller that talk to each other and their appropriate other part, or a single controller that mediates between the view and model directly.

There are a variety of ways to solve this:

* Accept that Tanks are models and controllers. Let the Tank manage its own view.
* Split the Tank class into separate model and controller classes. The controller mediates the two so they don't need to know about each other; object creation is a controller responsibility.
* Realize that MVC is about abstractions, and there are ways to do abstractions that do not require three totally separate classes; two or three mixins communicating via shared state on the same object work just as well in Python.
* Realize that MVC is a bad pattern for games, especially simple games in very high level languages, and just do what works.
> 3 votes

---
Tags: architecture, sprites, models, pygame
---


# Question
Title: Why aren't linked lists more common data structures for enemies?
I was recently listen to a talk that Jonathan Blow gave, you can find it here. In the talk, he was talking about what data structures he (and he seemed to imply many others) use, and why. Which is to say that he simply used arrays to store data, and use the naive approach to find data in it, meaning iterate through the array until you found what you wanted, assuming it wasn't in a performance critical place in the code. He gave the example of loading data from a wad file in doom, which while fast, still took that naive approach (at least according to the talk, I haven't looked at the source code since I have not a clue to where I should begin). The reason he gave for this was because while it may be slightly slower to do things the naive way, it's not much, and in many cases, not noticeable, so it's better to optomize how much work you can get done in your lifetime, than to make things a millisecond faster, again, assuming it's not in your physics engine or something like that.

All this seems well and good, except I have one question, why not linked lists rather than arrays? Sure, if you had to make your own linked list class, I would be on board, but in c++ anyway, assuming your using STL, you only need to declare the type as a list, rather than as a vector, and use iterators to loop over it, rather than looping an index.

The advantages of using a linked list though seem much greater, for example, if you can be guaranteed that nothing is going to be removed from it while your iterating, you don't need to have locks around it, because adding data doesn't have the possibility of moving everything (or is that a bad assumption). Also, in general, moving data is slow, although this could potentially be avoided if you know the size of your data by reserving the space.

Another advantage is when you do remove data, you just tell the list to remove it, and it just needs to change a few pointers, and call a destructor, which can be done pretty quickly. But to remove something from an array/vector, you have to either shift everything back one, or possibly add a flag saying that it has been deleted. (Or, another possibility if you don't care about the order of the data, is move the data at the end index, to the data in the now deleted position). Either way, this seems like it is a lot of extra, unneeded work, or potentially too slow.

I did take a look around and found this, which claimed that a lot of older developers didn't want to use STL because it wasn't mature enough. Also, older games AFAIK, used C rather than C++, which also doesn't have STL. And I could see a case there for using arrays rather than linked lists, because you would have to make your own (which while simple enough to do, could potentially lead to many more errors).

I also read that it's a bad idea to create iterators in Java (due to the garbage collector), but that idea seems moot in languages such as C++, where there isn't a garbage collector, and I would imagine that linked list iterators are pretty lightweight (admittedly probably not as lightweight as vector iterators though). Or is this also a bad assumption, and it's better/faster just to use an index in your loop, and increase that.

# Answer
My answer to this question would be the same as my answer to this other question: When should vector/list be used?

Basically, cache-coherency-related performance gains from having everything be contiguous in memory is more valuable than "Big O" algorithm theoretical performance from linked lists.
> 14 votes

# Answer
Usually for performance reasons. Take a look at the example of the WAD file that you gave. You know at the time that you pack that level how many elements of the array/list that you are going to have. Therefore you can allocate one chunk of memory, fill it in once via DMA from the media to the structure and keep moving. As you walk the array you can take advantage of the cache of the CPU as it will be loading in the next elements that you are going to be iterating on. As for removing the data, it's a WAD file describing a level, what exactly are you going to remove?

That's not to say that linked lists aren't useful, just that there are a lot of uses for a plain old array particularly when it comes to streaming in resources for a level.

Another issue is overhead. Are you loading in thousands or tens of thousands (vertices in a model / world) of elements? Great that 32 bit pointer to the next element, or 64 bits if it's doubly linked just increased your memory footprint by 33% without actually buying you anything because you're still never going to remove a vertex from the middle of a model.

Also take a look at the Electronic Arts version of the STL EASTL http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html
> 3 votes

# Answer
Arrays are dependable, static in size and are never prone to run time degradation and fragmenting. I believe that using complex structures like linked lists smells of optimizing before measuring and over-engineering before need, and those are a sin if ever there was one.

This is, of course, in the arena of small budget development where wasted effort that doesn't directly improve the end user experience means hamburger on the table instead of steak. Or to put it another way, Jonathan is optimizing for user experience and not run time performance.
> 1 votes

---
Tags: c++, vector, data-structure
---


# Question
Title: Why am I having these weird framerate issues with OpenGL on Windows?
I'm using OpenGL on windows (have been for a while now), and I've come across a strange issue.

Once every so often, the rate at which frames are presented on the screen drops to roughly 10 fps. However, my framerate counter stays at the usual framerate (2000fps in the menu, 300fps in game).

My framerate counter is based on the time between draw calls, so the graphics card is definitly rendering 2000 frames a second.

What is the problem? How can I fix it?

EDIT: I forgot to mention, this only happens when running in windowed mode.

# Answer
> 4 votes
Definitely rendering at 2000 fps? Nah, I guess you're measuring elapsed frame time like usual, which means you're measuring time it took for the driver to generate the GPU commands and not the time it took the GPU to actually render the frame. After a while CPU waits for the GPU to catch up and it shows as spike in frame time.

As for possible reasons... Well, it could be everything starting from bad hardware or drivers and ending with bad code. Try to do the simplest graphics call possible:

```
while(1)
{
  glXSwapBuffers();
  // This should use QueryPerformanceCounter/QueryPerformanceFrequency
  CalculateElapsedTime();
}

```

And then see if it still spikes. If it doesn't, add a code until it spikes again, and if it does, then it's a technical issue. For additional confirmation enable VSync and see if spiking rate changes. Launch a HWMonitor and see if temperatures and voltages are OK, check System Event Log, use GPUView with xperf, maybe try to somehow debug it with gDEBugger, change drivers, change hardware... Possibilities are endless :)

EDIT: Maik Semder actually gave a better advice :) Your problem may be completely unrelated to the video at all, so check what you're doing every frame, look at the GC, wrap different OpenGL calls with QueryPerformanceCounter.

---
Tags: opengl, graphics, frame-rate
---


title: What is the purpose of glEdgeFlagv?

text:
# Question
Title: What is the purpose of glEdgeFlagv?
I know that what both glEdgeFlagv and glEdgeFlag do is toggle boundary edge status, but my question is why does the v version exist when the documentation specifies that the only difference is that glEdgeFlagv takes (quoting from documentation):

> a pointer to an array that contains a single Boolean element, which replaces the current edge flag value.

What's the point of having a special version that takes a pointer to an array of length one? I can't imagine its to let you toggle the pointed-to bool to change the value later because the documentation would have to mention that to avoid inadvertent frees. I don't know of any platform where a pointer is smaller than a bool. When would one use glEdgeFlagv instead of glEdgeFlag?

# Answer
It is there for the sake of completeness and consistency with the other APIs. There are vector forms of glVertex, glColor, glTexCoord, etc. glEdgeFlag is part of that group of functions; therefore, there is a vector version of glEdgeFlag.
> 3 votes

# Answer
If you are looking for just the outline portion of the graphic, you could try using an emboss filter on it. The outline will be highlighted in white and remove the other non-white pixels below a certain tolerance.

Here's a decent link talking about various image filters and matrices for accomplishing them: Image Processing for Dummies with C# and GDI+ Part 2 - Convolution Filters
> 0 votes

---
Tags: opengl, c++
---


title: Enum Vs. Integer for Skill Values

text:
# Question
Title: Enum Vs. Integer for Skill Values
I'm implementing a basic skill and attribute system, though I'm having second thoughts about how I should go about it.

For example, I could use a Dictionary/HashMap which uses SkillType enums to represent keys, and integer values representing the values. But should I do this?

```
public class Skills
{
    public IDictionary<StatType, Int> skills; //StatType is enum, being the key; the int //is the value.

}

vs.

public class Skills
{
    public int LongBlade, Armor, Marksman; //...etc
}

```

I'd like to know the benefits of type safety here, as opposed to just using basic integers. Any recommendations?

# Answer
If there is eventually going to be:

* a large variety of skill types across your game,
* or ability-granting items,
* or ability-granting buffs,
* or a large ability tree,

then I start to prefer the flexibility of string or integer keys in a dictionary instead of individual instance fields or even a dictionary with an enum key.

My reasoning-- *Because you may soon realize...*

> Boy, it'd be nice if I could tweak my mathcraft and select unit abilities in (my favorite text editor | Excel | a custom tool ).

...at which point a dictionary with string or integer keys become a more natural fit than having to maintain enum values or a long list of instance fields yourself. However, said tool could always be written to generate C# code too, so you may be able to find a happy hybrid.

If your game complexity is going to be fairly simple and your variety of skills small, then managing instance fields by hand (instead of dictionary & enum) seems more convenient and avoids a level of indirection, both at run-time and "keystroke"-time.
> 8 votes

---
Tags: c#
---


# Question
Title: How can I render a circular progress bar procedurally?
I'm working in Flash AS3, but pseudo-code or any other language is fine.

How can I make a circular progress bar? Akin to the ship bars in Pax Britanica, you can see them in the screenshot here.

Apart from making them frame by frame, is there some obvious solution I'm missing here?

I'm seeking the equivalent of stretching a rectangle for a regular progress bar, or using a simple mask (if such a solution exists).

(Also I can't tag this with circle or progress bar due to lack of rep if anyone could that would be great)

# Answer
First I'll explain the principle, then the drawing part:

In my example I'm assuming that you have a progress value of 0 to 100 (%), even though anything else will do.

On a straight line, the current position of progress-bar would simply be that progress value.

On a circle you get that position with trigonometry. Any point on a circle is given as:

```
point.x = r * cos(angle);
point.y = r * sin(angle);

```

where r is the radius of the circle. As you see, the angle is the only variable in those equations. That means that you somehow have to integrate your progress into the angle.

The solution is simple: One "run" around the circle equals 2\*Pi (or 360 degrees). You have to split that distance into 100 smaller parts, so that when the progress value is 100, the value inside cos() and sin() is 2\*pi (or 360 degrees).

You achieve that by simply dividing 2\*pi (or 360 degrees) by 100 and multiplying it with the progress:

```
float step = 2*pi/100;

point.x = r * cos(progress * step);
point.y = r * sin(progress * step);

```

Now to the drawing part.

I don't know anything about Actionscript3 (or Flash, for that matter), so I can't tell you the exact procedures, but in general there would be two ways to do this:

First, and (in my opinion easier of the two): Draw the partial circle manually as simply a connection of colored lines with a certain thickness (if you don't need a texture on it and a simple color suffices), or draw the circle as a connection of textured quads (if you need texturing).

Second: You draw a picture which represents your fully-loaded circle and load it as a texture, put it on a quad and render it. Then, you again manually draw a partial circle over that quad and only render the part of the textured quad where the circle is rendered in front of it. In OpenGL, for example, you could easily do this using the stencil buffer.

If you want to know how to calculate the different points on your circle to use them to assemble the required polygons/lines, you can take a look at the above equations again:

```
point.x = r * cos(angle);
point.y = r * sin(angle);

```

You can run those inside a for-loop that runs from 0 to your current progress, for example, if it was a circle that consisted of a series of connected dots (in c++ syntax):

```
float granularity = 2*PI/required_granularity; //determines how smooth your circle will look
float step = 2*PI/100.0f;

list<Vector2> points; //list of all the calculated points
for(float angle=0; angle < progress*step; angle += granularity)
{
    Vector2 point(radius*cos(angle), radius*sin(angle));
    points.push_back(point); //adds the point to the list
}

```

Now these points will all be centered on the origin of your coordinate system, so you need to move them to whatever position where you want your circle to be. But I think you can figure that one out yourself :P
> 19 votes

# Answer
Looks like you're wanting to draw an arc. An arc that's thick. I found this article for doing just that in AS3. Check out the demo at the bottom.
> 4 votes

# Answer
I haven't tried the following, but it sounds like it should work.

You need two images:

1. the outer HUD graphic, make the portion you want the progress to show through transparent
2. a solid color circle image the radius of the progress meter, then cut the bottom half off and make that transparent (it could be a half square really as the HUD portion will cover the rest)

The following assumes your 0% (and 100%) mark is at the 9 o'clock position.

---

**If your progress is 50% or less:**

* Rotate and draw the semi-circle so the desired percent is visible in the top portion
* Do a rectangular cut of the bottom half area to remove the left starting of the semi-circle showing in the bottom area
* Draw the top layer HUD graphic

---

**If your progress is \> 50%:**

* Draw the semi-circle so that it fills the entire top half (50% mark). You should need no rotation
* Rotate and draw the semi-circle again to reflect the remaining percentage
* For example, if you want 60%, draw the first copy to show 50% then rotate and draw the second copy to show another 10%
* Draw the top layer HUD graphic

I'm not sure how to do this specifically (or if it's even possible) in AS3. I hope this makes sense (oh, and actually works!).
> 1 votes

# Answer
Another method I saw was using shaders.

You only need one image, the entire HUD image, with the progress area in a gradient gray scale. Start at the 0% position (9 o'clock for example) with pure white and gradually progress to black at the 100% position.

You can't have any gray in your HUD portion, including no white or black. If you need to use those colors, then choose another pure color for your gradient scale (a color not used anywhere else).

Have your program pass the shader the progress value in the range of '0.0' to '1.0' (or whatever scale your shader language uses for it's color ranges). You could also pass the shader a progress bar color (and the 'off' color if you wish) if you want the color to change dynamically, such as when empty (or full) to warn the player.

In your shader you evaluate each source pixel, and if it's pure gray (each R,G,B has the same value) then that pixel is part of the progress meter. If it's not just pass the original color through. If it's a progress meter pixel, you have to determine if it should be the 'on' color, or the 'off' color. Just simply check the pixel color (it's pure gray, so you only need to check say the 'red' component) to see if it's above or below the passed progress value. The effect is that any gray color below the progress value will turn on, the others will turn off.
> 0 votes

---
Tags: mathematics, actionscript-3
---


# Question
Title: How can I draw beautiful lines with XNA on WP7?
I'm trying to figure out how to draw good looking lines using XNA on the WP7 platform. By good looking I mean something not skinny and flat that a simple primitive gives you. A nice gradient, or texture or something applied.

It would be pretty easy if the lines were all straight, but I need to be able to make 45\* and 90\* turns.

Has anyone else tried doing this? I have found ways to do it, but they all require custom shaders which the platform doesn't support. Like this one for example

Example output from that library:

# Answer
What the vertex shader for the round-line library that you linked does is simply take your two positions and use those to transform a pre-calculated outline of a line (including appropriate stretching).

You could do simply do the same transformations on the CPU, using `DrawUserPrimitives` or a `DynamicVertexBuffer` to draw them via `BasicEffect`.

You could then also calculate appropriate texture-coordinates on the CPU, to apply a texture of your choice (or use vertex colours for a gradient, and so on).

For a small number of lines, this should be perfectly acceptable, performance-wise.
> 1 votes

---
Tags: xna, windows-phone-7
---


title: Is game development a super elite club?

text:
# Question
Title: Is game development a super elite club?
We all read job vacancies via the internet like GitHub jobs or StackExchange Careers 2.0 for example. You know, web app development, iOS/Android jobs and many other things. We even read about jobs ads in Google, Apple or any other big company.

Why don't we read about "Game Developer" vacancies? Is the demand for game developers so low? Or are game developers really rare?

How are companies like EA, Konami or Activision are getting their developers?

How can I overcome this response to an application: "You can't work for us because you don't have experience in developing games." How am I supposed to get experience if I'm not able to work in the field?

# Answer
> 22 votes
The first question is where are you looking? If you are interested in a particular studio, outside of industry sites the best place to find jobs for the studios is on their own site.

In my experience (from just looking around, speaking to people) the industry has no shortage of applicants. Because of that, there is no real need to expend extra resources paying a premium to get listed on various jobs sites. People interested in their companies will already be checking their website.

Finally, the experience issue. The positions that you see advertised on these sites are generally *not* for entry-level positions.

* Larger game companies (like the ones you listed) get tons of entry level resumes sent to them from a variety of people. There is little financial incentive to advertise that they are looking for entry level people.

+ *Also, I've yet to meet a recruiter that wasn't ok with having my resume on file. It's generally understood that companies need fresh blood.*
* What isn't always known, is if they have any place to fit the higher experience people (at their right pay grades and all) so it's beneficial to advertise it. Also, these people are generally harder to find, and might be otherwise employed.

+ *These people are less likely to shoot resume's into the dark.*

Of course, making a cool demo never hurts.

For more information on applying for a job in the games industry, I turn to Sloperama: http://www.sloperama.com/advice/jobapp.htm

# Answer
> 13 votes
You don't see game development positions on general programming job sites because good candidates don't come from there. With few exceptions (web/database guys, for one), game programming is such a different beast than the majority of programming jobs out there. And "game programmer" is one of those "sexy" titles that has a lot of casual people throwing their hat into the ring and not being good fits for it. Your signal/noise ratio from the responses would be crap. Not to mention, most \[experienced\] game programmers aren't looking at sites like that because they're not the kinds of jobs they're trained for or want to do.

Even if a person you find on a general programming site is a smart guy and can pick up on the topics, their salary expectations are probably not in the ballpark of what most game programmers make. Most people who have a cushy 100k/year programming job aren't going to take one with most likely longer hours and a steep pay cut.

So most game companies put their high profile positions on their own site and on game specific job boards like gamasutra. From the applicant's perspective, there usually aren't that many game companies in any given city (with a few notable exceptions like L.A.), so for looking for a job if you're not in a position to move you can usually get the short list and apply directly.

There are a few other places to get good people. Job fairs at game educational places is one. Booths at industry events (i.e. GDC) is another. If you manage to go to GDC, it's amusing to see the huge line for "students" vs "professionals" for the larger, well known companies out there.

# Answer
> 2 votes
I think you need to look in the right places, Edge magazine in the UK always has a section on game jobs, and all the articles have adverts for games companies looking for developers.

Likewise Gamesindustry.biz advertises for developer jobs.

There are recruiters who specialize in the games industry here is a list of agencies and sites that might be of help.

---
Tags: career, jobs
---


# Question
Title: How do I find the contour points of a png?
In my game, I need a way to produce convex polygons from pngs of objects.

For example, a maple leaf would result like this:

Essentially right now, the way my algorithm works is by putting all pixels that have an alpha of 255 in a list. I then create a convex hull from this list, and finally optimize the hull with a graph algorithm. The part I'm trying to optimize is the first part. I'd like a way to have the outline / border pixels of the shape rather than all pixels of the shape.

What sort of algorithm could do this?

Thanks

# Answer
> 5 votes
Scan each line and only record a point on entry to your 255 areas and then another point on exit from the 255 areas. You can then pick a point and start finding closest neighbors and walk all the way around to build your contour lines.

That will end up being pretty dense, but then you could collapse multiple points that are on the same slope into a beginning and end point for your final result.

# Answer
> 3 votes
The marching squares algorithm should work really well for this. Another really good algorithm is the "Canny edge-detection algorithm".

For your purposes, marching squares should be good enough (and way faster than canny), since you don't want to actually detect lines "inside" the image but just the outlines of the shape (using the alpha).

---
Tags: c++, algorithm
---


# Question
Title: When do I need to ask for permission to recreate an old game?
> **Possible Duplicates:**
> How closely can a game resemble another game without legal problems
> Legal issues for a "fangame" of a commercial franchise?

I want to do a mobile version of an old game I used to like called Bow And Arrow (video, game). There's a project already port it in Ruby. I'm wondering if I can do a remake of this game. Do I have to get permission from the creator, or does it only matter if I use the same resources (graphics and sound)?

# Answer
> 6 votes
Generally, and nearly universally around the world: *game systems* (pure mathematical formulas and algorithms) can't be copyrighted, and thus can be copied freely, even without being nice and asking. However, In some jurisdictions they can be protected - in parts or whole - by *patents*.

For everything else, **ask a lawyer**.

---
Tags: legal, copyright
---


# Question
Title: Sprite vs 3d Model in Flash Facebook Game
I'm looking at creating a real time strategy/tower defense mashup game for facebook (and other platforms like google+) along the same feel, but of course different mechanics, as backyard monsters.

The model animations will hopefully be fairly thorough, with maybe three different animations (walking, attacking, resting) and 30 different monsters to model. The models themselves will be VERY simple and likely low texture since I'm not an animator, so I'm looking for the solution that's the best balance between ease of use and processor cost.

When creating a game like this is it generally better to go a full fledged 3d model route for the "monsters" or is it better to model the animations in an external editor and turn them into a sprite?

# Answer
> 6 votes
The workflow for 3D models is most likely less complicated than rendering all your models to sprites. If you change some detail in a texture, you don't have to render all the sprites again etc.

Since you're targeting flash, you'll have to consider the limitations of the platform as well. The new 3D APIs (molehill) are capable of performant 3D graphics, however it might take quite some time till this player will be released and has a wide user-base.

Current flash 3D engines like Papervision or Away3D could work, they will put a heavy load on the CPU though, even with low poly-count. Also z-fighting is a constant issue with these engines. If you plan to use a fixed viewing-angle, you can prepare your models in a way that minimizes these issues though.

If you go the sprite-route, you can leverage existing frameworks like Flixel or Flashpunk and it won't matter how complex your models are. Also the amount of monsters/entities you can display on screen will be much higher with the sprite approach.

There's probably lots of people that play games on Facebook that have an old and/or slow CPU (eg. netbooks), so performance can be an issue.

So for your target audience, it would be best to go the sprite/bitmap route as of now. 3D will become viable with the new flash 3D APIs. If you're interested in that, this project might be a good way to learn about this new technology. Early adoption might give you more visitors, but it's also harder to do since APIs might change or tools/frameworks aren't mature yet.

---
Tags: 3d, flash, sprites
---


title: Game Maker not recognizing variable

text:
# Question
Title: Game Maker not recognizing variable
Attempting to set up a targeting array for a MMO-style game in GameMaker8 Pro, I have this code in the create event for the player's character, which is and has been running perfectly fine:

```
j = 0
i = 0
g = 0
for (i=100000; i<1000000; i+=1) if instance_exists(i) {if i.object_index = enemy         {global.ttarget[j] = i j+=1}  if i.object_index = rk or i.object_index = sage    {global.etarget[g] = i g += 1}}
global.rmtargets = j
global.etargets = g

```

Then running this code in the step event for the player character:

```
h = 0
g = 0
i = 0
for (i=0; i<global.rmtargets; i+=1) global.target[i] = 0
global.target[0]=101139
for (h = 0; h<global.rmtargets; h+=1){hv = -1
for (g = 0; g<global.rmtargets; g+=1){if global.ttarget[g].range > hv {hv =    global.ttarget[g].range}}
global.target[h] = hv
global.ttarget[h] = -1}

```

Returns this error message:

ERROR in action number 1 of Step Event for object rk:

Error in code at line 8: for (g = 0; g hv {hv = global.ttarget\[g\].range}} at position 61: Unknown variable range

Even though I have this in the create event for the enemy:

```
range = 0
range = distance_to_object(rk)

```

And I've used this sort of syntax all over:

```
global.target[target].threat[s] += damage

```

Help? Any ideas why Game Maker won't recognize the variable?

# Answer
I think the problem is that variable can not have "under variable", in GM is this possible even with the objects.
> 1 votes

# Answer
The enemy at that point in the array has probably been destroyed. Instead of looping through an array full of potentially-gone instance ids, you should use `with`:

```
var hv;
hv = -1
with (enemy) {
    if (range > hv)
        hv = range
}

```

Replace the inner for loop of your step event with that and then you can create and destroy enemies all you like without worrying about updating the now-unnecessary array.
> 0 votes

---
Tags: game-mechanics
---


# Question
Title: What common spritesheet formats for 2D Top-Downish Games are there?
For 2D top-down style sprites, what commonly used spritesheet formats are available?

By a sprite sheet format, I mean this: for any RPG Maker sprite sheet, you can count on all the walk animations being in the same place on the image between characters. For Final Fantasy 6's characters, you could open all their sprite sheets and compare them and in each one, the walk animations, crouching sprites, surprised sprites, etc would all be in the same places. They all adhere to a standard.

I'm using RPG Maker XP right now and it defines character tilesets as having four states -- facing up, down, left, and right, each with animation. This is really restrictive, and I'd rather have more options like Final Fantasy 6.

So are there any more common sprite sheet formats out there that I can use?

# Answer
As stated, there's not really any "standard system" for sprites or tiles. The closest such thing is something like RPG Maker sprites, which are only standard because there's a community built around the game (much in the same way that there's tilesets or mods for other popular games)

That said, there's a few options. You could find a set of free graphics to use and load them into game in that format. Many times the same artist will create sprites with a "standard" layout. The downside to this approach is that your options would be pretty limited.

A potentially better solution is to use one of the RPG Maker formats. The trick is that you are NOT limited in the same way that RPG Maker is, since you can define the layout of the sprite sheet. So, you can expand on the different actions per character to be whatever you want. The RPG Maker sprites have 12 frames for each 'character', 4 directions with 3 frames of animation per direction. A lot of times, an artist would make more 'actions' for a specific character, and would simply use another 'character' slot to allow for another 12 frames of animation, or poses, or whatever.

The reason commercial games (like FF6) have unique spritesheet layouts is because **each game customized the layout for the game being made**. RPG maker uses a standard layout format because it's a tool to make the games, and so it needed to be able to have a standard. Unless you're making a tool to make other games, you can easily make whatever changes you want to that standard. It might require some time spent editing graphics, but when making games, it's pretty important to have skills to edit graphics files, unless you plan on only making text based game.
> 2 votes

# Answer
There are no "tileset systems." The only generic solution games pick up is *how tilesets work on a basic level.*

Here's how tilesets work:

* The sprite sheets contain sprites. These sprites all belong to a "region" which corresponds to a particular state. All those "walking right" sprites arranged in a row are in the region with the "walking right" state. The "dead" sprite (a still body, with no frames of animation) is its own region with the "dead" state.
* A state may have any number of animation frames, or one frame (no animation). Different states can have different amount of animation frames. Some animations can be played faster, slower, or irregularly compared to others.
* A character uses the sprites + animation for whatever state it's in.

Both FF6 and RPG maker do exactly that. FF6 however picked more states and more animation than RPG maker did, probably because they were actually going to make some money for it. Every other game has done the same thing, choosing exactly the states that suit them and exactly the frames of animation they want.

They're all just companies fulfilling their unique requirements using the same technique: sprite sheets. It's not like there's a third party offering an engine which features certain states and offers Y frames of animation for each. Each developer just developed *their own* system.

So here's your generic solution: **Start wondering about *your* requirements!** What states do you want? How do you want each of them animated? Then use the same basic technique as anyone else: draw them, arrange them in regions and animate them.
> 2 votes

# Answer
I'm kind of confused about what you're asking, but if a file format and tilemap editor in any way helps you, check out the Tiled editor and the TMX tile map format that it works with. I've used it for a sneaking game (top down tilemap) and for shmup levels (just lined up the spawns).

If you're developing for the iPhone/Mac and in objective-c, cocos2d supports reading TMX maps and rendering them.
> 0 votes

---
Tags: assets
---


# Question
Title: Does inflating scores make players happier?
I realize that this will depend on a game-to-game, situation-to-situation basis and that this is not a very technical question, but I remember hearing in a tech podcast a few years ago that inflated numbers of points (e.g. 1000 points vs. 1 point) was preferable in games because it was either a standard or because it had been shown to produce better feedback/experience from users. Either case, it seemed to make users happier than lower numbers of points.

I have since been unable to find supportive evidence either way for the theory that inflating scores can keep the user engaged.

Is this inflated-point theory true? Where can I find more information and, particularly, some experimental data on different approaches and their effectiveness?

# Answer
> 24 votes
I find myself most satisfied when I see what appear at first glance to be prime numbers.

If the score always just adds a 0 (10, 20, 50, 200, 300 etc.) at the end, I feel cheated.

Multiples of 5 (5, 25, 45, 80, 95 etc.) are a bit better, but you quickly catch on to the fact that your accomplishment is worth 1/5 of what's being shown.

Numbers like 47, 76, 298 etc. feel more meaningful than 45, 75, 300 etc., and you end up with the illusion that there's some really precise math and balancing going on, legitimizing your score.

So to answer your question, big numbers are probably better, but only if it's not obvious that they're inflated.

Oh, and don't forget the thousands separators -- those are achievements in themselves.

# Answer
> 11 votes
I would say the main reason why some games use such high numbers is, because they don't want to deal with fractions. "0.375 Experience Points" just isn't as *catchy* as "375 Experience Point". Those numbers have a wider range and variation for balancing without the need of fractions.

The developer can still decide later in a patch to use 1015 points as damage instead of 1000 for the super gun. If the original value would have been a damage of 1, it would become 1.015 damage after the patch. That fractional number just doesn't look so nice rendered highlighted in your HUD

# Answer
> 6 votes
**Preamble:** As Patrick Hughes noted, for the "correct" answer to your question, take a sample of test playes. Give one group your game with standard scores, and a second group the same game but with 100x/1000x the scores.

**Fractions:** Depends on your Game, really. Commenter Joe provided an example of where rounding can occur, but that's about Hit Points rather than scores. It's relatively rare for a game to have adaptive scores, because scores are supposed to reflect the player's skill, whereas, for example, adaptive damage tries to deal more damage to more expierenced players than less expierienced ones. If you suspect fractions for another reason, then avoiding rounding does legitimate for raising everything by a factor of 10 or 100. I can't think of a reason why this could happen, though.

**Comparing scores**: Again, relatively subjective. Larger scores are easier to compare than smaller ones, though. Try this:

* Team Alpha got 38 Points
* Team Beta got 20 Points
* Team Charlie got 80 Points

versus

* Team Alpha got 3800 Points
* Team Beta got 2000 Points
* Team Charlie got 8000 Points

Which team was better, and how much better? Mathematically seen, both representations are absolutely equivalent.

**Satisfaction**: I'd say it depends on whether your game is fast-paced or slow-paced. If your game is fast-paced with a lot of action, then "busting the high score" gives me *much* more satisfication if I cracked the high score not by 80 points, but by 80000. If your game is slow-paced, with lots of tactical thinking, then scores usually aren't the most relevant satisfaction factor at the end of the game. I'd compare the time I needed to beat the round/level. How many mistakes did I make? How many units did I need?

**Conclusion**: It depends on your game, and know your target audience.

Also, I haven't seen a game which gives you sub-one scores. It's an interesting concept. Getting finaly a score of 1.0319049.

As you can see in the answers and comments, it varies from player to player.

# Answer
> 5 votes
I'd say higher numbers tend to make players happy. It's better to get *$1000* instead of *$10*, right? Big numbers also go better together with effects. Imagine a particle explosion and sound-effects every time you achieve something in the game. That would certainly look better with an accompanying *14'500*, than some low number like *34*. Big numbers give the impression of something, well, big, that warrants an audiovisual firework.

Why do big numbers feel like they are more of an achievement? In our daily life, we deal a lot with low numbers. Our daily purchases are usually not in the thousands of dollars, also we don't have thousands of friends or a hundred pair of shoes etc. Numbers from one to ten are probably most common and are very *normal* to us. It's also the amount we can show using just our fingers. So are numbers from 10 to 50. Higher numbers are more and more rare in our daily life and therefore become special or more valuable.

On the other hand, you shouldn't use numbers for your total score that are so high that your average person doesn't even know how to pronounce it. Anything above several million is too high and too hard to decipher. This is readable: *1'400'000*, this is not: *1'400'000'000'000*. This means that your score distribution should be in a way that your total score won't go higher than about 6-8 digits.

Beware though, that if you start throwing really high numbers at the user right from the start, it might feel as if there's no room for improvement. A good example are RPGs, where your hero starts really weak and deals low damage at around 1-10, but at a high level with "uber" gear, the damage goes into the thousands. That really gives an impression of progress and achievement.

That being said, it's also a matter game-type and player expectations. As Joe Wreschnig pointed out in his comment, pinball machines started to work with very high scores quite early and this has established as some sort of standard. Doing anything else might dampen the users enjoyment. Eg. "What, only 1'041 points? I got a highscore of 1'300'000 on that other machine".

When you're creating a simulation type-of game, your scores (eg. currency) should be somewhat realistic. Realistically You won't get $1000 per visitor in your theme-park (unless the value of the dollar keeps sinking, but that's another story).

A lot of answers have covered technical reasons for high scores. One that you should keep in mind is screen-size and readability. If your game runs on a mobile device, you simply don't have the space for really high numbers. Also on devices that run on a TV, you're limited by the lowest possible resolution, where readability can become an issue. I'd rather have a very well readable score of *450* than an unreadable *450'000'000*.

**TL;DR:** When designing your scores, think about it as a reward and never forget the context and player expectations. Will 10 points feel good in the context of a pinball game? Probably not. Also try to give the player some feel of progress by increasing scores, maybe giving higher scores more *oomph* by adding audiovisual effects. So that it really feels rewarding getting better scores.

# Answer
> 3 votes
Experiment.

Make two games, differing only in the graphics and scoring systems. Give these games to your friends, ask which they liked better.

# Answer
> 2 votes
Indeed higher scores are said to make the player feel like he's playing better, and hence *could* enhance user experience. This needs to be experimented for you to really find if this makes a difference in your specific game. If you compare an arcade game like Every Extend Extra Extreme and a platformer like Mario, the effect score has on the player is widely different.

As Maik said, higher scores are not only easier on the programming side of things, but are generally much easier for the user to *understand* at a glance.

Whether you give your player 100 points for a coin, or 2000 doesn't matter: if it is the first object a player picks up in a game, this will be his *"score reference"*. (In this case though I would said 100 points is inherently easier to understand than 2000, but that's more in the realm of psychology).

In my opinion, what's important then is not to necessarily have a high score reference, just an *understandable* one. What could really give the player satisfaction is when you give him 5000 points instead of the default 200 because he did something well.

A great game for user satisfaction in my opinion is Peggle by PopCap.

In Peggle, when you finish the level, you get a zoom and slow-mo on the last peggle, and huge explosions when you hit it. Very nice. Any bonuses you get multiply your score by huge amounts, again with colourful explosions everywhere.

What is interesting is the mix of visually pleasing feedback, and score multipliers; if I remember correctly, the base score for a peggle is also 100 points, 500 for the ones needed to complete the level. 1 & 5 are mathematically the same, but probably less easy to understand when things are hectic and your score is going up constantly.

So easy, understandable base scores, and huge bonuses and multipliers for doing things well. (Lovely explosions and classical music is also win ^^).

I know that some of the top companies are currently recruiting "Score Designers" to think out how players should be awarded; this shows that it's not something that's simple, and is probably worth investing time into to do right.

---
Tags: game-design, user-experience, scoring
---


title: Using spritesheets with z-buffer

text:
# Question
Title: Using spritesheets with z-buffer
I am working on a 2D game with sprite sheets. I might be completely overlooking something here, but I can't figure out for the life of me how to use sprite sheets with z-buffer testing.

Here are the conflicting issues as I understand them:

1. A sprite in a spritesheet will have transparent pixels all around it that define where the sprite doesn't exist (since each frame in the sprite sheet "grid" is a rectangle, but the sprite is contained within that rectangle).
2. Transparency doesn't work with z-testing.

Therefore, it's impossible to use spritesheets with the z-buffer? I should just use painter's algorithm then?

Are both of those conclusions correct?

# Answer
You can make things transparent while using depth testing. You just have to do it correctly.

One way is with alpha test. If your transparency is a simple binary on/off (not translucency, where something can be partially transparent), then alpha testing is all you need. You can set your renderer to simply ignore fragments that have an alpha value less than a given alpha. Or greater than, but generally, you're probably looking for less than.

However, if there is actual translucency, then you will have to draw things back-to-front. You can use depth testing on non-translucent objects, but you'll have to turn off depth writes on the translucent ones.
> 2 votes

---
Tags: spritesheet
---


# Question
Title: What do you use to support multiplayer turn-based network game for iOS and Android games?
If I'm doing a turn-based card game, what kind of technique do you use to support multiplayer gameplay over Internet?

Is it socket? If it's socket, which SDK (CoronaSDK etc.) can provide solid socket library?

Can Unity3D can be used solely to support what I need without using other socket servers like SmartFox or Electro?

# Answer
If your game is turn based, a combination of long-polling (read Push) and web services (SOAP or REST) should be more than sufficient for any turn-based game. They are simple to implement on a server and consume on a multitude of clients.

The advantage of using web services, are two fold. First, just about every platform worth its salt will have a mechanism to invoke web services natively without much ruckus. Second, is that adding additional platforms, or even letting web (desktop based browser) players play against anyone else, is easy since you're just passing messages back and forth over an HTTP connection.

In addition to that, since you're talking about Android and iOS -- where 3G connections are likely to occur, an HTTP web service wont completely die in a "flaky-connection" mode, where as pure TCP sockets would have issues staying connected.
> 5 votes

# Answer
I had the same dilemma when I ventured into Android gaming. SmartFox was beyond my budget but I was keen to use a third-party SDK which I could leverage across multiple games. Further, I don't really have the programming knowledge to design a socket library interface by myself. I came across Skiller - a free SDK for developing turn-based multi-player games which integrates with Eclipse and abstracts such details from developers.

I'd suggest you take a look at Skiller's TicTacToe. It would give you a good idea of whether their SDK would suit your needs. I hope this helps.
> 1 votes

---
Tags: android, networking, game-mechanics, ios
---


# Question
Title: Issue with implemented Minesweeper algorithm
So I'm attempting to learn Python by way of Minesweeper. I've got experience with SDL, so I figured playing around with PyGame sounded like a fun way to learn the syntax of the language.

Anywho, I'm having an issue in uncovering adjacent open squares as you would in a normal game of Minesweeper. I click on a cell with 0 neighboring mines, and attempt to scan the top, left, right, and bottom to see if those also have 0 neighboring mines, and I do this recursively.

Here is the error that I receive:

```
RuntimeError: maximum recursion depth exceeded in cmp

```

And here is my algorithm:

```
#open up blank mines
def open_blank_cells(mines, cr, cc):
  #top
  if (cr > 0):
    t_mine = mines[cr-1][cc]
    t_mine.switch_state(3)
    if (t_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr-1, cc)

  #right
  if (cc < 9):
    r_mine = mines[cr][cc+1]
    r_mine.switch_state(3)
    if (r_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr, cc+1)

  #bottom
  if (cr < 9):
    r_mine = mines[cr+1][cc]
    r_mine.switch_state(3)
    if (r_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr+1, cc)

  #left
  if (cc > 0):
    l_mine = mines[cr][cc-1]
    l_mine.switch_state(3)
    if (l_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr, cc-1)

  return

```

where `mines` is my 2D array of cells, `cr` is the index of the current row (first array index), and `cc` is the index of the current column (second array index).

I thought that my algorithm was decently solid (but please tell me if I'm wrong there!!!), so I turned to the Internet and found that the default Python recursion limit of 1000 could be to blame. However, when I bump it higher with the call to `sys.setrecursionlimit` the game either exhibits the same behavior, or simply crashes as the system kills it.

When I comment out 2 of the 4 recursive checks in the function, it will open up blank cells without any problem. 3 or more however breaks the algorithm.

---

**Edit**

As requested....

**Calculation of neighbor\_mines**

```
# if not a mine, figure out how many surround it
  for i in xrange(10):
    for j in xrange(10):
      if (mines[i][j].is_mine == False):
        #check top 3
        if (i > 0):
          if (j > 0):
            if (mines[i-1][j-1].is_mine == True):
              mines[i][j].neighbor_mines += 1

          if (mines[i-1][j].is_mine == True):
            mines[i][j].neighbor_mines += 1

          if (j < 9):
            if (mines[i-1][j+1].is_mine == True):
              mines[i][j].neighbor_mines += 1

        #check left and right
        if (j > 0):
          if (mines[i][j-1].is_mine == True):
            mines[i][j].neighbor_mines += 1

        if (j < 9):
          if (mines[i][j+1].is_mine == True):
            mines[i][j].neighbor_mines += 1

        #check bottom 3
        if (i < 9):
          if (j > 0):
            if (mines[i+1][j-1].is_mine == True):
              mines[i][j].neighbor_mines += 1

          if (mines[i+1][j].is_mine == True):
            mines[i][j].neighbor_mines += 1

          if (j < 9):
            if (mines[i+1][j+1].is_mine == True):
              mines[i][j].neighbor_mines += 1

```

**Switch\_state**

```
 def switch_state(self, newstate):
    self.state = newstate

    #marked as mine
    if (newstate == 1):
      nf = "sq_mine_marked.png"
    elif (newstate == 2):
      nf = "sq_mine_question.png"
    elif (newstate == 3):
      nf = "sq_mine_open.png"
    elif (newstate == 4):
      nf = "sq_mine_mine.png"
    else:
      nf = "sq_mine.png"

    oldrect = self.rect #save old rect as load_image overwrites it
    self.image, self.rect = load_image(nf, (255,0,255))
    self.rect = oldrect

```

# Answer
Imagine the following setup:

```
1 1 1 1 1 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 0 0 0 0 1
1 1 1 1 1 1

```

As a side note, I refer to squares in the matrix like this: (row, column). I've represented mines with "1" and empty spaces with "0". Assume the user clicks on the empty space at (2, 2) (the corner at the top-left is (0, 0)).

This is what would happen:

* the square at (2, 3) is empty and has no adjacent mines. Let's call our function for those coordinates
* in the new function call we notice that (3, 3) is empty and has no adjacent mines, let's call the function for that space as well
* (3, 2) is a valid place too, let's call again
* in the fourth call we'll notice that (2, 2) is empty and has no nearby mines, so we're back at square one, thus creating an endless loop

Any adjacent squares that each do not have adjacent mines will create an endless loop once your recursive function is called for either of them. Simply putting in a condition to not call the function again for the square you just came from wouldn't have been enough, as can be seen in the example above.

One solution is to create another matrix that can show what squares have already been visited. If the current square has already been visited, return from the function immediately. Otherwise, mark is as a visited square and carry on with your usual code.
> 10 votes

---
Tags: algorithm, python, pygame, recursion, minesweeper
---


# Question
Title: Translating Steering Behaviour Pursuit sample
I've come across a C++ Sample of from Programming Game AI by Example. For the most part it is fairly understandable, the only thing confusing me is the reference to "m\_pVehicle-\>Heading()" I'm not sure what it means by heading. If anyone could clarify this, I would really appreciate it.

```
 Vector2D SteeringBehaviors::Pursuit(const Vehicle* evader)
    {
      //if the evader is ahead and facing the agent then we can just seek
      //for the evader's current position.
      Vector2D ToEvader = evader->Pos() - m_pVehicle->Pos();

      double RelativeHeading = m_pVehicle->Heading().Dot(evader->Heading());

      if ((ToEvader.Dot(m_pVehicle->Heading()) > 0) &&
          (RelativeHeading < -0.95))  //acos(0.95)=18 degs
      {
        return Seek(evader->Pos());
      }

      //Not considered ahead so we predict where the evader will be.

      //the look-ahead time is proportional to the distance between the evader
      //and the pursuer; and is inversely proportional to the sum of the
      //agents' velocities
      double LookAheadTime = ToEvader.Length() /
                            (m_pVehicle->MaxSpeed() + evader->Speed());

      //now seek to the predicted future position of the evader
      return Seek(evader->Pos() + evader->Velocity() * LookAheadTime);
    }

```

# Answer
On p.87 of the book, you will find the definition of m\_vHeading as:

```
//a normalized vector pointing in the direction the entity is heading.
SVector2D m_vHeading;

```

If you look through the source, you will find:

```
Vector2D  Heading()const{return m_vHeading;}

```

Right before your code snippet he explains that if the target being pursued is ahead and almost directly facing the agent, it should just seek directly towards the target's position.

A way to easily determine if the target is ahead, or "in front", of the agent is by using the dot product of the vector from the agent's position to the target's position `ToEvader` and the agent's heading vector `m_pVehicle->Heading()`. If the dot product is greater than 0, the target is in front of the agent:

```
(ToEvader.Dot(m_pVehicle->Heading()) > 0)

```

You can read more on the dot product and it's uses on pages 23-26.
> 5 votes

---
Tags: c++, ai
---


# Question
Title: How can I give the player the impression of speed?
> **Possible Duplicate:**
> Effects to make a speeding spaceship look faster

I am currently developing a racing game akin to F-Zero in that the race is held at very fast speeds. The player is therefore placed in a 3rd person view.

Graphically, I'm thinking of using motion blur and lowering the camera angle when the ship is going faster to give the player the impression of speed. This from the fact that the closer you are to the ground, the more you percieve speed.

This question has intersting answers, but don't really apply because the effect needs to be progressive and constant, not like a boost effect.

I was wondering if these techniques are viable, and if any other techniques exist?

# Answer
Many of the answers at the linked question may help. Here are some other ideas off the top of my head.

Lots of what I remember about FZero was the ground and barrier textures that were very obviously striped/tiled in ways that they weren't very "long" in the "forward" direction. As you pass by these elements, they seemed to whiz by at very high speed. Very commonly, the ground textures would change to a different pattern, further enhancing that feel of speed.

Very responsive, almost jumpy/jittery, controls give a feel of speed as well. In FZero, very slight shifts left and right are actually rather noticeable.

Speed lines (wind-like particles) may or may not work for your environment. They're probably at least worth an iteration or two.

Banked turns. Play off the knowledge players may have that banked turns are related to high-speed driving.

I like the idea of the lower camera angle. Staying tight(-ish) on the vehicle will certainly make the environment local to the camera pass by more quickly. The closer the camera is to the vehicle will increase this effect but, of course, be wary of making the game unplayable through being unable to see enough.
> 2 votes

---
Tags: graphic-effects, user-experience
---