# Question
Title: How can I make a character walk on uneven walls in a 2D platformer?
I want to have a playable character who can "walk" on an organic surface at any angle, including sideways and upside-down. By "organic" levels with slanted and curved features instead of straight lines at 90-degree angles.

I'm currently working in AS3 (moderate amateur experience) and using Nape (pretty much a newbie) for basic gravity-based physics, to which this walking mechanic will be an obvious exception.

Is there a procedural way to do this kind of walk mechanic, perhaps using Nape constraints? Or would it be best to create explicit walking "paths" following the contours of the level surfaces and use them to constrain the walking movement?

# Answer
Here is my complete learning experience, resulting in a pretty much functional version of the movement I wanted, all using Nape's internal methods. All of this code is within my Spider class, pulling some properties from its parent, a Level class.

Most of the other classes and methods are part of the Nape package. Here's the pertinent part of my import list:

```
import flash.events.TimerEvent;
import flash.utils.Timer;

import nape.callbacks.CbEvent;
import nape.callbacks.CbType;
import nape.callbacks.InteractionCallback;
import nape.callbacks.InteractionListener;
import nape.callbacks.InteractionType;
import nape.callbacks.OptionType;
import nape.dynamics.Arbiter;
import nape.dynamics.ArbiterList;
import nape.geom.Geom;
import nape.geom.Vec2;

```

First, when the spider is added to the stage, I add listeners to the Nape world for collisions. As I get further into development I will need to differentiate collision groups; for the moment, these callbacks will technically be run when ANY body collides with any other body.

```
        var opType:OptionType = new OptionType([CbType.ANY_BODY]);
        mass = body.mass;
        // Listen for collision with level, before, during, and after.
        var landDetect:InteractionListener =  new InteractionListener(CbEvent.BEGIN, InteractionType.COLLISION, opType, opType, spiderLand)
        var moveDetect:InteractionListener =  new InteractionListener(CbEvent.ONGOING, InteractionType.COLLISION, opType, opType, spiderMove);
        var toDetect:InteractionListener =  new InteractionListener(CbEvent.END, InteractionType.COLLISION, opType, opType, takeOff);

        Level(this.parent).world.listeners.add(landDetect);
        Level(this.parent).world.listeners.add(moveDetect);
        Level(this.parent).world.listeners.add(toDetect);

        /*
            A reference to the spider's parent level's master timer, which also drives the nape world,
            runs a callback within the spider class every frame.
        */
        Level(this.parent).nTimer.addEventListener(TimerEvent.TIMER, tick);

```

The callbacks change the spider's "state" property, which is a set of booleans, and record any Nape collision arbiters for later use in my walking logic. They also set and clear toTimer, which allows the spider to lose contact with the level surface for up to 100ms before allowing world gravity to take hold again.

```
    protected function spiderLand(callBack:InteractionCallback):void {
        tArbiters = callBack.arbiters.copy();
        state.isGrounded = true;
        state.isMidair = false;
        body.gravMass = 0;
        toTimer.stop();
        toTimer.reset();
    }

    protected function spiderMove(callBack:InteractionCallback):void {
        tArbiters = callBack.arbiters.copy();
    }

    protected function takeOff(callBack:InteractionCallback):void {
        tArbiters.clear();
        toTimer.reset();
        toTimer.start();
    }

    protected function takeOffTimer(e:TimerEvent):void {
        state.isGrounded = false;
        state.isMidair = true;
        body.gravMass = mass;
        state.isMoving = false;
    }

```

Finally, I calculate what forces to apply to the spider based on its state and its relationship to the level geometry. I'll mostly let the comments speak for themselves.

```
    protected function tick(e:TimerEvent):void {
        if(state.isGrounded) {
            switch(tArbiters.length) {
                /*
                    If there are no arbiters (i.e. spider is in midair and toTimer hasn't expired),
                    aim the adhesion force at the nearest point on the level geometry.
                */
                case 0:
                    closestA = Vec2.get();
                    closestB = Vec2.get();
                    Geom.distanceBody(body, lvBody, closestA, closestB);
                    stickForce = closestA.sub(body.position, true);
                    break;
                // For one contact point, aim the adhesion force at that point.
                case 1:
                    stickForce = tArbiters.at(0).collisionArbiter.contacts.at(0).position.sub(body.position, true);
                    break;
                // For multiple contact points, add the vectors to find the average angle.
                default:
                    var taSum:Vec2 = tArbiters.at(0).collisionArbiter.contacts.at(0).position.sub(body.position, true);
                    tArbiters.copy().foreach(function(a:Arbiter):void {
                        if(taSum != a.collisionArbiter.contacts.at(0).position.sub(body.position, true))
                            taSum.addeq(a.collisionArbiter.contacts.at(0).position.sub(body.position, true));
                    });

                    stickForce=taSum.copy();
            }
            // Normalize stickForce's strength.
            stickForce.length = 1000;
            var curForce:Vec2 = new Vec2(stickForce.x, stickForce.y);

            // For graphical purposes, align the body (simulation-based rotation is disabled) with the adhesion force.
            body.rotation = stickForce.angle - Math.PI/2;

            body.applyImpulse(curForce);

            if(state.isMoving) {
                // Gives "movement force" a dummy value since (0,0) causes problems.
                mForce = new Vec2(10,10);
                mForce.length = 1000;

                // Dir is movement direction, a boolean. If true, the spider is moving left with respect to the surface; otherwise right.
                // Using the corrected "down" angle, move perpendicular to that angle
                if(dir) {
                    mForce.angle = correctAngle()+Math.PI/2;
                } else {
                    mForce.angle = correctAngle()-Math.PI/2;
                }
                // Flip the spider's graphic depending on direction.
                texture.scaleX = dir?-1:1;
                // Now apply the movement impulse and decrease speed if it goes over the max.
                body.applyImpulse(mForce);
                if(body.velocity.length > 1000) body.velocity.length = 1000;

            }
        }
    }

```

The real sticky part I found was that the angle of movement needed to be in the actual desired direction of movement in a multiple contact point scenario where the spider reaches a sharp angle or sits in a deep valley. Especially since, given my summed vectors for the adhesion force, that force will be pulling AWAY from the direction we want to move instead of perpendicular to it, so we need to counteract that. So I needed logic to pick one of the contact points to use as the basis for the angle of the movement vector.

A side effect of the adhesion force's "pull" is a slight hesitance when the spider reaches a sharp concave angle/curve, but that's actually kind of realistic from a look-and-feel standpoint so unless it causes problems down the road I'll leave it as is. If I need to, I can use a variation on this method to calculate the adhesion force.

```
    protected function correctAngle():Number {
        var angle:Number;
        if(tArbiters.length < 2) {
            // If there is only one (or zero) contact point(s), the "corrected" angle doesn't change from stickForce's angle.
            angle = stickForce.angle;
        } else {
            /*
                For more than one contact point, we want to run perpendicular to the "new" down, so we copy all the
                contact point angles into an array...
            */
            var angArr:Array = [];
            tArbiters.copy().foreach(function(a:Arbiter):void {
                var curAng:Number = a.collisionArbiter.contacts.at(0).position.sub(body.position, true).angle;
                if (curAng < 0) curAng += Math.PI*2;
                angArr.push(curAng);
            });
            /*
                ...then we iterate through all those contact points' angles with respect to the spider's COM to figure out
                which one is more clockwise or more counterclockwise, depending, with some restrictions...
                ...Whatever, the correct one.
            */
            angle = angArr[0];
            for(var i:int = 1; i<angArr.length; i++) {
                if(dir) {
                    if(Math.abs(angArr[i]-angle) < Math.PI)
                        angle = Math.max(angle, angArr[i]);
                    else
                        angle = Math.min(angle, angArr[i]);
                }
                else {
                    if(Math.abs(angArr[i]-angle) < Math.PI)
                        angle = Math.min(angle, angArr[i]);
                    else
                        angle = Math.max(angle, angArr[i]);
                }
            }
        }

        return angle;
    }

```

This logic is pretty much "perfect," inasmuch as so far it seems to be doing what I want it to do. There is a lingering cosmetic issue, however, in that if I try to align the spider's graphic to either the adhesion or movement forces I find that the spider ends up "leaning" in the direction of movement, which would be ok if he were a two-legged athletic sprinter but he's not, and the angles are highly susceptible to variations in the terrain, so the spider jitters when it goes over the slightest bump. I may pursue a variation on Byte56's solution, sampling the nearby landscape and averaging those angles, to make the spider's orientation smoother and more realistic.
> 9 votes

# Answer
How about making any "stick" surface a character touches apply a force along the inverse normal of the surface? The force remains as long as they're in contact with the surface and overrides gravity as long as it's active. So jumping off the ceiling will have the expected effect of dropping down to the floor.

You would probably want to implement some other features to make this work smoothly and be easier to implement. For example, instead of just what the character touches use a circle around the character and sum up the inverted normals. As this crappy paint image shows:

*(The spider likeness represented is property of Byte56)*

The blue lines are the inverse normals to the surface at that point. The green line is the summed force being applied to the spider. The red circle represents the range the spider is looking for normals to use.

This would allow for some bumpyness in the terrain without the spider "loosing its grip". Experiement on the circle size and shape for that matter, maybe just use a half circle oriented with the spider down, maybe just a rectangle that encompasses the legs.

This solution allows for you to keep the physics turned on, without needing to deal with specific paths the character can follow. It's also using information that's fairly easy to get and interpret (normals). Finally, it's dynamic. Even changing the shape of the world is easy to account for, since you can easily get normals for whatever geometry you're drawing.

Remember that when no faces are within range of the spider, normal gravity takes over.
> 8 votes

---
Tags: actionscript-3, physics, movement, platformer
---


# Question
Title: Benefits of upgrading from OpenGL ES 1.1 to 2.0 on iOS
I have an animated 3D iPhone game that I first wrote using OpenGL ES 1.1 in late 2009.

After many updates to the rest of the game, the OpenGL ES 1.1 code still runs fine under iOS 6, but I'm wondering about benefits to 2.0 that I'm missing out on, and whether it is worth converting to. I don't care about backwards compatibility with devices unable to support 1.1.

I've read this post and this post on the sister site, but some information there is no longer applicable, and I would like a perspective specifically from a gaming programmer's point of view about whether it's worth updating, rather than which I should use if I were doing it from scratch.

Thanks for your help.

---

\[Edited to answer comments below\]

This is the project. I don't need shaders, textures, or anything ES 1.1 doesn't do in some fasion (at least for a while), but would be tempted to upgrade if for example 2.0 just does it much better, or is much faster, or does something that's just so useful and/or awesome that it would be criminal not to take advantage of it, or 1.1 has some awful bug on a device that I haven't had a chance to test on.

# Answer
If it's worth it or not depends entirely on your needs, the goal of the project and the resources available for the project vs what resources it will take to upgrade.

However, simply based on what you've described, I would see no reason to upgrade. You've said the game you wrote still runs fine, so it sounds like there's nothing to fix. If there's no problems that will be overcome by switching to 2.0, it's not worth it. You'd just be generating work for yourself at that point.

If you were to start a new project, you might as well use 2.0, if that project also doesn't have the requirement of supporting older devices.
> 4 votes

# Answer
While ES 1.x is supported by new devices, the support is actually implemented on top of the shader hardware. This means that writing directly to ES 2.0 (or 3.0) should give you a bit of a performance edge over 1.x, as well as the obvious flexibility shaders give you.

If the ES 1.x implementation has bugs, they may be harder to figure out since everything goes through a couple of layers. This is less of a reason to go with ES 2+, but a thing to consider nevertheless.

Third upside is getting on with the times; what you learn now by moving to ES 2+ will help you in the future.

Downsides include potentially more complex code, having to figure out how to implement the same things with shaders, potential shader compatibility issues between devices (all the devices have their own compilers, after all), and potentially no obvious visible change for your customers.
> 2 votes

# Answer
The pragmatic perspective:

The benefit of upgrading from OpenGL ES 1.1 to OpenGL ES 2.0 is that you get to use OpenGL ES 2.0 features which aren't available in OpenGL ES 1.1 (most notably, shaders and framebuffer objects).

If you don't plan to use those features (as you say in your question), then there are no benefits to modifying your program to render using OpenGL ES 2.0 rather than 1.1. In fact, it limits the number of devices which will be able to run your program -- devices older than the iPhone 3GS can't run OpenGL ES 2.0 code at all. Thus shrinking your market for no gain at all.

Additionally, (and this is probably obvious, but is still worth pointing out explicitly) if you spend your time upgrading your existing program to run using OpenGL ES 2.0 (so that it can fail to work for some users and provide no benefit to the rest), then that time is time you won't be spending to write your next game. Which probably would be an activity of more benefit both to yourself, and to everyone who enjoys your games.
> 2 votes

# Answer
The most important reason is of course the main difference: fixed vs programmable rendering pipeline. Shaders are more flexible, allow creation of more sophisticated faster and with more performance, and you can expect more and more support in upcoming iOS devices.

Besides, 2.0 is *already* outdated, with 3.0 spec probably being implemented by various manufacturers right now. And since 3.0 will be compatible with Desktop OpenGL, it will further simplify creation of cross-platform programs. Transition from 2.0 to 3.0 will be certainly easier than from 1.1.
> 1 votes

---
Tags: 3d, iphone, ios, opengl-es, opengl-es2
---


title: Drawing many quads XNA

text:
# Question
Title: Drawing many quads XNA
I asked a similar question to this yesterday and gained some knowhow but I'm a little confused:

If I have many quads that contain vertices and indices that are positioned to to form a bigger picture, then that bigger picture is positioned using world matrices...

How do I draw them all? From what I've gathered I've got to do in it in one pass for good speed.

I used to draw every quad with its own pass. Now every quad in an object is drawn in one pass.

But if I have a lot of objects it will slow down.

So my question is: how does one go about drawing lots of separate vertices and indices without losing frame rate? I don't need someone to hold my hand just maybe point in the right direction.

# Answer
Take a look at this tutorial: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series1/Terrain\_basics.php . It is about terrains but you should be able to figure out how to combine "quads" (xna doesn't have quads, it is just 2 triangles) in one draw call.
> 1 votes

---
Tags: xna, optimization
---


title: 3D models and hit detection

text:
# Question
Title: 3D models and hit detection
I'm currently trying to create a game that involves the inside of a cube, which i will make in Maya. My question is what is the best way to create a model with hit detection in mind?

For example my model will be a cube that you can walk inside of, so should i make the cube as a one model or make one wall and put it together inside XNA?

The reason I ask this is because I'm sure that if I create a whole cube and then use XNA's bounding rectangle method, hit detection will always be true because the bounding rectangle will encompass the whole cube, making collision detection inside the cube non existent without the use of hard values.

Whereas separate walls would make the process easier because i will checking against separate walls instead of the whole thing.

To add to the problem, I also have doors in the walls so hit detection for the walls in that area need to be turned off.

What is the best way to do this?

# Answer
> 3 votes
You make the model however it needs to be made to appear correctly and/or animate correctly.

The collision shape does not need to be the same as the model and the collision shape can be a combination of multiple different shapes. If the inside of the cube is to be collided with, you can create collision shapes that just occupy the solid parts of the model, in this case, you would create rectangles that represent each of the walls.

---
Tags: collision-detection, xna-4.0, maya
---


title: Artificial intelligence in board games?

text:
# Question
Title: Artificial intelligence in board games?
How to create AI in games like suduko/snake and ladder/tic-tac-toe in general board games where computer is a another opponent.

# Answer
The question is a bit vague, so I'll give a primer on the subject.

To make an AI opponent, you'll need to create a sub-routine that considers the current state of the board and chooses a move, just like the player would. For example, in Tic-Tac-Toe, the subroutine would look at the state of the nine positions of the board, and choose where to place its own mark.

Now, how does this subroutine choose what move to make? In a simple game like Tic-Tac-Toe, each optimal move is obvious from the rules of the game (try to make three in a row and don't leave open lines to the player). For more complex games like chess, that depend on strategies beyond one move, you start looking into AI.

AI is basically "guessing for computers" - algorithms that calculate not the best move, but a move that -could be- good. AI algorithms involve, among others:

* Searching through all possible moves (for this turn, two turns, etc) and calculating which one is "better" (through mathematical formulas called 'heuristics')
* Predicting what the player character will do and trying to minimize damage;
* Memorising track of what strategies worked in the past and reusing them.

From here it's a matter of studying AI algorithms, discovering which ones work best for your specific game, and implementing the math in code.

A more indepth look at all the steps of AI programming for games can be found at Programming Game AI by Example, by Mat Buckland (http://www.amazon.com/Programming-Game-Example-Mat-Buckland/dp/1556220782)
> 5 votes

# Answer
This is a really general question, so you're probably only going to get overly-general answers until you post a new, more specific question.

It's also going to differ pretty significantly depending on the style of game. For example, the algorithms used to implement Sudoku solvers differ from those used to solve tic-tac-toe, chess, or Go (game trees / alpha-beta pruning). And I'm not sure what kind of AI is necessary for Snake -- generally it tends to be mostly random.

Alpha-beta pruning is probably the most common search technique for most of the class of board games you're thinking of (at least as far as *I* know, but I'm admittedly not terribly familiar with AI). There's also Negascout and whatever this is (these last two links aren't that great, if you spend more time sifting through the Google search results you can probably find better since you presumably have a more detailed idea of what you're really looking for).
> 4 votes

# Answer
I would suggest trying to write down how you yourself would think step-by-step when considering what move to make in a game. Once you define small-enough steps, all you need to do is put them into algorithm.

Most likely it will not be a small program. I would suggest to start from preparing a very general idea and a very basic principle how moves will be determined. Most likely it will appear not good enough at first and you will need to add more and more code to compensate bad decisions. At some point you will reach what you want. At least this is how I did it in my TicTacToe website. Try yourself - http://www.xo-play.com.
> 3 votes

# Answer
What you could do is do like the old computers did when solving board game: Have the computer play through the game many times (\> a couple thousand, not so hard to do if you remove player input). Each time it gets to a decision, choose randomly, but have it mark that it made that decision. Then have it analyze based on the other games where that same exact decision was made, and compare the results of those to the ones where the opposite choice was made.
> 0 votes

---
Tags: ai
---


title: Importing a transparent image to flash

text:
# Question
Title: Importing a transparent image to flash
How do I import an image that has transparent background to flash and give it class and use `addChild` to show it on the screen? Transparent background should stay transparent.

# Answer
> 1 votes
This is answered on the main StackOverflow: https://stackoverflow.com/questions/8005068/better-way-to-include-images-in-as3-than-embed

In summation, you can either include your images in the swf and then call them from the code, or you can load external images. If you have the Flash authoring tool then one approach would be to import the image in the authoring tool, and then in the Library go into the Properties and set the ActionScript linkage for that image. If you don't have the Flash authoring tool then the equivalent approach is to use \[Embed\] tags at the top of your code.

If you can't or don't want to include the images in the swf (eg. loading user images) then use Loader

---
Tags: actionscript-3, transparency
---


# Question
Title: Location-based mobile game without data plan
I'm in the planning phases of a mobile-based game that depends heavily on tracking your location (think FourSquare). The main problem I have is storing and tracing location.

If a user has a phone with a data plan, I can simply ask them to turn it on at the target location to allow me to save that information (that they visited location X). **But what about if they don't have a data plan?**

FourSquare allows you to use some sort of SMS system to "check in" to locations, but implementing that is beyond me. What I probably need is some way to just figure out and temporarily store the user's location, and when they next connect online, they can upload all the "visited locations" information.

I know this is vague; I'm looking for general solutions. If you want specifics, I will be using MonoGame and supporting iPhone and Android phones.

# Answer
> 1 votes
I don't believe there's a feasible way to implement location features in a mobile game without a data plan. Foursquare's SMS system only allows you to nominally check in. They don't award points unless they can verify you were there by a phone with a data plan with their app installed.

SMS systems are not hard to implement: use Twilio. Using their API, you can respond to and SMS via a HTTP requests. When you sign up, you get a reasonable amount of free credit to get started on development. Services like this are how a lot of companies are implementing their SMS features. It's super simple.

If it doesn't matter that much to you that a user could tell you they've been all sorts of places (you could probably do some server-side checking, eg. probably impossible to visit the Grand Canyon and the Taj Mahal in the same day), then the SMS bit is easy. Somehow triangulating on their position via SMS or phone calls sounds impossible unless you are best buddies with executives at a telecom or something.

---
Tags: android, game-design, iphone
---


title: How to make an infinite map

text:
# Question
Title: How to make an infinite map
I was wondering if someone could explain to me how to implement a seemingly dynamic infinite map like the one at http://wordsquared.com/

My main issue is really generating new tiles in any direction when the user drag the board.

I'm also trying to figure out how to handle the coordinate system, and actually what/how to store the map in a database.

# Answer
**Regarding the coordinate system:**

In order to address individual tiles, you will need some kind of origin (a 0:0 point). In order to allow the playing field to expand in every direction, you will also need negative values. This will give you a world which stretches from -2.147.483.647 to 2.147.483.647 in both directions, which is "large enough" to seem infinite for most sane players (depending on the game concept, of course).

To allow an even larger world you could use floating point numbers. But the disadvantage of floats is that you can not rely on their accuracy. This might introduce some strange and obscure bugs when you reach extreme distances from the origin, like in minecraft.

**Regarding storage:**

Saving the state of 2^64 tiles is more than any database can bear, so you should only save those tiles which are worth saving (those which are already discovered and changed by a player). To avoid infinite growth of your database you might consider to discard the state of tiles which were not visited for a considerable amount of time, but that's a gameplay decision.

But how do you save them?

Saving the whole world in one huge data structure would mean that the whole world needs to be kept in memory all the time. When the world is extremely large, this could result in unacceptable memory usage. But storing each tile individually in a database would mean that you need a lot of database queries all the time, which can become pretty inefficient.

A good compromise is to work with squares of uniform size of 16x16, 256x256 or whatever is appropriate for the specific use-case and store and retrieve each of them as one entity in the database. Such sections of the map are usually referred to as "chunks".

**Regarding the procedural generation:**

An interesting aspect of pseudorandom number generators is that they always return the same sequences when they get the same seed value. When you use the coordinates of a chunk as the seed value to generate it, it will always look the same. That means you don't even have to save the static information about a chunk anywhere, because you can just re-generate it on demand. Only the dynamic information (in this example, the letter tiles) needs to be stored in the chunks. When a player just visited a chunk without leaving any traces behind, you don't even have to save it at all.

The default random number generator of Javascript (Math.random) unfortunately doesn't allow you to set a seed, so you will have to implement your own RNG. But that's easier than it seems, because you can just use one of the many stock algorithms. See this question for some options.
> 11 votes

# Answer
The approach described by Phillipp is essentially what you'd do.

I would build the world in "blocks". Suppose you have one block, say 50x50 tiles, then you can pseudorandomly generate it (using the offsets from the origin as a seed). You can then keep these tiles in memory until the player walks too far away, then discard the block and regenerate it again.

Because a player expects adjacent areas to be "similar" - for example, a swampy area would not have a desert *right next to it*, you can use some kind of smoothed noise function (again pseudorandomly seeded, so it's always the same) to determine the terrain type for a given block.

To generate pseudorandom numbers in my web game, I used the "seedrandom.js" library by David Bau (Google it).
> 3 votes

---
Tags: javascript, html5, maps
---


# Question
Title: How to handle slopes/bridges in a 2d grid turn based strategy game
I was wondering about the following:

In a 2D turn-based strategy game (using some grid(i.e. tiles, isometric hexagons) as movement), what techniques do they use to determine where a character moves next, especially how this works when stuff is happening that as far as I can see cannot be so easily implemented using a two-dimensional grid, such as slopes/different heights of movement and also things like bridges that characters might both walk over or under, depending on how they approach it.

# Answer
> 2 votes
This issue can be solved by having multiple independent map layers and special tiles which serve as portals between these independent layers. In addition to their x and y coordinate, every object then also has a z-coordinate which carries the information which layer it is currently on - so the z-coordinate tells you if an object is under or on a bridge.

Most routefinding algorithms don't assume a single 2-dimensional grid, but can in fact work on any graph, no matter how many dimensions it has. So they can easily be adopted to deal with nodes which have an additional link which leads to a tile on another 2-dimensional grid.

---
Tags: tiles, movement, isometric, turn-based
---


# Question
Title: How do I implement unit selection in this program?
I'm trying to implement unit selection on a large, scrollable surface.

```
# Arbitrary values for window size
self.w, self.h = 1600, 900

# Game world surface, everything gets blitted to this, which is then drawn to the screen:
self.mapSurf = pygame.Surface((3600, 3600))

```

The general process looks like this:

```
# draw the floor first
    for e in self.map_layout.fixed_list:
        if e.type == 1:
            self.mapSurf.blit(self.map_sprite_list['floor_red'], e.rect)
# then draw the walls
    for e in self.map_layout.fixed_list:
        if e.type == 2:
            self.mapSurf.blit(self.map_sprite_list['wall'], e.rect)
# add agents (units) to the mapSurf
    for a in self.agent_list:
        self.mapSurf.blit(self.map_sprite_list['proto_unit'], a.pos)
# draw everything to screen
    self.screen.blit(self.mapSurf, self.mapSurfRect)

```

I have a method for getting the coordinates of a click on the screen. And tried to use this to select units.

```
def mouseUp(self, button, pos):

# select agent
    if button==1:
        for a in self.agent_list:
            if a.pos.get_distance(vec2d(pos)) < 24:
                self.selected.append(a)

```

The problem is that the value pos does not correspond to the mapSurf, but rather to the self.screen surface, so when comparing a.pos to the pygame event.pos returned from mouseUp, this function can only return coordinates within the window size, and I can't select agents which are spawned outside of the top left area of mapSurf.

What would be the general method of selecting units I need to implement to fix this program?

For some more details, here are three relevant links, all of which describe different aspects of how my program was built:

Trying to make a python map editor

Collision detection performance problem

Pygame performance issue for many images

# Answer
> 3 votes
If I'm understanding your question correctly, you want to select agents within the map, but outside of the current view/camera.

The approach is to convert your mouse/screen coordinates into world coordinates, by using your view position to offset the mouse.

Short example:

```
def ViewToWorld(view, mouseX, mouseY):
    finalPos.x = view.LeftX + mouseX
    finalPos.y = view.TopY  + mouseY

    return finalPos

```

You will need to update the view reference coordinates every time the view is moved around. I use top-left corner in the example above as the reference.

One of your links above contains a question about optimizing drawing sprites. At one point or another, most games have a *Game View* structure that contains functionality to convert coordinates to and from Screen/World, and it is also used to skip drawing things that are outside of the view, as a first step in optimization.

# Answer
> 0 votes
Using the advice from Jovan, I was able to solve my problem with this code:

```
vec2d(pos) + (vec2d(self.mapSurfRect.topleft) - ((self.mod_w * 2), (self.mod_h * 2)))

```

Where mod\_w and mod\_h are variables which get increased or decreased according to camera movement.

---
Tags: python, pygame
---


title: Flixel Development in Ubuntu/Linux

text:
# Question
Title: Flixel Development in Ubuntu/Linux
I've been trying to setup a development environment for Flixel on Ubuntu using this guide http://forums.flixel.org/index.php?topic=4545.0 but thus far have been unsuccessful mainly due to the guide being dated and using an outdated and inactive plugin for Eclipse (axdt).

I was wondering if anyone currently develops Flixel based games using Ubuntu/Linux, and if so how you got yourself setup. Ideally I would want to use an IDE like Eclipse but I would be open to other options.

# Answer
You can successfully compile a Flixel project on Ubuntu by downloading the Flex SDK, adding it to your PATH, and running `mxmlc YourMainGameFile.as -static-link-runtime-shared-libraries=true`

OR

Install Eclipse 3.7 Indigo, FDT 5 (http://marketplace.eclipse.org/content/fdt-1#.UPolm32Ux0w), and the Flex SDK mentioned above. Make a new Flash Web project and setup a run config.
> 1 votes

---
Tags: linux, eclipse, flixel
---


title: No intellisense on my classes

text:
# Question
Title: No intellisense on my classes
I've been using Monodevelop's current version and Unity 4. I don't get intellisense on the classes I've created but I do have intellisense on classes that are in Unity's framework. Bug or its just as it is?

I use UnityScript:

```
class SomeClass extends ScriptableObject{
    public function Test(){return "";}
}

```

In another class, when I use a variable typed as this class I get no intellisense.

# Answer
> 1 votes
There just isnt any intellisence on custom classes when using UnityScript unless they are in the same file. Which is very unconvinant.

I Switch to C# with Monodevelop.

Thanks anyways.

---
Tags: unity, unityscript
---


# Question
Title: AS3 UML Tools other than Crocus Modeller
I have been using Crocus Modeller a lot this past year, and it's been great. It's the first UML tool I've used, and so I don't know how it compares, but it seems to work very well. However, today I just got a MacBook Pro (first Mac) and while Crocus Modeller is an air application, it does not work properly (it doesn't even work properly in a Windows 8 vm using Parallels - which seems quite strange). I'm searching for a new tool. I haven't found any other AS3 UML tools, but I thought I'd ask to see if there is anything else people are using.

In case anyone is wondering, the problem with Crocus Modeller on the MacBook is that certain keys on the keyboard do not seem to register. Specifically, the S, D, F, G, H, L, C, and V letters do not register (they do register when holding down the shift key - but that is no workaround). This happens when running the air application natively in OSX as well as in the Windows 8 virtual machine using Parallels.

**Summary of primary question:** what are some good UML tools that can export AS3 code stubs?

**Bonus question:** I'm assuming there's no fix for the keyboard issue in Crocus Modeller, but if there is that would be an ideal solution to this problem.

# Answer
> -2 votes
You can try UML4AS: http://www.uml4as.com

UML4AS is an Eclipse Plugin. It allows you to work with diagrams, to generate code, reverse engineer and the whole round-trip scenario.

UML4AS works on both Windows and Mac. You can give it a try. Take a look at its "bigger brother", Flower Dev Center ( http://learn-discuss.flower-platform.com/flower\_dev\_center/ ), that allows you to model ActionScript projects, using the web browser.

Best regards, Cristian

---
Tags: actionscript-3
---


title: Professional game design documents

text:
# Question
Title: Professional game design documents
> **Possible Duplicate:**
> How should I structure a design document?

I'm planning to apply for a game designer position at a big company. But the problem is, according to my CV, I'm not fit for being a game designer. (I'm a programmer).

But, I don't like this and still would like to try my chances. Even though I'm a programmer, I have lots of ideas which I can put on paper in any detail depth imaginable. (It's not like "bro, I have this cool game idea in which you fly a spaceship and you see these scary monsters just like in ....", I can really make it professional).

To be able to achieve this, I want to send a game design with my application, written in proper way, that will make it easy for them to accept me.

Question is, what is the proper format for game design documents? Is there a template? What is the detail level? Where can I find a final game design document for a released professional game?

# Answer
> 3 votes
**Reality**

This is not the way to approach getting a job as a game designer. It won't happen, not this way. At least not with any company worth working for. First of all, if you have to ask what a professional game design document looks like, even though you say you can make it "look professional", you are not getting the job. Game designers have worked on several projects, they have a proven track record, and they certainly know the formatting of a game design doc. I know this all sounds harsh, but it's the reality.

**Be a game designer**

You can be a game designer without working professionally as one. There’s nothing stopping you from designing games. And if you want to do this professionally, that’s exactly what you have to do. You should have many finished game designs, not just on paper, you should make your own working prototypes. As you likely won’t have anyone to make your games for you, you need to do them yourself. We’re not necessarily talking finished products you can release on Steam, but it would help a lot. If you can prove you’re able to come up with interesting gameplay mechanics all wrapped up in a nice package that actually sells, well, then you’ve got a lot better chance than the guy who just sends in a game design doc… that document will likely not even be read.

**The game designer position**

I don’t think the game design position is what you think it is. There are very few game designers in the world doing just game design. Most have a lot of other responsibilities. If you do work solely as a game designer, well, then your job on that project can be over before you know it. It’s very likely you won’t get to be involved in a project from start to finish, you might be there just from the start and do a game design doc, and then you’re done. From there someone else is in charge, like the producer. Game design is more about game rules and mechanics than it’s about “this MMO where we have the whole planet in our game, and you can just like, live in apartments, buy things, and yeah, there should be discos where you can be like all virtual reality on the dance floor, when you’re actually at home in your apartment, but in the game! So it’s a game, but VR, inside of a game. And, oh yeah, there should be…”

**Getting the job**

Basically I’m saying you can’t get a job as a game designer without having designed a few games. It’s as basic as that. There are a few ways to get there. A) like I’ve said earlier, you can start making your own successful games. B) You can work on countless games in other roles, testing, programming, concept artist, whatever it takes, and eventually get to the producer role. From there you can eventually get to a game design position.

**The game design doc**

To actually answer concretely at least one of your questions:

http://www.gamasutra.com/view/feature/3384/the\_anatomy\_of\_a\_design\_document\_.php

# Answer
> 1 votes
Check out first couple of answers in this topic:

You can also check following ones:

# Answer
> 0 votes
There are no guidelines or rules for that. But keep in mind that it should be practical, write it down in a way you could use it as reference when developing it. You should have developed a few games haven't you? (If not you will probably have a hard time getting a job as game designer.)

# Answer
> 0 votes
My advice is this: don't apply for this job. Build something and write multiple designs, then apply for a job. Emphasis on "build something" here.

Don't expect that you can whip up a design document before hand and pass it off and get someone's attention. They don't have to be long, but they can be. Are you ready to make a well done document 15-20 pages long with concept art? Again, a design doc doesn't always have to be that, but it can be.

Do though go create a game, or at least the prototype-concept of a game. An excellent way to start is to make a mod for a game -- Half-Life 2 for example. You're a programmer, so that means you can actually implement your ideas.

---
Tags: game-design, design-document
---


title: At this point in time, avoid XNA?

text:
# Question
Title: At this point in time, avoid XNA?
XNA seemed like a valid option a few years ago, but XNA was never a real success, and now it seems like a footnote, even Microsoft seems to treat it that way.

Should I just go the DirectX route instead?

Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac + all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8.

EDIT: This question and releated might already be answered here: What is the future of XNA in Windows 8 or how will managed games be developed in Windows 8?

# Answer
I'm going to focus on this:

> Ideally, eventually, I'd like my games to be playable on all major platforms (Windows, Linux, Mac + all consoles), but my primary focus is getting the games out the door on Windows XP, 7 and 8.

Generally OpenGL and DirectX are the two most supported graphics libraries. Of course XNA is built over DirectX, however it was not adopted to the expected extent. Now if you are being smart in your development, you should be able to isolate your graphics handling in such a way that by changing only a select few of your files, you can completely migrate from one graphics library to another.

I can't remember which Sims game it was, (Medieval i think), but the game was developed with DirectX for PC and Xbox, but then they replaced it with OpenGL for the Mac, Linux builds.

I recommend sticking to the more commonly accepted libraries, as to have the largest amount of support. XNA is greatly accepted here at gamedev, however OpenGL and DirectX are both supported as well, both here and at overflow.

I was making the same decision around a year or two ago and concluded I would head into OpenGL (OpenTK for C#) grounds rather than staying with XNA for the following reasons:

* OpenGL can be used on all platforms
* XNA (in my opinion) was messy, which is one of the reasons i think it hasn't been adopted to a large extent.
* A knowledge of OpenGL or DirectX is as good as you get. If you learn them, picking up XNA would be a piece of cake. The same cannot be said the other way round.

My final advice though, is to try it all out for yourself. Check out Reimers tutorials in XNA and DirectX (and just browse google for some OpenGL tuts), and work out which one you think would be better for your interests.
> 0 votes

# Answer
> but XNA was never a real success

XNA *is* an amazing success. If you just look at this site as a measuring ground, you will notice that:

* XNA is the top recent tag (it stays up there quite a lot)
* XNA questions get quickly answered, often with multiple answers
* Difficult XNA problems are addressed

This shows that there are a lot of people interested in, and actively using, XNA. I tried many, many different tools and platforms before eventually coming back to XNA.

> I'd like my games to be playable on all major platforms

Me too. Since I love XNA so much, I ditched the Microsoft version, and went with *an open-source implementation of XNA*, aka MonoGame. Try it, and see for yourself.

And by the way, it supports Android and iOS via MonoTouch and MonoDroid. It also supports Windows (and Windows 8) out of the box.
> 15 votes

# Answer
Unity seems to be a good option to you, even if you are a beginner, since it welcomes new users easier than most engines and frameworks, like XNA. It has a growing community and fast support. Also have options to export for almost all major platforms (including consoles).
> 0 votes

# Answer
XNA would work wonders for you then, and I imagine XNA will build up again when they release the new Xbox.
> -1 votes

---
Tags: xna, directx, windows, console
---


# Question
Title: Drawing with SpriteBatch and GraphicsDevice.DrawPrimitives
I've faced with a problem when i tried to draw 2d game with `SpriteBatch` and `GraphicsDevice.DrawUserPrimitives`. I suppose that what is drawing with `SpriteBatch` has higher priority, because i can not see a result of its rendering. `GraphiscDevice.DrawUserPrimitives` renders only if i comment a line of rendering background. Here is my method Draw. Could you check the order of rendering. What is the reason?

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.BlanchedAlmond);

    basicEffect.CurrentTechnique.Passes[0].Apply();

    spriteBatch.Begin();
    spriteBatch.Draw(background, new Rectangle { X = 0, Y = 0, Height = Bounds.Height, Width = Bounds.Width }, Color.White);

    DrawCell();
    spriteBatch.DrawString(defaultFont, "fps: " + FPS, new Vector2(10, 75), Color.DarkBlue);

    spriteBatch.End();

    base.Draw(gameTime);
}

private void DrawCell()
{
    basicEffect.Texture = cellBody;
    graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleList, cell.Triangles, 0, cell.Triangles.Length / 3);
}

protected override void Initialize()
{
    basicEffect = new BasicEffect(graphics.GraphicsDevice);
    basicEffect.TextureEnabled = true;
    basicEffect.Texture = bg_menu;
    basicEffect.World = Matrix.Identity;
    basicEffect.Projection = Matrix.CreateOrthographicOffCenter
  (0, graphics.GraphicsDevice.Viewport.Width,
  graphics.GraphicsDevice.Viewport.Height, 0,
  0, 1);
...
}

```

# Answer
The spritebatch items don't actually draw onto the back buffer until spritebatch.End() is called. This is so it knows which sprites to 'batch' into 1 call to the GPU.

So your code basically:

1. informs the spritbatch that `background` will be one item in the batch
2. draws `Drawcell` directly to the back buffer (because you call it explicitly)
3. informs the spritebatch that `"fps: "` will be another item in the batch
4. `End()` is call so it batches and draws `background` and `"fps: "` to the back buffer overwriting the `DrawCell` stuff

It is generally recommended to `End()` the spritebatch before explicitly calling directly from the graphics device.
> 2 votes

# Answer
I have found this issue in my game recently, however I found the way to get over it is to call end before your draw primatives and begin after it:

```
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.BlanchedAlmond);

basicEffect.CurrentTechnique.Passes[0].Apply();

spriteBatch.Begin();
spriteBatch.Draw(background, new Rectangle { X = 0, Y = 0, Height = Bounds.Height, Width = Bounds.Width }, Color.White);

spriteBatch.End(); //end the spritebatch here
DrawCell();
spriteBatch.Begin(); // start it again here
spriteBatch.DrawString(defaultFont, "fps: " + FPS, new Vector2(10, 75), Color.DarkBlue);

spriteBatch.End();

base.Draw(gameTime);
}

```
> 1 votes

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


# Question
Title: How to encourage players to level up multiple characters?
In my game, it is possible to make multiple characters. You can make as many as you desire. What I usually do (and almost all players do) is just make a single character and level it up a LOT, and just use it for everything.

Some games have tried to solve this by having multiple "classes" or types of characters that do different things, but this typically results in just having one of each "class."

How could I encourage players to not make one or two really high leveled characters but instead have, maybe, several high-level characters, several mid-level, and some low-level characters that are currently being leveled up?

(**NOTE**: I am unaccepting the previously accepted answer because I seem to have a lot of new answers coming in. (sorry Thomas Marnell, your answer is still great :) ))

# Answer
A few ideas I've seen in action:

* Tweak the growth numbers. This is something games featuring a leveling system should almost always do. Characters usually gain strength easily and quickly in the beginning, but require more effort to be put in later on. By magnifying this distinction, players will be more inclined to spend their resources on low-level characters. Related: tweaking the growth of enemy strength may force low-level characters to either keep up or fall behind.
* Apply teamplay bonuses or lone wolf penalties. Some games impose artificial (dis)advantages based on the number of characters around. Strategy games like the *Total War* series often use this in the form of a morale check, though such mechanics may seem arbitrary out of context.
* Create a risk versus reward scheme. If players tend to stick to one character because that is somehow beneficient, have them risk that character being unavailable to encourage them not to put all their eggs in one basket. Games that are heavily story-driven (several JRPGs come to mind) often play this card.
* Split the characters up. Quite often, multiple characters simply fight alongside each other. The absence of one can be offset by making the other stronger. That need not be the case. For example, in *Heroes of Might and Magic*, multiple heroes do not just add to the combat strength, but also allow more map control and more tasks to be completed per turn.
* Multiplayer. No one likes to be the useless side-kick. Players will back away from optimal strategies that aren't fun. This naturally applies to single player as well, but is not as trivial to implement.
> 18 votes

# Answer
A few ideas:

* Allow players to call on their other characters as NPCs to support their current character (call in a healer or DPS character for a short time).
* Make a shared bank for sharing items/resources.
* Allow players to "train together" with their other characters to increase their XP while offline. (diverse groups train better, equal level characters train better)
* Make some quests only available if they have a team. (Similar to the first option, the second character can be at the controls opening doors or whatever)
> 15 votes

# Answer
Games like Pokemon have this problem a lot. I think they used two different methods.

1. Attrition. Make attacks and healing limited, encouraging multiple characters
2. Rock-Paper-Scissors. Make some characters better in certain situations

Techniques that promote multiple play-throughs like achievements can also help.

Edit:

After some thought, games like Final Fantasy have this problem a lot as well. I have seen them use story line to force multiple character progression.
> 7 votes

# Answer
Here are some more suggestions:

1. Make it impossible to advance to certain areas without having them previously unlocked with a special character class.
2. Make it possible to merge two characters into a single one in order to gain benefits.
3. Introduce crafting and collecting professions, WoW style, which has already been proven to work. You need at least a few characters to get the most resources (e.g. a miner, a blacksmith and an alchemist).
4. This is simple: make classes distinct and fun to play. This adds replay value to the game as well. No reason for the players not to go on another adventure if it wont be the same thing over again, and if they have new problems to solve and new mechanics to play with.
> 4 votes

# Answer
This might sound like heresy in today's entitlement world but consider a gameplay system where leveling up a character also introduces penalties (an aging mechanic perhaps or something else). This will enable players to grow in some areas but at the same time lose power in others. It might create interesting dynamics where a low level character might be better at some stuff than a higher level one
> 2 votes

# Answer
You haven't written what kind of game it is and why do you want players to play with multiple characters, so I could only speculate.

What are the acceptable interactions between multiple characters of one players? It gives more possibilities than simply create multiple classes.

Example A: inspired by Arena Albionu and Vallheru. Characters can be trained in multiple jobs, so that they can produce multiple resources. The final resources are weapons and potions. The energy is limited, so you need many characters to suppor powerfull warrior.

Example B: inspired by Diablo and the team play abilities. You could provide missions, where the player could play with all his characters. There's the rule 'non Hercules contra plures', so 10 low level characters would be more powerful than single high level one. Add the requirements for battle leaders, which would have to have higher level, and you'll result in optimal strategies for having a few high levels, a bunch of middle level and a lot of low level ones.
> 2 votes

# Answer
This really all comes down to the type of game you're making, and ***what*** you'd like to (/have time to) add, in order to promote this growth.

From the standpoint of making something like a traditional RPG, take a tip from Fallout 1 (***NOT 3***, whatsoever):
Build a game in which it is impossible to do everything with one character.

Build a game which doesn't support "classes", but rather customizations -- as the player customizes, open doors and paths and bonuses for those customizations (/modules/attributes/etc).

However, limit the ***AMOUNT*** of modules/perks/bonuses/boosts/etc, so that a character MUST either be semi-specialized, or suffer the penalty of being a very underpowered jack-of-all-trades, who has limited/no access to the additional content.

In the level/quest design phase, make it clear that a particular skill/stat/attribute (or one of a set, or several in conjunction) must be used, in order to access that content.
(eg: to go on a specific quest with a modern-day Robin Hood, you must have 75% lockpick, 60% speech, agility of 8 and a perception of 6).
Make it clear, as you pass each of these checks, that a user ***DOES*** need to meet these requirements.

Have entry to another quest be based on picking up the back end of a car, and moving it out of the way...
...or based around having a carry-weight of more than 300lbs...

These are things which would appear to the player as something they ***CAN*** do, in a meta-gaming sense, but ***CAN'T*** do with their current player, without coming back 20 levels later, and dedicating all of the rest of their stat-points to.

---

In terms of weapons and gear and crafting, you can apply the same concepts...
Looking at WoW and Diablo II, the kings of gear-grubbing (great retention-rates, too).
Instead of making gear have class-requirements ("only druids can wear this pair of gloves"), have gear be based on:

a) stat-requirements ("Boots of Sneaking \[req: sneak \<= 50%\]")
b) att-requirements ("Goggles of Grokking \[req: INT \<= 7\]")
c) story-requirements ("Sword of Swords \[req: 'Quest of Awesomeness' -- must have DEX \> 4 STR \> 7 to begin quest\]")

If you put an item-crafting element into the game, from there, you should be able to auto-generate stat/att requirements, based on, say, the components used to make the item (or used to enchant/patch the item), their quantity, if they have different potencies, et cetera.

Now you have gear that ANYBODY can use...... ***IF THEY HAVE THE ABILITY TO USE IT***, or let them use it anyway, but apply a penalty to misuse.
Give everybody the ability to use a minigun, but if they don't meet the strength requirement, then slow their movement speed by `req_str - player_str` units of movement per turn (or a multiplier, depending on what a move-unit might look like in your game).

Give everybody the opportunity to use a sniper rifle, but without high perception and agility, make it impossible to hit anything...

The point of the whole thing is that if you want to foster replayability with characters who are unique, then you want to ***limit*** what each character is allowed to do.
Therefore, each character with different skill-sets will have different advantages and disadvantages.

Just be sure to spend a lot of time balancing them, and make sure that every major quest point is solvable in at least 3 or 4 different ways, based on characters who MUST play to match their skills, and make side-quests accessable in only 1 or 2 or 3 ways:
Not every character needs to access all content, and instead of thinking about adding class-specific stuff, think about removing access to things based on character-weaknesses.
> 2 votes

# Answer
Make the leveling fun, with support to multiple playstyles. I play wow and I'm always playing low level chars because I think it is fun to level doing only battlegrounds.

Also, if you have some achievements system, make it account wide, so the player can advance some achievements with any char, of any level.
> 1 votes

# Answer
The first key is to have a diverse system of customizing your characters, specifically giving each character choices in the abilities they'll have and what they can do, so you can make your super cool single character, but that single character can't do everything. What this accomplishes is it motivates multiple characters to have access to all the abilities. Maybe your main damage dealer won't be able to heal, so having a healer is nice, or some enemies are resistant to your main's abilities so you have a secondary damage dealer.

^This encourages diversity which is usually enough, but to help things along you can have higher level characters assist in leveling up lower characters, which will help those with high level characters bring up new characters without a long grind. Something that can be done in addition is allow different characters to give passive, boosts to the rest, which will encourage full teams of characters.
> 1 votes

# Answer
SWTOR has a legacy system which i love. You could somehow make new skills if items in the game available to all char's. So that way players will want those skills or items so they will try and keep all their "classes" leveling at the same rate to unlock the skills for example: when you have a lvl 10 "soldier" and Level 10 "medic" all characters can use the stimpack during a battle. and then have a super large ladder like that. You could have powers that required X levels chars in all classes.
> 1 votes

# Answer
What you're essentially asking for is for the player to *like starting over again*.

Games like Diablo or Diablo II had me do this *because of the random generation*, the possibility of finding new weapons or armor on different plays. Diablo kind of left you with a sense of **something being unexplored** in those other games you started but didn't progress in, which is I guess what made me go back and play those lower level characters further.

Games like Final Fantasy 6, did *not* have me do this (I had a single "important" save game with very high level characters) because the play through was pretty much the same, and the variability in play due to item drops was kind of minimal (barring that time I got 2x Minerva armor from defeating Pugs in a treasure chest! And of course what you can get in the Colloseum, but that is very late in the game).
> 0 votes

---
Tags: game-mechanics
---


# Question
Title: How does braking assist of car racing games work?
There are a lot of PC car racing games around which have this unique driving assist which helps brake your car so that you can safely turn it. While in some games it just an 'assist', it will just help your car brake but won't ensure a safe turn. While in others, the braking assist will help you get a safe turn. I was wondering on what could be the algorithm that is followed to achieve it.

A very basic algorithm I could think of was,

* Pre-determine the braking distance of an ideal car for every turn of the track, depending on the radius of the turn, and then start braking the car accordingly. For example, for a turn of less than 90o, the car would start braking automatically at 50m distance from the start of the turn.

A more advanced algorithm, which would ensure a safe turn, could be

1. Pre-determine the speed of the car at the start of each turn, individually for each track, turn and car. Also, pre-determine the deceleration rate of each car individually, which varies because of the car's performance.
2. The braking assist would keep recording the speed of the car at a certain instant of time.
3. Start braking the car appropriately so that the car gets to the exact speed needed at the start of the turn.
4. For example, let the speed of a particular car at the start of a turn 43m in radius, be 120km/h. Let the deceleration rate of the car be 200km/h2. If, at some instant of time, the speed of the car is 200km/h, then the car would automatically start braking at 400m from the start of the turn.

# Answer
Fundamentally, braking assist works comparing the player's car's speed against the speed of the nearest point on the track's optimal racing line, and automatically applying the brakes as needed to bring the player's car's velocity down to match the speed specified on the optimal racing line. It's exactly like writing racing car AI, but only applying the AI's brake outputs, not the accelerator or steering.

This does (obviously) require you to have data about an optimal racing line, so you can tell how much the player needs to slow down. This racing line is typically generated computationally during development, and is shipped with the game as a piece of static data, rather than being calculated at run-time. (I have worked on games which dynamically generated a racing line in front of the player, but this was computationally expensive, and I don't recommend it unless you have tracks that change in unpredictable ways)
> 4 votes

# Answer
You could calculate the path the car would describe if it turns with the current speed without drifting. Then apply brakes in proportion to the distant ***d***, which is the distance measured from the calculated path to the curve.
> 1 votes

---
Tags: physics, racing
---


title: Tongue pull effect

text:
# Question
Title: Tongue pull effect
I've been searching on the net for several days and can not find nothing about this effect. Even a name for this effect. I want to make a character that can use his tongue to pull objects objects it touches in the extension including the tip.

Can anyone help me with a tutorial or code, may be specifically to do this as this taut language of (image)Froad windows phone or the tongue of the Leon of Awesomenauts. In the video its in use.

# Answer
As mentioned by others, it's likely you want an effect similar to a "snake". Effectively, you want to break down the "tongue" into individual pieces that form a trail, much like chain-links.

The objects you'll want to create should work similar to a linked list - each node will point to potential nodes that can come before and after it. From there, you pick some relative positions near each end of each node where they will visually connect when drawn on the screen. You may want to have a maximum angle at which each node can bend relative to its prior node in order to make it look smooth.

From there, you can simply make a node act special if it is "the end" node, i.e. the following node it points to is null. You can have it manipulate things in whatever manner you'd like at that point.
> 1 votes

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


# Question
Title: Moving a 2D character on a straight line
I am trying to create an Android Game and I am facing my first big problem.

After reading blogs, tutos ... I am able to easily move a character with a drag and drop, make it move move to a touched area, but I am unable to move it on a straight line with a finger gesture !

Here's a quick explanation of my problem

I want the character to move on a virtual grid, only up down left right, on a straight line and until it uncounter a wall. If there is nothing on his path, he is unstopped and "fall" from the screen !

He can only move from center of a square to the center on the square he is stopped on. This mean that when he hits a wall, he bounce and go back to the center of the previous square.

For complement :

* It will be a sliding movement
* The wall is just a term, in fact it will be objects ( let say fruits, animals ... ), with different size in a square with the same size that all the other squares.
* I want to movement to be fluid over the tiles, not moving from tiles to tiles with a stop every time.

I am on that movement since weeks and can afford to find a solution, so your help is really welcome !

Thank you very much.

# Answer
> 0 votes
Check to see if the touch was within the player's bounds for X (touch\>playerX && touch \< playerX+width)...If so, check whether the touch was on the right or left side (just check to see if the touch was less than or more than the player's position) and move the player toward the touch on the X axis. Do the same for the Y axis.

Do a simple collision check against wall objects to determine whether to stop the player or keep him moving.

if(!collision) { movePlayer(); }

# Answer
> 3 votes
It sounds to me like you have to take your input, in gesture form, and convert it into simple 4-directional input. You're basically converting very complex input into something much simpler.

You're going to want to take the starting position and the ending position of your gesture command and determine the angle of the vector between them. Recall your high school math - it's a simple formula. You're going to have to get comfortable using COS and SIN. With that angle, just determine which direction it most faces. You can break them up into 90 degree segments for each direction.

# Answer
> 0 votes
if you can move it by a given touch position on the screen, where's the problem? you already know how to move it

using gestures you just have to check the first and the last touchpoints, and find out if it was a vertical or a horizontal gesture according of what that was you just increment the x or y axis

---
Tags: android, animation, movement, character
---


# Question
Title: Direct3D shader compilation fails with constant buffers
I've been particularly annoyed by a 'bug' for a couple days involving D3DCompile and vertex shaders with constant buffers. I'm assuming the bug is my fault (missing flag or small nuance of the poorly documented API).

During my asset compile process I compile this vertex shader:

```
cbuffer Frame : register(b0) {
  float4x4 model_view_proj;
  float4x4 inv_model;
  float4x4 inv_view;
  float4x4 inv_projection;
};

struct VS_INPUT {
  float3 position  : POSITION;
  float2 tex_coord : TEXCOORD0;
  float3 normal    : NORMAL;
  float3 binormal  : BINORMAL;
};

struct VS_OUTPUT {
  float4 position  : POSITION;
  float2 tex_coord : TEXCOORD0;
};

VS_OUTPUT vs_main( VS_INPUT IN )
{
  VS_OUTPUT OUT;
  OUT.position = mul(IN.position, Frame.model_view_proj);
  OUT.tex_coord = IN.tex_coord;
  return OUT;
}

```

With this code:

```
const D3D_SHADER_MACRO defines[] = {
  { "VERTEX_SHADER", "1" },
  { "D3D11",         "1" },
  { NULL, NULL },
};

D3DCompile(
  src, src_len,
  path,
  &defines[0],
  &include,
  "vs_main",
  "vs_4_0",
  D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY |
  D3DCOMPILE_OPTIMIZATION_LEVEL0 |
  D3DCOMPILE_PACK_MATRIX_ROW_MAJOR, 0,
  &blob,
  &error_msg_blob
)

```

I have verified (by stepping through) that my ID3DInclude implementation works and all input data is correct. However, I receive a E\_FAIL with an associated error message:

```
error X3004: undeclared identifier 'Frame'

```

What gives?

# Answer
Constant buffers don't create a namespace; their members are visible at global scope. So instead of `Frame.model_view_proj` you just want `model_view_proj`.
> 5 votes

---
Tags: directx, shaders, hlsl, asset-creation
---


title: Why can't I compare two Texture2D's?

text:
# Question
Title: Why can't I compare two Texture2D's?
I am trying to use an accessor, as it seems to me that that is the only way to accomplish what I want to do. Here is my code:

Game1.cs

```
public class GroundTexture
{
    private Texture2D dirt;
    public Texture2D Dirt
    {
        get
        {
            return dirt;
        }

        set
        {
            dirt = value;
        }
    }
}

public class Main : Game
{
    public static Texture2D texture = tile.Texture;
    GroundTexture groundTexture = new GroundTexture();
    public static Texture2D dirt;

    protected override void LoadContent()
    {
        Tile tile = (Tile)currentLevel.GetTile(20, 20);

        dirt = Content.Load<Texture2D>("Dirt");
        groundTexture.Dirt = dirt;

        Texture2D texture = tile.Texture;
    }

    protected override void Update(GameTime gameTime)
    {
        if (texture == groundTexture.Dirt)
        {
            player.TileCollision(groundBounds);
        }

        base.Update(gameTime);
    }

```

}

I removed irrelevant information from the LoadContent and Update functions.

On the following line:

```
if (texture == groundTexture.Dirt)

```

I am getting the error

```
Operator '==' cannot be applied to operands of type 'Microsoft.Xna.Framework.Graphics.Texture2D' and 'Game1.GroundTexture'

```

Am I using the accessor correctly? And why do I get this error? "Dirt" is Texture2D, so they should be comparable.

This using a few functions from a program called Realm Factory, which is a tile editor. The numbers "20, 20" are just a sample of the level I made below:

tile.Texture returns the sprite, which here is the content item Dirt.png

# Answer
> 2 votes
From what I'm understanding you want to check what Tile you're trying to walk over. You shouldn't check textures. You should compare tile ID. In the end the Texture is just a visual presentation of the tile context ( in this case "dirt" ).

Like so:

```
//Somewhere you see fit
enum TileType{None, Wall, Water, Dirt, Grass};

//When comparing it:
if(tile.ID == TileType.Dirt) // Do something

```

ID in this case is an enum-type of TileType. So when you load you're level you simply assign the type to the tile:

```
Tile myTile = new Tile();
mytile.ID = TileType.Dirt;

```

---

But have you tried it like

```
Texture2D dirt = groundTexture.Dirt;
if (texture == dirt)

```

But again if you want to know the context of your tiles I recommand using Enums or something similar.

It's also easier if you reference to one texture file at all time instead of creating new Dirt textures. Comparing 2 different references will result as false. I'm not sure how the Contentloader from XNA handles this but i'm just sharing just in case.

# Answer
> 0 votes
Have you tried Cleaning and Rebuilding? Cause Like David said, I can't see any problems either.

If that doesn't help I would also see if the type does in fact return a Texture2D by print it out.

hope that helps

---
Tags: c#
---


# Question
Title: Tips for Component Based Entity System message handling
I'm trying to implement a component-based entity system but am a bit confused on how I should handle the messaging. There are two problems I'd like to resolve so I can test the system. Below is the code I have so far,

**The Entity class:**

```
class Entity{
public:
    Entity(unsigned int id):
    id_(id)
    {};
    void handleMessage(BaseMessage &message){
        for(auto element: components_){
            element.second->handleMessage(message);
        }
    }
    template<class T>
    void attachComponent(T *component){
        //Consider making safer in case someone tries to attach same component type twice
        components_[typeid(T).hash_code()] = component;
    }
    template<class T>
    void detachComponent(void){
        components_.erase(typeid(T).hash_code());
    }
    template<class T>
    T* getComponent(void)const{
        return *components_.find(typeid(T).hash_code());
    }
    unsigned int getInstanceID(void)const{
        return id_;
    }
private:
    unsigned int id_;
    std::map<size_t, BaseComponent*> components_;
};

```

**The Base Component and Message classes:**

```
class BaseComponent{
public:
    virtual void handleMessage(BaseMessage &message){};
};

class BaseMessage{
public:
    virtual int getType(void) = 0;
};

```

## 1. Message Type Handling

My first question is how I should handle the different (derived from BaseMessage) message types.

I have thought of two ways for handling the message types of the derived message types. One is to generate a hash (i.e. using FNV) from a string that names the message type and use that hash to determine the message type. So the `handleMessage(BaseMessage &message)` function, would first extract this hash from the message and then do a static\_cast to the appropriate type.

The second method is to use a template as follows (similar to the `attachComponent` methods of the entity class),

```
template<class T>
handleMessage(T& message){};

```

and make specializations for each message type the specific component is going to make.

Are there any drawbacks using the second method? What about performance-wise, why don't I see this kind of use more often?

## 2. Input Handling

My second question is what would be the optimal (in terms of latency and ease of use) way to handle input?

My thought was to create an `InputHandlerComponent` which registers with the keyboard class to listen to specific key presses defined possibly in some file. For example

```
keyboard.register( player.getComponent<InputHandler>() , 'W')

```

I wish there was a more concise guide to component based systems but I guess there are many different ways to do the same things. I have more questions but I think it'd be wiser to first try implementing what I can.

# Answer
In a typical entity system you leave systems to have all the logic for your game and components to store data ***only***, and your entities are just a simple identifier. Input handling would be much easier that way and not to mention the flexibility of your game.

There are plenty of ways to handle events, such as: the observer pattern, or signals/slots. You could do message handling with templates/virtual functions or function pointers, however it'd probably be easier to use boost::signals, even known it's not that great for performance. If you want performance\*, I suggest you use templates and virtual functions or function pointers.

\*I noticed that your code could really be optimised. There are alternatives to the `typeid` operator, which are actually faster than using `typeid`. Such as using templates/macros and simple integers to define a class's ID.

You can look at my Entity System if you need some inspiration (which is inspired from the Java framework Artemis). Although I haven't implemented a way to handle events (other than entity-related events), I left that up to the user, but after sussing out the entityx library, which I found on reddit. I figured I might be able to add an event system to my library. Please do note that my entity system isn't 100% complete on what features I want, but it works and has decent performance (but I could optimize, especially with the way I'm storing entities).

Here's what you could possibly do to handle events (inspired from entityx):

### BaseReceiver/BaseListener

* A base class so you may store listeners/receivers.

### Receiver/Listener

* This is a template class and requires you to override the virtual function `recieve(const T&)`, where T is event information.
* Classes that want to be notified by events that send specific information when an event occurs must inherit from this class.

### EventHandler

* Emits/fires events
* Has a list of Receivers/Listeners objects that will be notified by fired events

I've implement this design in C++, just now, without the use of boost::signals. You can see it here.

## Pros

* Statically typed
* Virtual functions (faster than boost::signals, well it should be)
* Compile-time errors if you didn't emit notifications correctly
* C++98 compatible (I believe)

## Cons

* Requires you to define functors (you can't handle events in a global function)
* No event queue; just register & fire away. (which may be not what you want)
* Not direct calls (shouldn't be that bad for events)
* No multiple event handling on the same class (this could be modified so it does allow multiple events, via multiple inheritance, but may take some time to implement)

Also, I have an example in my entity system, which does deal with rendering and input handling, it's quite simple but it presents many concepts to understand my library.
> 3 votes

# Answer
I'm working on a component-based entity system in C#, but the general ideas and patterns still apply.

The way I handle message types is that each component subclass calls Component's protected `RequestMessage<T>(Action<T> action) where T : IMessage` method. In English, that means that the component subclass requests a specific type of message and provides a method to be called when the component receives a message of that type.

That method gets stored and when the component receives a message, it uses reflection to get the message's type, which is then used to look up the associated method and invoke it.

You can replace the reflection with whatever other system you want, hashes are your best bet. Look into multiple dispatch and visitor pattern for some other ideas though.

As for input, I chose to do something entirely different that what you're thinking. An input handler will separately convert keyboard/mouse/gamepad input into a flags enumeration (bitfield) of possible actions (MoveForward, MoveBackwards, StrafeLeft, Use, etc.) based on user settings/what the player has plugged into the computer. Each component gets a `UserInputMessage` every frame that contains both the bitfield and the player's look axis as a 3d vector (gearing development towards a first person shooter). This also makes it easy to let players change their key bindings.

Like you said at the end of your question, there are many different ways of creating a component-based entity system. I've geared my system heavily towards the game I'm making, so naturally some of the things I do may not make any sense in the context of, say, an RTS, but it's still something that's been implemented and that's been working for me so far.
> 1 votes

---
Tags: architecture, component-based, entity-system
---


# Question
Title: How can I retrieve the outer most points on a 2d graph?
I have a 2d graph which has some points plotted on it.

What I need to do is get only the outer most points so that I can connect them up (isn't really relevant).

What I can't seem to wrap my head around is the algorithm that I need to use in order to do this?

---

I think this might help you understand what I want to achieve:

```
o o o
o x o
o o o

```

All the o's I want to get and the x I want to ignore. Also, the points can be in any position and any shape but I still want to only grab the outer most points.

Any ideas? Thanks.

# Answer
You're probably looking for the Graham scan algorithm, a method for finding a convex hull of a set of points.
> 2 votes

---
Tags: algorithm
---


# Question
Title: What is the format of DXGI_FORMAT_D24_UNORM_S8_UINT?
I'm trying to read the values in a depth texture of type `DXGI_FORMAT_D24_UNORM_S8_UINT`.

I know this means "24 bits for depth, 8 bits for stencil" "A 32-bit z-buffer format that supports 24 bits for depth and 8 bits for stencil.", but how do you interpret those 24 bits?

It's clearly not going to be a 32-bit int, and it's not going to be a 32-bit float. If it is an integer value, how "far away" is a value of "1" in the depth texture?

# Answer
It's an Unsigned NORMalized float, which is a floating-point value between 0.0 and 1.0.

EDIT: To clarify, the Depth component is accessed as a float, and the Stencil component is accessed as an unsigned integer.
> 2 votes

# Answer
Here is some demo code which shows how it works:

```
// create a temporary texture
D3D11_TEXTURE2D_DESC desc;
depthStencilTexture->GetDesc(&desc);
desc.Usage = D3D11_USAGE_STAGING;
desc.BindFlags = 0;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
desc.MiscFlags = 0;

ID3D11Texture2D* tmpTexture = nullptr;
HRESULT hr = getDevice()->CreateTexture2D(&desc, nullptr, &tmpTexture);

// Copy depth buffer
getImmediateContextD3D()->CopyResource(tmpTexture, depthStencilTexture);

// access depth buffer
D3D11_MAPPED_SUBRESOURCE mappedRes;
getImmediateContextD3D()->Map(tmpTexture, 0, D3D11_MAP_READ, 0, &mappedRes);

unsigned int* color = (unsigned int*)mappedRes.pData;

// Extract 24 depth bits
float depth = static_cast<float>(color & 0x00FFFFFF);
depth /= 16777216f; // divide bei 2^24

// compute a grayscale value [0;255]
unsigned char colorValue = static_cast<unsigned char>(depth * 255.0f);

```
> 3 votes

# Answer
Generally for your texture (or rather the SRV you'll create) you use a format in the same "type" family, in this case DXGI\_FORMAT\_R24G8\_TYPELESS - then when you sample it in your shader you just use a .r swizzle to get the depth value out (in 0..1 range). You should not, of course, be reading it back to the CPU - how to interpret the data is going to be the least of your problems if you do.
> 1 votes

# Answer
I solved this problem by using `DXGI_FORMAT_D32_FLOAT` in my depth texture instead. It turned out that the z-buffer is all floats between 0.0f and 1.0f.
> -1 votes

---
Tags: directx11, depth-buffer
---


# Question
Title: Best technique for drawing isometric tiles
I'm thinking about making a simple isometric game with HTML5 Canvas, and wondering what's the fastest way to render the tiles.

Since the tiles are diamond shaped, but drawImage draws rectangles, I have to leave out the corners (the black parts in the following):

I think that leaves me with three options:

1. Use Image objects with alpha channels (.png). I'm afraid this might kill performance.
2. Use a clipping path. If the renderer is optimized this could be pretty fast.
3. Prerender square tiles, like this:

I'd have the black square as one actual tile in memory, and I'd draw such a tile for the green field, and all fields next to it, or above and below. The diagonal (blue) fields would be make up of the corners of the rectangular tiles. This would avoid clipping or alpha channels, but I would have to prerender all possible combinations of tiles, and it seems like overkill.

What's the best or fastest way to do isometric tiles? What do other games, like FarmVille, use?

# Answer
Using transparency (alpha channel) is the way to go, I recommend.

This means that when you want a vertical object on the tile like this:

Then you can do it easily if your renderer draws the tiles back-to-front i.e. painters algorithm.

IMAGE CREDIT: Reiner's tileset.
> 11 votes

# Answer
While the method described by sws and MarkR is also what I prefer, I would like to present an alternative approach.

A hackish option for creating an isometric look with minimal effort is to actually use orthogonal tiles, and use context.transform to set a projection matrix which makes the map look isometric (or a combination of context.rotate and context.scale when you don't know how projection matrices work).

See the specification for canvas transformation methods for details.

Tile image:

Drawing code:

```
    for (var x = 0; x < 5; x++) {
        for (var y = 0; y < 5; y++) {
            ctx.drawImage(img, x * img.width, y * img.height);
        }
    }

```

Result before matrix application:

Same code with same tile image after applying this transformation matrix:

```
    ctx.transform(  1,   0.5,
                   -1,   0.5,
                  160,   0    );

```

With the dashed grid removed from the tile image and changed the tile offset in the drawing code to `img.width - 1` and `img.height - 1` to get rid of the gaps caused by the transformation. Suddenly the tile looks half as ugly:

The main drawback of this method is that when you design your tiles in a graphic editor, they won't really be what-you-see-is-what-you-get. You will also encounter problems when you want to draw any objects which are not on the floor but standing upright. For these you can switch off the transformation matrix before drawing them, but then you will have to calculate the position yourself. You can use these formulas for that:

```
var xScreen = xWorld * 1   + yWorld * -1  + 160;
var yScreen = xWorld * 0.5 + yWorld * 0.5 + 0;

```

(note how the numbers from the transformation matrix reappear in these formulas - you are doing the matrix multiplication yourself here).

**So why should I do this?**

This method is good when you:

1. aren't experienced with designing isometric tiles, but you have orthogonal ones
2. don't want to spend much time on developing an isometric graphic engine, which is somewhat more difficult than an orthogonal one.

Another interesting feature is that when you know your way around matrix calculation, you can modify the projection matrix between frames to zoom, tilt and rotate the map in real-time for some nice fake-3d effects (try to do THAT with isometric tiles).

But when you know how to handle isometric tiles, both artistically and technically, and you don't need any fake-perspective trickery I would rather suggest you to go with diamond-shaped tiles with transparency.
> 9 votes

# Answer
1. You're using context.drawImage to copy pixel data from one source (Image, or offscreen canvas) to another (offscreen or onscreen canvas), which handles alpha gracefully out-of-the-box. Canvas is hardware-accelerated, so testing will allow you to determine whether there's a discernible difference in rendering speeds w.r.t. alpha- vs opaque-pixels.
2. Clipping will require you to push/pop the context's state when defining a clipping path once per tile, which could be a costly operation considering isometric's overdraw.
3. Prerendered tiles would, as you state, require an immense number of 'connector' tiles to be drawn, which may or may not be feasable. (I'm leaning more toward "may not".)

A fourth solution would be to adopt a pre-rendered "chunk" (PRC) of tiles, generated once to offscreen canvases, and then cover the screen with the PRCs once per frame. There would still be overdraw, but building the PRC once and rendering it with an offset determined by the player character's (or view camera's) position relative to the PRC should be a relatively simple operation. This would allow you to combine rendering with option #1, which is IMO the best option if performance weren't a consideration (since it's simplest to implement).
> 3 votes

# Answer
A little alpha channel doesn't hurt much, but if you want to avoid it consider using two quarter tiles, this also gives you some room for making nice tile transitions without doing a plethora of different images, that is probably the biggest advantage:
> 3 votes

---
Tags: html5, tiles, isometric
---


title: XNA button mouse click stop propagation

text:
# Question
Title: XNA button mouse click stop propagation
My game has a background that I can move with the mouse. I want to add some semi-transparent buttons on top of background as DrawableGameComponent. But when I click the Button mouse click will propagate to underlying background and it will be moved. How to detect that click was handled and not to call Update methods of underlying game components?

Sorry for my bad english.

# Answer
> 1 votes
As always, there are different ways to do this. One way would be to first check clicks on the buttons, return a value indicating whether the button was hit or not, and then only handle the click for the background if no button was hit.

I have used a similar method before (code simplified and from memory - not guaranteeing correct syntax, but the principle should be clear):

```
bool ClickHit(mouse.X, mouse.Y) //inside the button
{
    if (this.ScreenRectangle.Intersects(mouse.X, mouse.Y)
    {
        //do button stuff here or in another place, depending on where it's appropriate
        return true;
    }
    return false;
}

///////////////////////////////////////////////////
bool ButtonHit(mouse.X, mouse.Y) //inside the menu
{
    foreach (Button b in this.ButtonList)
    {
        if (b.ClickHit(mouse.X, mouse.Y))
        {
            //this might be a place to do button stuff as well
            return true;
        }
    }
    return false;
}

//////////////////////////////////////////
if (!Menu.ButtonHit(mouse.X, mouse.Y)) //where you do your other stuff
{
    //move your background and do other stuff that you only want to do if no Button was clicked
}

```

I'm sure there are more elegant solutions, but this one should be relatively simple to include into an existing codebase.

---
Tags: xna
---


# Question
Title: Unity editor stalling on second attempt to play
I am attempting to use a Tobii TX300 eye-tracker as an input device for Unity. This device is connected via LAN (TCP connection managed by Tobii SDK). The Tobii SDK has appropriate methods (I am writing in C#/mono) for opening and closing connections with the device.

I can 'play' my application once within the Unity editor and everything works as expected, but on the second attempt to 'play' the game, the editor stalls. The problem also occurs if I am currently playing the game in the editor, and then synchronize any code changes. I notice that this thread remains open:

mono.dll!mono\_unity\_socket\_security\_enabled\_set+0x1e04 (there are usually at least 3-4 threads with the same name, but one always consumes a higher amount of cpu).

If I kill it manually using ProcessHacker then the Unity editor resumes normal operation.

The problem also occurs if I build the application into an executable. The game will play fine, but as soon as I attempt to exit then the application freezes, and I have to manually kill the process.

```
void Start ()
{
    Library.Init();
    eyeTracker = EyetrackerFactory.CreateEyetracker(SERVER, SERVER_PORT, SYNC_PORT, EventThreadingOptions.BackgroundThread);
    eyeTracker.StartTracking();
}

void OnApplicationQuit()
{
    eyeTracker.StopTracking();
    eyeTracker.Dispose();
}

```

Does anyone have any suggestions on why this thread is remaining open, or how to release resources within Unity scripts?

# Answer
The Unity socket security is a system that attempts to ensure that Unity only connects to servers that are expecting a Unity client. This is there to reduce the ways in which Unity can be used maliciously.

In theory this should only apply when running a web build, but in practice I'm pretty sure it can run in other circumstances too, whether appropriate or not. So, check the 'Implications for use of sockets' section on this page and see if setting up the relevant security policy server helps.
> 1 votes

---
Tags: unity, multithreading, socket
---


# Question
Title: Which of these two particle generator lifetime management techniques is better?
What would be better:

1. An explosion class which gets created when needed, does it's stuff, then is deleted. (one instance per explosion)
2. An explosion class which persists through the whole game, and creates a new explosion in the appropriate place when needed. (one instance per game)

# Answer
> 8 votes
Probably the first option, as the second option implies you can only have a single explosion in any given frame. Unless you're talking about having a factory produce the explosion objects in the second option, in which case the two options are not mutually exclusive and you probably should, in fact, do both.

Regardless, the only downside to the first option (at this rough level of abstraction) is the cost of allocation churn. This can be alleviated using an allocation pool for your explosion object instances (for example, in the factory that produces explosions), which will will allow you to have the logically correct model of explosions (that is, there can be multiple explosions and each explosion has an associated object instance) without incurring the overhead of frequent allocations during runtime.

# Answer
> 2 votes
There is a game programming pattern that I think can be applied to your particle/explosion system. Put simply, you maintain a list of explosion classes allocated at startup, and when you want an explosion to occur you pick an unused explosion from the pool of classes and give it back when it's finished displaying.

This makes showing explosions fast and avoids memory fragmentation (which you want to avoid if you're writing for a console). You might not display explosions as often as particles as the pattern is intended for (well, depends on your game, Explosion Simulator II?) but it may be helpful.

Here is the article documenting the pattern, complete with example code, by Robert Nystrom:

Game Programming Patterns - Object Pool

I suggest you check his other work in progress articles too, they're great reads!

---
Tags: architecture, particles
---


# Question
Title: Some theory questions about classic endless arcade games
I had read in the book "A theory of fun for game design" that once the player realizes that he cannot overpower the computer in anyway (or) the AI is unbeatable (badly designed/coded) he will leave the game and not try to beat it. But looking at new age games like "Jetpack Joyride" I think this rule is not true for everyone anymore. Not sure if this is a deliberate choice or just bad design.

I want to know if there exists any history about how the old classic ATARI / Arcade machines games were implemented/tested. Best example would be Pac-man/Asteroids etc. I am hoping that those game makers didn't just increment the speed of the enemies blindly with the level number. They must have tested it enough to ensure that the game can actually beaten up to very high levels and might have tweaked the required parameters to ensure it in their code.

Are there articles/tutorials about designing endless arcade games? I have been searching a lot but couldn't find any.

# Answer
> 5 votes
Seeing as javamonk has already linked some good technical articles, I'll try to approach this from more of a theoretical angle.

---

**Arcade game difficulty...**

From my own personal experience (not sure there are many or even any articles to back this up but I'll keep looking), arcade games are almost always consistently incremental. Every level the enemies get a set amount stronger, they move a set amount faster, the timer is shortened by a set amount, etc. There are variations to this, like when entirely new enemies or other gameplay elements are introduced at certain points, but in infinite games these will run out eventually.

DDA (Dynamic Difficulty Adjustment) is an interesting difficulty concept that can be found in some arcade games. One good example is Astrosmash. The game gets progressively harder in the form of more and more asteroids, but it can also get a little easier for a short time if the player is struggling.

One example of purely linear difficulty (no DDA) in an arcade game is Robotron: 2084. As the player finishes the levels, enemies progressively become more and more difficult with more and more of them appearing in each level. The game was specifically designed to be extremely difficult and yet people have still managed to "beat" it (after 255 levels the game reverts to the original screen). Not because the developers specifically made it so that it could be beaten, but simply because some people are dedicated enough to do so regardless of the odds (barring the literally impossible).

On that note, if you haven't already, check out The King of Kong. Sort of relevant and offers a bit of an insight into the minds of dedicated arcade gamers who set out to "beat" games (or in this case, high scores).

---

**And now for level design...**

This article mostly covers newer games but contains some fascinating insights into level design in general - you might find it helpful and at the very least an interesting read: http://www.gamasutra.com/view/feature/1771/gameplay\_design\_fundamentals\_.php

This is an article about a technique to manage the difficulty of, well, difficulty. It's scalable to infinite levels and uses DDA concepts: http://games.soe.ucsc.edu/sites/default/files/jenningsteats-fdgpcg10.pdf

The information in both of the above articles could be applied to arcade environments - level design tricks to keep people playing, ways to dynamically adjust difficulty so as not to discourage people, etc. You could apply more linear concepts at the same time as well. For example, your game may use DDA in conjunction with a linear difficulty scalar so it consistently increases in difficulty over time while slightly lowering or raising it at certain points based on the player's performance.

# Answer
> 4 votes
A modern example of generating infinite maps is the Mario AI contest. See http://www.marioai.org/LevelGeneration

A good approach to take for generating levels/maps would be a markov chain, http://en.wikipedia.org/wiki/Markov\_chain.

You can create a model for the kind of level you are looking for, then generate much larger ones (possibly infinite) using that model.

---
Tags: game-design, level-design, playtesting, arcade
---