# Question
Title: How to implement "Flick" gesture for throwing an object in the 2D realm
I am trying to implement a FLICK gesture for throwing a ball from point A to point B on the iPhone. This is my current plan....

Using `touchesBegan` and `touchesEnd` I can find the direction I need to move the ball, and with a small counter, I can impact a certain velocity on the object.

My question is simple...

***Is there a better way to do this ?***

I am unaware of the physics engine and how I could use it in this scenario. Any good suggestion will help !

# Answer
The flick gesture is managed in two separate step: detection and conseguent dynamics.

**Flick Check**

The first one is the toughest. Basically you have to collect points in time and space when the touch starts as the touch moves. When the touch ends you have to look to what you gathered to see if there were a Flick.

A simple flick check can be done by looking to the last two recorded position. Computing the distance and the time that occurred between the two events one can easely find a velocity vector: if the vector is large enough a flick to that direction may be triggered. Tree or more points can be used to let filter noise.

Not everyone knows that a flick done with a finger moves quadratically versus time (ie accelerates) while a flick with mouse is linear (ie moves roughly with the same velocity): if you are sure that the flick will be done with a finger, you can use the records to compute a quadratic regression coefficients of determination, to see how good the last n records look like a parabola.

Another common problem is the reliability of the quantities reported by the event handler; large distance covered in few milliseconds are suspect: never trust super high flick speed.

This kind of problems are common when the device is busy so some event may be discarded while other old pending events may be posted at the same time.

The check for zero division you certainly do while computing speed, is a good place to check for near-zero division: if this appends you may discard that point and check some previous one that is recorded before.

**Flick Dynamics**

After checking if the flick happened for real, you should have a velocty vector: a speed and a direction. You may consider to bound that direction to one axis if you see that the speed in the other axis is small compared to the speed on the other axis as well as to "snap" the direction to one of the diagonals if the speed on both the axes are roughly the same.

Once you get the velocity vector the thing start to be fun: you have to simulate what would happen if you would actually impressed a thrust to the object.

If you try to push a bottle on your table you will see that it start to moving by itself when you release it whether it is standing or rolling then gradually slows to a stop.

This happens because of the *friction* where the slowing depends on the type of friction and the binding reaction, which in turn depends on the weight of the object.

The friction is manifested as a **force** that opposes motion so in the absence of forces that sustain the movement, the object decelerate following the Newton's second law.

If we call Fk the force due the (kinetic) friction and we assume that the object lies on a non inclined plane we can compute the deceleration due the friction ak:

The first line states that the force is proportional by mu to the object weight (that is the object's mass multiplied by the gravitational acceleration: m\*g).

The second line is the second Newton's Law for the friction force: the deceleration ak is bounded to the friction force by the object mass.

The third line computes the deceleration using the frist two lines.

All this simply tell us that the deceleration is constant and it will appear realistic if you use the save value for big and small objects.

**Apply Flick Dynamics**

Once you have the initial velocity vector there are several way to apply the deceleration.

If you have to update yourself the position of the object, you may integrate dinamically the deceleration or use the equation of motion to establish the position when at a given time.

The first one can be used if you want to add variable to the simulation (like wind or variable friction areas or with user interaction); the second one is suitable if you are sure that the motion will not be perturbed.

If you are using a framework that allows transition and easing you can compute the final position and a quadratic easing to simulate constant decelleration.

*Euler integration*

To simulate the dynamics you have to store the object position, the current velocity,and the last update time (the touch release for the first time).

At each position update you have to compute the elapsed time from the last update (dt), multiply the ak by dt to obtain the velocity loss then substract that loss from the current velocity. Likewise multiplying the updated velocity by dt you will get the displacement to apply to the position to get the new position.

The euler integration works well if the elapsed time between updates is small-enough™. Here you can sum up all the accelerations, beside friction, to take in account other forces if there are.

*Law of Motion*

The law of motion is described by the initial velocity and the time elapsed taking into account the deceleration. This means that you have to store both the initial velocity and the time the flick start (when the touch is released) but you do not need to update them.

To make the things simple let's consider the velocity as a direction unit vector multiplied by a (positive) velocity value; in this case the aceleration has to be considered negative.

If the initial speed is V pixel/ms and deceleration is -A pixel/ms/ms then every millisecond the velocity loose A pixel/ms until it reaches 0 pixel/ms.

The red area represents the distance covered in t milliseconds (the integral generalization of the formula space = speed * time).

Knowing V,A, the elapsed time you can compute the distance covered (the red area) using the formula for the trapezoid area:

you can multiply **Δx** by the velocity unit direction to get the actual displacement and add it to the initial position to get the position after t ms.

Take into account that V reaches 0 when At = V i.e. after V/A milliseconds; if t \> V/A then **Δx** remains to its final value:

*Implementation notes*

In both cases it would be useful to delegate the position updating to external component. When an object has to "flick" you instatiate an instance of a "position Manager" giving the relevant initial parameters and the moving object reference. At each update you traverse the manager list and let them update their object (and destroy/recycle themself when finished).

*Transition + easing*

If your framework supports it you can set a quadratic transition by computing the final position, the transition duration and a quadratic easing.

The final position can be computed using the final **Δx** as explained before; the same for duration.

In summary if **P** is the initial position, **v** is the velocity unit vector, V is the velocity value and -A is the deceleration then:

If your framework does not support the quadratic easing you can emulate it using a cubic bezier transition with the following control points:

P0 = (0,0); P1 = (0.33,0.66) P2 = (0.66,1) P3= (1,1)

(generally p0 and p3 are implied)

You should see the first branch of the parabola.

**My favourite parameters**

After some test I found some value you may use as starting point to find your own:

*Flick treshold*: 0.3 - 0.5 pixel/ms (no flick if slower than this)

*Flick scaled speed*: 60% - 90% of the flick speed; transfer less motion to the object than the final "flick speed" gives better results

*Flick cap speed*: 1-1.2 pixel/ms; I don't allow flick faster than this but this is very subjective

*flick deceleration*: 0.004 pixel/ms/ms; loose one pixel/ms 4 times in a second (4 pixel/ms in a second if you prefer)
> 9 votes

# Answer
The UIGestureRecognizer might be something you can use. There are subclasses for many different gestures.
> 3 votes

---
Tags: physics, iphone, objective-c
---


# Question
Title: Should each UI screen contain the list of screens on the stack or should I use a manager class?
I have a `Screen` class that encapsulates the updating and rendering of several distinct states, such as the menu, gameplay, and credits. A stack of screens exists on which the screens themselves need to be able to push new, and pop screens (imagine selecting "Start game" from the main menu, pushing the gameplay screen and popping the main menu screen).

I could have a `ScreenManager` class to babysit my screens but this would basically just be a wrapper around a list. I am therefore considering to pass each screen the `std::list<Screen*> _screens` and have them push and remove as they see fit. What I am worried about is overhead of copying this list around. If I recall correctly, since the list contains pointers to screens, the only thing I would be copying are the list of pointers, correct? And not the actual screens themselves.

Would this be an advisable way to go, or would you recommend creating a "wrapper class", such as a `ScreenManager` in any case?

# Answer
If you are *copying* that list around (i.e. passing in the list by value) then the overhead of copying a list of pointers is the least of your concerns - it probably **won't even work as you expect**. Each Screen will have its own separate list, and modifications won't propagate to other screens. You would need to share the *same* list between all screens. There are two simple ways to solve this:

* You could make the list *static* inside the `Screen` class so that only one instance will be created and shared by all `Screen`s.
* Or you could pass the list *itself* as a reference or a pointer so that all `Screen`'s have access to the **same** list and no copying is performed. I.e:

```
// Inside the Screen class you would store the screen as a...
// Pointer
std::list<Screen*>* _screens;
// or
// Reference, must assign in constructor/initialization list
std::list<Screen*>& _screens;

```

Careful with scope too. You must keep the list alive throughout the duration of the application.

But still, I'd really recommend creating a `ScreenManager` class and I see no benefit from doing the list handling like this. Even if it's just a simple wrapper, it's going to be easier to understand (and extend if needed).

And by the way, a `ScreenManager` class is not necessarily just a wrapper around a list. There can be many different features added to it. For example, my ScreenManager is also responsible for:

* Keeping a dictionary/map registry of screens and their ids which allows me to do everything by id: `screenManager.PushScreen("PauseScreen")`
* Handling "smooth" transitions between screens, such as fades or slides. Basically, each screen has a fade out and fade in time and a float fade value between 0 and 1. The screen manager takes care of handling these transitions and interpolating the fade value. The screen decides what to do with this value (i.e. darken the screen, offset sprites, etc).

And I've seen screen managers supporting other operations such as:

* Add delays between switch/push/pop screen operations.
* Popping several screens at once.

I think it's neat to have all of this encapsulated in its own class, rather than polluting the Screen class. So, it depends a bit on what you need, but I still think creating a simple ScreenManager class would be better than passing that list around.
> 6 votes

# Answer
Since pointers act only as references to addresses you would only be copying those addresses and not the screens themselves.

*Personally*, I prefer to have a `ScreenManager` merely because the manager can be used for more than just holding the screens. For example, what if I wanted to find all of the Enemies being drawn to a given `Screen`? Rather than do some fancy checking inline, I could just create a function which returns all of the objects of a certain type from some `Screen` inside of the `ScreenManager`. In the end, the choice between a simple list and a manager depends on how complicated of a game you're making.
> 2 votes

# Answer
As my previous speaker noted, I'd also prefer the `ScreenManager` of the same reasons.

If you really want to follow through with adding the list to your `Screen` class, I'd use a pointer to the list since there should be only one instance of it (like singleton pattern, which is another argument for a `ScreenManager` class)

Concurrency is another issue you should be aware of when building this logic into `Screen` class. E.g. the `ScreenManager` of my engine loops over all `Screens` and calls the `Update` method of every `Screen`. It is possible that a `Screen` pops itself off the stack in `Update` which breaks the iterator logic in the `ScreenManager` class. Pretty easy to fix if there is just one place to look at...
> 2 votes

---
Tags: architecture, software-engineering
---


# Question
Title: How do I start writing an MMO game server?
I am developing a multi-player on-line game.

I just started coding the server but I have no idea how to do it. Do I have to use threads ?

And if i do, do I need one thread for every client?

Knowing that I am using UDP, can I use multiple sockets in different threads to send packets on the same port?

edit:

```
server does:

-listen for client connections

-when a client connects:

    -update files (send new files to the client)

    -retrieve data from database

    -loop to retrieve and update live data

-when client disconnects:

    -update data in database

```

# Answer
> 40 votes
I may be wrong, but your question makes it seem like you are missing a lot of knowledge in order to successfully write an MMO server. I know this message will likely fall on deaf ears because I was in your position when I started programming.

**My answer:** If I were you I would start smaller. If you want to learn to write an MMO server I would do the following.

* Write a TCP based p2p chat client.
* Extend that chat client to work with NAT routers
* Extend the chat client to have a central server that authenticates and stores message history
* Extend it to have a secure handshake with the server to verify the client software and server software/location
* Write a high level architecture of what you would want your MMO server to be
* Read some articles on MMO server architectures
* Start expanding your high level architecture into more and more detail
* Write essential user stories for your architecture
* start implementing your server

**The answer you probably want:**

* Write a thread for the listener to accept incoming connections using TCP
* Once the player is connected, use TCP for chat messages and sector changes
* Use UDP for in-sector movement
* Each connection gets its own thread for the messaging
* UDP can be implemented with threads (if you really want) but I would probably use some sort of queue on one thread that accepts movement messages. Or spread it out depending on how many connections you get.

---
Tags: c++, networking, mmo, server, multithreading
---


# Question
Title: What engine could I use for a simulation?
I have a simple requirement: I want to put some ships (I have some mesh models) on a body of water, with islands, and play with various collision avoidance and command and control algorithms. So I need a environment where I can modify object behaviour but where the world and its mechanics are already coded. I was expecting that this would be trivial to find as this is such an obvious requirement for say, AI experimentation. But I haven't found anything open source or commercial. I've looked at Glest, Delta3D, Spring, Unity, ORTS, Strive, and VBS2. I looked for, but never found, the Homeworld Engine. I also found Breve, Lagoon (seemed perfect), ECSLent, but these were/are either no longer supported or documentation (if it exists) is confusing enough that it isn't clear what can/can't be done or how to go about it. Interestingly, it seems like you have to roll your own if you have a need eg. Breve, Lagoon.

So I'm putting the question to you: is there a virtual environment out there, with physics, that would allow a person to focus just on behaviour creation? What have I missed? Thanks for any guidance you can provide.

# Answer
> 5 votes
Unity is probably your best option for this, but you're going to have to do some work to get what you want, it's *not* actually that simple. You could try checking the Unity store, though, to see if someone has made something close to what you want, or even exactly what you want. Something like Lagoon could be made fairly easily by going through the documentation and tutorials for Unity, at least in terms of setting up the environment.

---
Tags: simulations
---


# Question
Title: Fitting a cap for a hollow object in blender
I have a thin-walled hollow object that I made by extruding a closed path that formed an outline. So the objecft is like a hollow pipe with a 1mm-thick wall (but the cross-section isn't a simple oval). Now I'd like to fit a cap for it. Since my objectt is hollow, I can't just boolean-intersect the shape with a block to make a cap -- that just gives me the outline of a cap.

How can I produce the shape for the cap I need?

If there were a "fill hollow shape by deleting all internal faces" tool, that would help. Or maybe there is a more obvious approach?

# Answer
Sounds like you'll want to do some Face Filling.

For example, starting with something like this:

First, if you're putting a cap on this shape, you likely don't need that internal ring of vertices. You can join the vertex pairs that make up the current "cap" between the internal and external faces. Select the vertex pairs across from each other and merge them into one, using Alt+M.

When you're done it should look something like this:

Then you can generate new faces to cap your object. Select the perimeter of vertices/edges that will make up the cap, these should not have any faces between them. Then press Alt+F. This will generate a new face. Something like this:

**EDIT**

Keep in mind that the internal faces are not removed by this method. This is so that if the other end remains open, the internal faces will still be there. Additionally, you'll notice that the face generated is not pretty. You can attempt to create a nicer looking face by selecting 3-4 vertices at a time, and pressing Alt-F to create a face there. This will give you more control over where the faces are placed, and allow you to generate quads if you want them.

For more details on filling faces, see this tutorial.
> 3 votes

---
Tags: 3d, blender
---


title: Documentation on 2D space partitioning

text:
# Question
Title: Documentation on 2D space partitioning
I am looking for documentation that explains the different kinds of (well the major ones anyway) 2D space partitioning algorithms & data structures.

Any pointers besides 'Google it and sift through hundreds of papers'. A book perhaps?

# Answer
> 7 votes
I've got this sort of info spread over many books on my bibliography, but I'm currently away from them. But from what I could gather up from memory and browsing through the table of contents online, I recall the following books:

**3D Math Primer for Graphics and Game Development 1st Edition** or **Mathematics for 3D Game Programming & Computer Graphics**

or

Chapter 16 (Visibility Determination) of 3D Math Primer for Graphics and Game Development 1st Edition (*strangely the authors seem to have removed this section from the second edition of the book*) covers the most common techniques (i.e. grid system, quadtree and octree, bsp trees, portal occlusion). The book is really good, although perhaps not the best of its kind.

I've seen Mathematics for 3D Game Programming & Computer Graphics being mentioned very often, but unfortunately haven't gotten my hands on it yet. From the table of contents, it seems to cover space partitioning algorithms too. Not sure how they compare against each other.

Naturally, the focus of these books is on the math. And although the title says 3D, they are also quite relevant for 2D programming.

**Real-time Rendering 3rd Edition**

Chapter 14 (Acceleration Algorithms) of Real-time Rendering also covers most of these topics, and this is actually my favorite general graphics programming book ever. Very comprehensive but I don't recall how much it covered this particular subject.

The focus of this book is on the graphics theory, but it covers such a *large* amount of topics that I could hardly find a better recommendation for anyone interested in the field.

**Game Programming Gems**

The previous books were mostly theoretical though. For more specific and *practical* advice, I've read several articles on the subject scattered throughout the Game Programming Gems series. Some that come to mind:

* Octree Construction - Game Programming Gems 1
* Loose Octrees - Game Programming Gems 1
* Sphere Trees for Fast Visibility Culling, Ray Tracing, and Range Searching - Game Programming Gems 2
* A High-Performance Tile-based Line-of-Sight and Search System - Game Programming Gems 2
* Sphere Trees for Speedy BSPs - Game Programming Gems 5
* Spatial Partitioning Using an Adaptive Binary Tree - Game Programming Gems 6
* BSP Techniques - Game Programming Gems 6

---
Tags: algorithm, books
---


# Question
Title: Moving along a flat plane with accordance to camera view
I'm making a 3D game, and I'm stuck on a little experiment.

I currently have a flat plane with a free camera running around, and a sphere (really, a light approximated as a sphere) that rests above the surface of the plane at, say, 50 units up. I'm trying to move the sphere, and I can do this easily by simply adding to the position in the X and Z direction. However, I got a bit messed up because when I move the camera, pressing the left arrow might move the sphere to the right, because of the coordinates. So I'm trying to move the sphere along the X and Z dependant on where my camera is looking.

For example, if I was looking at it from behind, down on an angle, I expect the sphere to move to the camera's left along the plane, or move down towards the camera, still along the plane.

I have seemed to get left and right working with `a.Position -= Vector3.Cross(((FreeCamera)camera).Forward, ((FreeCamera)camera).Up);` but trying to move the sphere using just the camera's forward causes the sphere to move into or out of the plane, depending on the angle of the camera (this makes sense, because the camera's forward may be pointing into the plane).

My question is, how do I move an object left or right along a plane (remaining 50 units above the Y axis) in accordance to the camera's direction? For example, viewing the plane from its left facing towards the center, moving left should make it move towards the top of the plane if viewed from the back or to the camera's local left.

Here's two screenshots showing what I mean:

When viewing the red light from here: Pressing right should give me this. Notice how the red sphere has moved (disregard the fact the camera angle changed slightly):

# Answer
Your Camera class generates a View matrix right? Multiplying a position in world space by the view matrix results in that same position being transformed into view space. Conversely, if you multiply a position in view space by the inverse of your view matrix, you'll get your position back in world space. On to your question.

**Part 1) Moving light in relation to the camera**

So you'd like to move the light position according to the camera's current orientation. An easy way to do this is simply to apply the transformation in view space (as opposed to world space). As an example:

```
Vector3 viewLightPosition = Vector3.Transform(light.Position, camera.ViewMatrix);
if(keystate.IsKeyDown(Keys.Right)) viewLightPosition += Vector3.Right * moveSpeed * dt;
light.Position = Vector3.Transform(viewLightPosition, Matrix.Invert(camera.ViewMatrix));

```

That takes care of the problem where movement should always be relative to the camera.

**Part 2) Clamping the light back onto the correct plane**

In step 1 the light was moved according to the camera, but disregarding the plane. Now it's time to fix that, i.e. you need to validate the light position to ensure that it remains at the same distance from the plane. The first thing that occurs to me would be:

1. Project your light position *into* the plane.
2. Then move it out of the plane by the desired amount along the plane's normal.

I'm not sure but I think XNA's Matrix.CreateShadow could be leveraged to simplify the first step. Once again, example:

```
Matrix projectionMatrix = Matrix.CreateShadow(plane.Normal, plane);
light.Position = Vector3.Transform(light.Position, projectionMatrix);
light.Position += plane.Normal * distance;

```

**Note) Calculating the correct plane for your wall**

Of course part 2 only works if you're using the correct plane. Since the Plane is usually stored as a Normal and Distance from the origin, it might be hard to come up with the correct values to fit a specific object in the world.

Luckily the Plane class also has a constructor that makes this task easy - you only need to pass it three points that lie on the plane. So to create a plane for your wall, all you'd have to do is:

```
Plane plane = new Plane(wall.Vertices[0], wall.Vertices[1], wall.Vertices[2]);

```
> 1 votes

# Answer
Figure out the camera's rotation around the Y axis and use that with trig functions to calculate the X and Z distances:

x = cos(angle) * speed

z = sin(angle) * speed

btw an answer I gave to a different question described the same math for a slightly different situation https://gamedev.stackexchange.com/a/18395/6588
> 0 votes

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


# Question
Title: Complex Game AI for Turn-based Strategy Games
I'm doing some research for a turn-based Strategy game project and looking for good resources on this topic. The game is a typical war game where countries can fight each other, deploy units and have these units move around on a hexagonal tilemap, attack each other, etc.

I'm particularly interested in how the AI of Civilization V is organized! According to Wikipedia the game uses four different AI systems for different layers of the game's AI:

* tactical AI controls individual units
* the operational AI oversees the entire war front
* the strategic AI manages the entire empire
* the grand strategic AI sets long-term goals and determines how to win the game

Conceptually this looks like it makes a lot of sense to achieve a complex AI and it makes me curious to find out about how these different AI systems work (and work together). The tactical AI is probably the most easy to understand since it handles the decision-making for a single unit (move, attack, repair, retreat, etc.) but I think the other AI systems are where it really gets interesting. For example what does the operational AI do and how does it do that? I'm sure these are best-kept secrets by Firaxis Games but it would be cool to get some discussion started on this to find out more about it.

Also if anyone knows any good books that handle turn-based strategy game AI it would be great to know. Obviously this is a sparsely seeded topic on the web. I got "Programming Game AI by Example" but that book is more about single agent behavior AI than high-level goal-oriented AI.

# Answer
Whilst I agree with DampeS8N's opening paragraph (i.e. game AI only needs to be smart enough to make the player *think* that it's smart), I feel that this question needs a little more elaboration. The data structures in use could be FSMs for all levels, but that doesn't really answer the question as to *how* the individual systems work.

Disclaimer: I have hardly played the Civilization games so my understanding of the gameplay is limited. If there are any obvious errors, I do apologise. Please correct me, and I'll gladly edit.

I'll be taking quotes from the original IGN Article.

**1. Tactical AI**

> At the lowest level, the tactical AI uses the forces at hand to win a battle on a local scale.

This is probably the most standard part of the subsystem. There are limitless ways to carry this out from using FSMs, Behaviour Trees (or even performing random actions, depending on the difficulty of the AI).

However, since this is a turn based game, similar to Risk, I think what is more likely happening is that each unit is assigned a score. There are then multipliers attached to this score depending on different variables (allegiances, terrain bonuses, etc).

The outcome is then calculated by something like this:

```
If (AI unit score >> (much greater) enemy unit score) Then Completely destroy enemy unit
If (AI unit score > (somewhat greater) enemy unit score) Then Partially destroy enemy unit
If (AI unit score < (somewhat less) enemy unit score) Then Partially destroy AI unit
If (AI unit score << (much less) enemy unit score) Then Completely destroy AI unit

```

It makes sense that the AI will try and maximize this score when in battle.

Add in an epsilon value (e.g. small random chance of failure/success) and you've got a pretty decent looking AI (no one wants a perfect opponent, that's just not fun!).

**2. Operational AI**

> One step up from that, the operational AI picks which battles to fight and makes sure that the necessary forces are available.

I think there are a couple of points to this:

* Evaluating current strength
* Reinforcement of units
* Evaluating which fights to pick/avoid

*Evaluating Current Strength* \- This just screams Influence Map to me. It can be easily represented on a hex grid. As this subsystem is combat oriented, the influence values can be representative of the strength values of each unit in the vicinity. If you have a massive army focused in a small area of hexagons, the influence value will be huge and the operational AI will take this into account when evaluating fights to pick. Don't forget, the influence values of opposing armies will also be calculated. This allows the operational AI to predict potential incoming threats.

*Reinforcements of units* \- By receiving information on opposing factions from the influence map, the AI can determine which units are under the most threat. The AI can then issue a command to close-by units to go and reinforce the threatened parties.

*Evaluating which fights to pick/avoid* \- A couple of situations can occur here. If the AI detects a unit is under threat AND there are no nearby units to help it could a) decide to sacrifice the unit (if they're just lowly infantry, instead of an irreplaceable general, for example) or b) Order the unit to retreat. Conversely, if the AI detects a weak enemy unit near an army, it could order the units to take this enemy out.

Here's a decent paper that makes use of influence maps in Real Time Strategy games.

**3. Strategic AI**

> Moving even higher, the strategic AI manages the empire as a whole, focusing on where to build cities and what to do with them.

"Where should I build a city?" just sounds like position evaluation. Chess programs and other games use it to determine the desirability of a given position. For example:

Hex A: Close to resources, on high terrain, close to allies, close to enemy Hex B: Far from resources, on mid level terrain, medium distance from allies, far from enemy

The position evaluation function could take these three factors like so:

```
Score = Proximity to resources (closer yields a higher score) +
terrain elevation (higher yields higher score) +
proximity to allies (closer is better) +
proximity to enemies (farther is better)

```

And whichever hexagon has the higher score, will be where the city is built. More information on evaluation functions can be found here.

I reckon the strategic AI also has a bunch of pseudo-prebaked strategies in the game depending on the type of victory the AI is going for.

**4. Grand Strategic AI**

> At the top of the ladder is the grand strategic AI, which decides how to win the game.

I think this is probably the simplest of the bunch, and it gives the impression that it's more impressive than it really is. In a game such as this, there will only be a finite number of victory types. The article mentions a Conquest victory, assuming that there are also Alliance victories, etc, it could be as simple as randomly picking one of the types and then pass it onto the other systems.

EDIT: Of course as pointed out by DampeS8N, the type of map could dictate the best victory condition to go for, in which case it could be hardcoded by the designers or some sort of evaluation function factoring in different variables.

**Summary**
I think what's really important to note about this kind of system is that the way the subsystems are layered, they don't actually need to be communicating a great deal with eachother. It looks to be a top-down architecture with the components loosely coupled. From a technical design point-of-view it's clean and it's flexible and probably takes its inspiration from Emergent Behaviour and/or the Subsumption Architecture.

I really do apologise for the length of this post, it's turned into a bit of a beast :(

Either way, I hope it helps!
> 19 votes

# Answer
In general AI in games shouldn't be thought of as 'complex' it is all about getting what you want with the least possible effort. The name of the game is Emergence.

In this case, your fundamental conceptualization is wrong. These 4 systems do not need to work together at all. They just need to look like they do. They can also be a lot more stripped down than you think they need to be.

You've also reversed the order of difficulty. The hardest component of Civ AI is the tactical AI, followed closely by the Operational. Strategic is probably very simple, and the grand AI is probably simpler still.

Communication between components is more like a system of grunts and less like real communication. From high level to low level it would look like this:

## Grand AI

assess the state of the map. Given the knowledge the AI has (which could be everything or only what it would have if it was a player) it decides what end goal is fastest to reach. It is likely a Finite-state machine that does some number crunching and picks a goal. Possibly it is something more exotic; a Genetic Algorithm or possibly a Bayesian based doohickey. It then grunts down a message like "more science."

## Strat AI

then looks at what it has available to work with using much of the same information. It goes about trying to meet that overall goal, but also worries about more detailed aspects of the game. Am I at war? Do I have starving people? so on. It is probably also a Finite-state machine, possibly Fuzzy Logic (which is really just an evolution on an FSM.) Let's assume it is a simple FSM. It will ask the above questions in an order where, given certain criteria, it will decide different things need to happen this round. I'm at war, allocate monies for training soldiers. My people are starving, build a granary here rather than building something sciencey.

Picking what units to build might be part of Strat AI or Op AI depending on how we are splitting things up.

## Op AI

will take the units that are available and will assign them to move into different fronts of war. It will decide the overall shape of the conflict, where new units will head once they are deployed. It is probably also an FSM. It may notice that the enemy on Front A is attacking with units weak against Unit B, and will send more Unit Bs there, rather than to the other Front which is strong against Unit B. It will issue general orders to the units at large. Attack at will. Retreat. So on.

## Tactical AI

is unit specific. Each type of unit will react differently to the general order. A unit that is intended to suicide, may ignore a retreat order. Units that are wusses might retreat even when told to fight. Civ is typically very light on this kind of thing. Generally all the units in Civ follow their commands. Given the larger order they are under, they are (see a pattern here?) an FSM. Am I injured? I should back out and heal up. Do I have an advantage in this location? Attack. Am I too close to attack? Back off. And the complexity of this FSM need not be much more than those 3 things to be effective and convincing as intelligent.

### Can this be enhanced?

Yes, of course. The question is if the players will notice. And 99% of the time they will not.

Now, this is all decision making AI. There are other AI subsystems at play here. There is A\* or some other path-finding algorithm that lets units find the shortest path to a location. There are algorithms for finding the best location to start new cities. So on. There are often grouped with AI, and often are really more complex then the 'thinking' part of the AI. In fact, the code for finding the answers to the questions the FSM needs to ask is often orders of magnitude more complex than the FSM itself. How exactly does one decide that
> 9 votes

---
Tags: ai, strategy, turn-based-strategy
---


# Question
Title: If I know a given action will result in a collision, should I allow the action to occur anyway?
I've finished programming my game engine, and now that I've been testing it, I've been noticing some graphics problems.

The big one is that when a player tries to push against a wall, their character will "jiggle" against it as it constantly tries to enter the wall's space and the collision detection constantly pushes it back outside.

What is the proper way to handle such a situation?

My first instinct was, if moving in a certain direction causes a collision, disable movement in that direction until the entity's position has changed. I.e., once an object falls onto a platform, disable gravity until the object is no longer above a platform.

Is there a better way to resolve repeated collision detections between the same two objects in the same overlapping space?

# Answer
> 5 votes
About character collisions with a wall, for instance (I'll use some arbitrary values as example): if you are 10 units (e.g. pixels) away from a wall, and a single step would normally move you 20 units in that direction, the correct behavior is for your character to move 10 units and stop there. If you cancelled the action instead, you'd remain 10 units away from the wall which is not what you'd want.

One way to do this is to move the character by the full amount, then detect the collision and its depth i.e. *how much* the bounding boxes of the character and the wall are overlapping, and move the character back by that same amount. If you do this correctly you shouldn't be getting any "jiggle" behavior from your character, he'll just press against the wall and stop there. If he's jiggle'ing then you're probably moving him back too much (you're probably moving him back to position he was before the collision, instead of clamping it against the wall boundary).

That being said, I usually see gravity being treated as a special case. In most implementations I've seen, the character stores an `onFloor` flag and gravity is only applied when that flag is false.

**Edit:** I guess you could expand this last concept and create additional flags such as `touchingRightWall` or `touchingLeftWall`, but only when the boundaries of the character and the wall *match exactly*. In that case you could perhaps bypass movement altogether. But if the boundaries are not matching precisely, you should let the movement take place and let the collision detection system resolve any intersections.

# Answer
> 2 votes
This problem usually occurs when the code clamps positions before detecting a collision. I.e:

```
MoveCharacter();
ClampPosition();
CheckCollision();
DrawFrame();

```

instead of

```
MoveCharacer();
CheckCollision();
ClampPosition();
DrawFrame();

```

The reason it "jiggles" is because the check happens after the character has been clamped to a "safe" location, but because the character is in a non-colliding location at the time of the check the engine allows for the character to continue to move, then the character is drawn and then the next frame the check fails, Clamp is called, causing the character to "snap" back to the safe location.

# Answer
> 0 votes
I've had the same problem recently and fixed it like this:

move the object, checking for a collision, if collision is found, place object outside of colliding object. draw the object.

The player could keep running into the wall without any jiggling because before he is drawn, he will be placed at the side of the object.

# Answer
> 0 votes
Using vector / plane mathematics you can calculate exact point of collision with wall that will happen in next frame. This assumes that your character has velocity which you can use to calculate movement vector that will happen during next frame. After finding point of collision you can calculte sliding vector that will move your character along wall, this vector actually can collide with another wall.

So back to your question, you should calculate the exact position of collision where your character should be located and what actually should happend then. If this is a wall and its FPS game, then let character slide along it.

---
Tags: collision-detection
---


# Question
Title: Some assistance with selective 2D Bloom in XNA
I'm in need of some assistance, as I've been at this for 2 days now and have gotten almost nowhere.

I'm trying to use the XNA Bloom sample's component to apply bloom only to my UI text. (The only way I know of to achieve a nice glow around the text)

(No need to look up the sample, I'll post all the relevant code for reference)

I'm trying to use a Rendertarget to store my UI. Currently it works great, except that the background of the rendertarget is always either A.) Black or B.) The purple screen of doom.

My SurfaceFormat is currently set to Color, so that's not the issue.

Here's how I'm drawing my UI:

```
 GraphicsDevice.Clear(Color.Transparent); //clear the device
 spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied); //start my spritebatch

 BloomComponent.BeginDraw(); //Call the method in the component to start rendering to the rendertarget

 // Draw all of my UI stuff

 spriteBatch.End();  // end the batch
 GraphicsDevice.SetRenderTarget(null);  //clear the rendertarget
 GraphicsDevice.Clear(new Color(0, 0, 0, 0));  //clear the device

```

Then, later in my code, I call this:

```
 BloomComponent.DrawBloomedScreen();

```

Which draws my bloomed objects to the screen. This all works fine, except, inexplicably, the rendertarget has an opaque background.

Here is my BloomComponent, in case the problem is in there:

```
 namespace MyGame
 {
 public class BloomComponent : DrawableGameComponent
 {
    #region Fields

    SpriteBatch spriteBatch;

    Effect bloomExtractEffect;
    Effect bloomCombineEffect;
    Effect gaussianBlurEffect;

    RenderTarget2D sceneRenderTarget;
    RenderTarget2D renderTarget1;
    RenderTarget2D renderTarget2;

    // Choose what display settings the bloom should use.
    public BloomSettings Settings
    {
        get { return settings; }
        set { settings = value; }
    }

    BloomSettings settings = BloomSettings.PresetSettings[0];

    // Optionally displays one of the intermediate buffers used
    // by the bloom postprocess, so you can see exactly what is
    // being drawn into each rendertarget.
    public enum IntermediateBuffer
    {
        PreBloom,
        BlurredHorizontally,
        BlurredBothWays,
        FinalResult,
    }

    public IntermediateBuffer ShowBuffer
    {
        get { return showBuffer; }
        set { showBuffer = value; }
    }

    IntermediateBuffer showBuffer = IntermediateBuffer.FinalResult;

    #endregion

    #region Initialization

    public BloomComponent(Game1 game)
        : base(game)
    {
        if (game == null)
            throw new ArgumentNullException("game");
    }

    /// <summary>
    /// Load your graphics content.
    /// </summary>
    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        bloomExtractEffect = Game.Content.Load<Effect>("Effects\\BloomExtract");
        bloomCombineEffect = Game.Content.Load<Effect>("Effects\\BloomCombine");
        gaussianBlurEffect = Game.Content.Load<Effect>("Effects\\GaussianBlur");

        // Create a texture for rendering the main scene, prior to applying bloom.
        sceneRenderTarget = new RenderTarget2D(GraphicsDevice, 1280, 720, false, SurfaceFormat.Color, DepthFormat.None); // init render target for full viewport size;

        // Can create two rendertargets for the bloom processing. These are half the
        // size of the backbuffer, in order to minimize fillrate costs. Reducing
        // the resolution in this way doesn't hurt quality, because we are going
        // to be blurring the bloom images in any case.

        renderTarget1 = new RenderTarget2D(GraphicsDevice, 1280, 720, false, SurfaceFormat.Color, DepthFormat.None); // init render target for full viewport size;
        renderTarget2 = new RenderTarget2D(GraphicsDevice, 1280, 720, false, SurfaceFormat.Color, DepthFormat.None); // init render target for full viewport size;
    }

    /// <summary>
    /// Unload your graphics content.
    /// </summary>
    protected override void UnloadContent()
    {
        sceneRenderTarget.Dispose();
        renderTarget1.Dispose();
        renderTarget2.Dispose();
    }

    #endregion

    #region Draw

    /// <summary>
    /// This should be called at the very start of the scene rendering. The bloom
    /// component uses it to redirect drawing into its custom rendertarget, so it
    /// can capture the scene image in preparation for applying the bloom filter.
    /// </summary>
    public void BeginDraw()
    {
        if (Visible)
        {
            GraphicsDevice.SetRenderTarget(sceneRenderTarget);
        }
    }

    /// <summary>
    /// This is where it all happens. Grabs a scene that has already been rendered,
    /// and uses postprocess magic to add a glowing bloom effect over the top of it.
    /// </summary>
    public void DrawBloomedScreen()
    {
        GraphicsDevice.SamplerStates[1] = SamplerState.LinearClamp;

        // Pass 1: draw the scene into rendertarget 1, using a
        // shader that extracts only the brightest parts of the image.
        bloomExtractEffect.Parameters["BloomThreshold"].SetValue(
            Settings.BloomThreshold);

        DrawFullscreenQuad(sceneRenderTarget, renderTarget1,
                           bloomExtractEffect,
                           IntermediateBuffer.PreBloom);

        // Pass 2: draw from rendertarget 1 into rendertarget 2,
        // using a shader to apply a horizontal gaussian blur filter.
        SetBlurEffectParameters(1.0f / (float)renderTarget1.Width, 0);

        DrawFullscreenQuad(renderTarget1, renderTarget2,
                           gaussianBlurEffect,
                           IntermediateBuffer.BlurredHorizontally);

        // Pass 3: draw from rendertarget 2 back into rendertarget 1,
        // using a shader to apply a vertical gaussian blur filter.
        SetBlurEffectParameters(0, 1.0f / (float)renderTarget1.Height);

        DrawFullscreenQuad(renderTarget2, renderTarget1,
                           gaussianBlurEffect,
                           IntermediateBuffer.BlurredBothWays);

        // Pass 4: draw both rendertarget 1 and the original scene
        // image back into the main backbuffer, using a shader that
        // combines them to produce the final bloomed result.
        GraphicsDevice.SetRenderTarget(null);

        EffectParameterCollection parameters = bloomCombineEffect.Parameters;

        parameters["BloomIntensity"].SetValue(Settings.BloomIntensity);
        parameters["BaseIntensity"].SetValue(Settings.BaseIntensity);
        parameters["BloomSaturation"].SetValue(Settings.BloomSaturation);
        parameters["BaseSaturation"].SetValue(Settings.BaseSaturation);

        GraphicsDevice.Textures[11] = sceneRenderTarget;

        Viewport viewport = GraphicsDevice.Viewport;

        DrawFullscreenQuad(renderTarget1,
                           viewport.Width, viewport.Height,
                           bloomCombineEffect,
                           IntermediateBuffer.FinalResult);
    }

    /// <summary>
    /// Helper for drawing a texture into a rendertarget, using
    /// a custom shader to apply postprocessing effects.
    /// </summary>
    void DrawFullscreenQuad(Texture2D texture, RenderTarget2D renderTarget,
                            Effect effect, IntermediateBuffer currentBuffer)
    {
        GraphicsDevice.SetRenderTarget(renderTarget);

        DrawFullscreenQuad(texture,
                           renderTarget.Width, renderTarget.Height,
                           effect, currentBuffer);
    }

    /// <summary>
    /// Helper for drawing a texture into the current rendertarget,
    /// using a custom shader to apply postprocessing effects.
    /// </summary>
    void DrawFullscreenQuad(Texture2D texture, int width, int height,
                            Effect effect, IntermediateBuffer currentBuffer)
    {
        // If the user has selected one of the show intermediate buffer options,
        // we still draw the quad to make sure the image will end up on the screen,
        // but might need to skip applying the custom pixel shader.
        if (showBuffer < currentBuffer)
        {
            effect = null;
        }

        spriteBatch.Begin(0, BlendState.Opaque, null, null, null, effect);
        spriteBatch.Draw(texture, new Rectangle(0, 0, width, height), Color.White);
        spriteBatch.End();
    }

    /// <summary>
    /// Computes sample weightings and texture coordinate offsets
    /// for one pass of a separable gaussian blur filter.
    /// </summary>
    void SetBlurEffectParameters(float dx, float dy)
    {
        // Look up the sample weight and offset effect parameters.
        EffectParameter weightsParameter, offsetsParameter;

        weightsParameter = gaussianBlurEffect.Parameters["SampleWeights"];
        offsetsParameter = gaussianBlurEffect.Parameters["SampleOffsets"];

        // Look up how many samples our gaussian blur effect supports.
        int sampleCount = weightsParameter.Elements.Count;

        // Create temporary arrays for computing our filter settings.
        float[] sampleWeights = new float[sampleCount];
        Vector2[] sampleOffsets = new Vector2[sampleCount];

        // The first sample always has a zero offset.
        sampleWeights[0] = ComputeGaussian(0);
        sampleOffsets[0] = new Vector2(0);

        // Maintain a sum of all the weighting values.
        float totalWeights = sampleWeights[0];

        // Add pairs of additional sample taps, positioned
        // along a line in both directions from the center.
        for (int i = 0; i < sampleCount / 2; i++)
        {
            // Store weights for the positive and negative taps.
            float weight = ComputeGaussian(i + 1);

            sampleWeights[i * 2 + 1] = weight;
            sampleWeights[i * 2 + 2] = weight;

            totalWeights += weight * 2;

            // To get the maximum amount of blurring from a limited number of
            // pixel shader samples, we take advantage of the bilinear filtering
            // hardware inside the texture fetch unit. If we position our texture
            // coordinates exactly halfway between two texels, the filtering unit
            // will average them for us, giving two samples for the price of one.
            // This allows us to step in units of two texels per sample, rather
            // than just one at a time. The 1.5 offset kicks things off by
            // positioning us nicely in between two texels.
            float sampleOffset = i * 2 + 1.5f;

            Vector2 delta = new Vector2(dx, dy) * sampleOffset;

            // Store texture coordinate offsets for the positive and negative taps.
            sampleOffsets[i * 2 + 1] = delta;
            sampleOffsets[i * 2 + 2] = -delta;
        }

        // Normalize the list of sample weightings, so they will always sum to one.
        for (int i = 0; i < sampleWeights.Length; i++)
        {
            sampleWeights[i] /= totalWeights;
        }

        // Tell the effect about our new filter settings.
        weightsParameter.SetValue(sampleWeights);
        offsetsParameter.SetValue(sampleOffsets);
    }

    /// <summary>
    /// Evaluates a single point on the gaussian falloff curve.
    /// Used for setting up the blur filter weightings.
    /// </summary>
    float ComputeGaussian(float n)
    {
        float theta = Settings.BlurAmount;

        return (float)((1.0 / Math.Sqrt(2 * Math.PI * theta)) *
                       Math.Exp(-(n * n) / (2 * theta * theta)));
    }

    #endregion
}

```

}

The only other thing I can think of is that the Bloom shaders are somehow disgarding the alpha values, thus leaving me with an opaque screen. Here's the shaders in case that's the case and I'm not seeing it:

BloomExtract, which is the first step

```
 // Pixel shader extracts the brighter areas of an image.
 // This is the first step in applying a bloom postprocess.

 sampler TextureSampler : register(s0);

 float BloomThreshold;

float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
{
     // Look up the original image color.
     float4 c = tex2D(TextureSampler, texCoord);

     // Adjust it to keep only values brighter than the specified threshold.
     return saturate((c - BloomThreshold) / (1 - BloomThreshold));
}

technique BloomExtract
{
     pass Pass1
     {
         PixelShader = compile ps_2_0 PixelShaderFunction();
     }
}

```

Then, I apply Gaussian Blur twice, once horizontally, then once vertically. I don't think it's the blur, so I'll leave that shader out for right now.

Then, BloomCombine, which is the final step

```
 // Pixel shader combines the bloom image with the original
 // scene, using tweakable intensity levels and saturation.
 // This is the final step in applying a bloom postprocess.

 sampler BloomSampler : register(s0);
 sampler BaseSampler : register(s11);

 float BloomIntensity;
 float BaseIntensity;

 float BloomSaturation;
 float BaseSaturation;

 // Helper for modifying the saturation of a color.
 float4 AdjustSaturation(float4 color, float saturation)
 {
     // The constants 0.3, 0.59, and 0.11 are chosen because the
     // human eye is more sensitive to green light, and less to blue.
     float grey = dot(color, float3(0.3, 0.59, 0.11));

     return lerp(grey, color, saturation);
 }

 float4 PixelShaderFunction(float2 texCoord : TEXCOORD0) : COLOR0
 {
      // Look up the bloom and original base image colors.
     float4 bloom = tex2D(BloomSampler, texCoord);
     float4 base = tex2D(BaseSampler, texCoord);

     // Adjust color saturation and intensity.
     bloom = AdjustSaturation(bloom, BloomSaturation) * BloomIntensity;
     base = AdjustSaturation(base, BaseSaturation) * BaseIntensity;

     // Darken down the base image in areas where there is a lot of bloom,
     // to prevent things looking excessively burned-out.
     base *= (1 - saturate(bloom));

     // Combine the two images.
     return base + bloom;
 }

 technique BloomCombine
 {
    pass Pass1
    {
         PixelShader = compile ps_2_0 PixelShaderFunction();
    }
 }

```

I've tried everything possible that I could think of, so I'm looking for some advice. Chances are that anything you suggest, I won't know how to do, so brownie points for clear and concise descriptions so I can try to implement it quickly to determine if you were correct.

Thanks in advance for any help rendered! (Pun intended)

# Answer
> 7 votes
I've managed to get it working with a few minor changes to the sample. Here's the steps I took, but let me know if you need additional help.

---

**On the BloomComponent Class**

1. Add a new private `RenderTarget2D` instance to the `BloomComponent` class. I called it `finalRenderTarget` (Line 29).
2. Add a public getter `FinalRenderTarget` so that you can retrieve it from outside. (Line 35)
3. Initialize `finalRenderTarget` in the `LoadContent()` method, exactly like the existing `sceneRenderTarget`. (Line 106)
4. On the final `device.SetRenderTarget()` call in the `DrawBloomedScreen()` method, change `null` to `finalRenderTarget` so that the bloomed image is stored in the new render target instead of being rendered to the backbuffer. (Line 188)
5. At the *very end* of the `DrawBloomedScreen()` method add a `device.SetRenderTarget(null)` to pass control back to the backbuffer. (Line 206)
6. (Optional) Rename `DrawBloomedScreen()` to `EndDraw()`. I think it makes the code more symetric as you'll see below. :-) (Line 156)

**Link:** Here's what my BloomComponent class looked like after these changes.

---

**On your Drawing Code**

Then on your side of the code draw things in this order:

```
// Step 1 - Render UI with bloom and store it in bloom's internal rendertarget
bloom.BeginDraw();
device.Clear(Color.Transparent);
DrawUi();
bloom.EndDraw();

// Step 2 - Draw your scene
device.Clear(Color.Black);
DrawScene();

// Step 3 - Draw bloomed UI on top of everything by drawing FinalRenderTarget with a spritebatch
spriteBatch.Begin();
spriteBatch.Draw(bloom.FinalRenderTarget, new Rectangle(0, 0, viewport.Width, viewport.Height), Color.White);
spriteBatch.End();

```

**Link:** Here's what the Game.Draw method of my sample looked liked.

---

**Results**

And this is what I got:

*PS: There are other ways (and better) to add an outer glow to your text.*

---
Tags: xna, hlsl, bloom
---


# Question
Title: How can I connect 2D skeletal animation to the physics engine?
I'd like to use skeletal animations in my 2D game, and since I already use Box2D as the physics engine, I'd like to enable (but not enforce) ragdoll animations as well. I need some help in figuring out how the Animation and Physics entity components relate to each other.

***How should data be represented on disk?*** Should the actual model/ skeleton be different from the animation? Here's what I currently have in mind: each texture has a corresponding Box2D body (`forearm.jpg` and `forearm.body`, for example). I also have a separate `hero.model` file that references the `*.body` files, and several `*.anim` files that reference the model and the textures.

The reason I don't think I should reference the textures in the model directly, but reference them in the animation, is so I can have the character blink (for example): its head would be one body, but different sprites can be pasted over it at different keyframes as to make it blink.

***Should I actually move the limbs while animating?*** While the character is still alive (and ragdoll should be off), what should I do with the physical limbs? When I animate, should I just render the sprites with the correct transform, or should I actually move the physical limbs to their current position according to the animation? If yes, how can I get over the fact that Box2D doesn't handle moving bodies directly too well?

***How to enable more complex communication?*** Architecturally speaking, how should I implement communication between the Animation and Physics components so that interaction is kept to a minimum, but to also be able to do create more complex entities, like for example a wheel on a robot being rendered with the rotation of the physical wheel, while the rest of the robot is rendered according to the animation's keyframes.

# Answer
You should do as Maik said.

Often it happens that skeletal animation is quite decoupled by the skeletal it moves: you may find that the limbs of a qadrupede move rougly in the same way if it paces, be it a dog or an horse. This means that you may find it useful to move the skeletal animation responsibility to an external entity by connecting the "animator" with the "puppet" when needed.

This strategy let you to "recycle" animator instances (insofar as possible), combine them to be behavioural (say inverse\_leg\_walk + atrophied\_arms\_walk for a TRex vs leg\_walk + arms\_walk for a man) and so forth.

As you can seamlessly switch between walk and run or jump, you may switch to ragdoll animation and detach your animator when the ragdoll stops (if you are looking to free resources as fast as possible)
> 1 votes

---
Tags: physics, animation, box2d, skeletal-animation
---


# Question
Title: Functional reactive programming (FRP) in games. Some doubts and thoughts
These days, I'm doing some research on component-based entity systems. I had a first approximation, using a blackboard pattern at the entity level, and with components sharing this blackboard to do communication.

Doing this research, I found an entity framework called Artemis, that follows a FRP structure for the entity management. The idea seems pretty good, and I'm thinking of integrating in to my engine. I have some questions that need to be solved to fully understand this "odd" architecture:

1. In my first approximation, the way components shared data is pretty straight forward, following the blackboard pattern. How should this be done, following FRP? It seems each system would be the ones holding all dependencies to the components, making components totally decoupled. If the collision system needs to know about physic component, movable system, etc; the collision system would import all of these components, and do all needed work with them. Is that right?
2. Would each system be a homogeneous or heterogeneous component container? I guess its system has to be homogeneous, related to the component type it holds, because the system needs to know the component data, to play with it during updates. This leads me to next question:
3. Does this architecture lead to too many system/components?
4. How does an event system fit in to this structure? I usually have slot/signals in game objects, for this, but it seems there is no "Entity" concept with the Artemis structure.

# Answer
> 4 votes
Not an expert, but doing something fairly similar; my thoughts:

1) In general, each system will scan the components (of all entities) that are of a type in which it is interested for some condition that it can handle. A “Gravity” system might ignore “position” components that have a “flying” flag, for example. One way of handling the component data locking and preserving immutable data (although I haven't looked into Artemis) is to remove the “previous” state from the set, pass it into the system, and have that system return the “new” immutable state.

2) I believe the answer is “homogenous,” although I'm unclear as to how you mean it. Each component (e.g. “position” or “affinity to spontaneously combust”) is a “record;” every component of a given type has the same fields; but every type of component has distinct (and non-duplicated) fields.

3) Entity systems are designed around that idea. The “ideal” system would have one system for every type of interaction in the game. In real life, sometimes things that are closely related are ganged together for efficiency.

4) Events can be replaced by state changes in the components. Entity systems, of course, don't lend themselves to having “objects” in the OOP sense; but where an “entity” is a “game object,” an “event” could be:

* attaching a new component to the entity (making it susceptible to effects from other systems)
* changing the state of that component (thus, systems listening for that state change would be triggered)

The “blackboard system” dispatcher would them be responsible for observing new records being inserted and triggering the systems that might want/need to handle those records in their new state, subject to (perhaps) timer-based rate limits or other effects.

# Answer
> 4 votes
I worked with both "componentbased game-objects" and "functional reactive programming". As you've used "functional programming" in the title already, I will give an answer from an functional programming perspective, but still keep in mind your componentbased perspective.

> Doing this research I found an entity framework called Artemis, that follows a FRP structure for the entity managment.

This doesn't make any sense. Please look up the definition of FRP! FRP is a concept on how to handle calculations and depdencies between data in reaction to an external event. I took a quick look at Artemis and I think it's called a componentbased game-object architecture.

> The idea seems pretty good and I'm thinking of integrating in my engine.

Please consider extending an existing engine.

**@1**

> shared data is pretty straight forward following the blackboard pattern

Believe me, you don't want to share data. You're creating something similar to a global variable, and we all learned that we shouldn't use them, didn't we? Mathematically speaking you're breaking functional dependency and you will get in a lot trouble with interdependencies and in the long run your brain will explode.

> How should this be done following FRP?

You differ between intra-object communication (via reactive values. think signal/slots) and inter-object communication (via messages).

> I mean, if the collision system needs to know about physic component, movable system, etc... The collision system would import all this components and do all needed work with them. Is this right?

The collision system handles functionality concerning more than one game object, thus it must be separate from an independent actor and only communicate via messages. The collision system doesn't need to know anything except the position and physical extension of the object.

**@2** see BRPocock's answer. But yet again, the system shouldn't know anything about a components data.

**@3**

> Doesn't this architecture leads to have too many system/components?

Correct. Object-oriented programming at it's best ;)

**@4**

> How does an event system fit in this structure? I ussually have slot/signals in game objects for this but it seems with artemis structure there's no "Entity" concept.

Aren't there any identites of some kind? If not, than I assume there's an "implicit protocol" based on component types. Have fun then!

---
Tags: entity-system
---


title: UX guidance for mobile games

text:
# Question
Title: UX guidance for mobile games
I m in need of some UX guidance if there is any for a game in mobile.

for example for pausing the game (assume I m not using iOS) say you want to pause the game and you dont want to loose part of the screen on having a button that will pause. I was thinking of using some sort of gesture ( double tap?, slide up?) is there any default standard?

Cheers

# Answer
> 3 votes
I've seen several usability guideline documents for mobile devices before, but unfortunately not for games specifically, which are a different beast entirely.

For your example, I guess that would have to vary from game to game. If for instance your game used double tapping or sliding as part of the gameplay mechanics, then obviously you would no longer be able to use that motion for pausing, so a standard wouldn't do you much good.

I've just checked a dozen of games on my library, and most of them display a little pause button (or just the symbol) on one of the corners of the screen to bring up the menu, so if anything, I'd call that the "default standard".

**Bottom Line**

*My advice is simple - play a bunch of games on your target platform and see how they are usually done. Assume the majority as being the standard and see if that implementation would also fit your game. If it doesn't, just find your own alternative! And don't be afraid to think outside the box, if it works well.*

For instance, I used to see lots of action/RPG games with d-pads drawn on the screen and thought that was the obvious solution... Then I played Final Fantasy III on the iOS and there's no d-pad drawn anywhere! You simply hold your finger down anywhere on the screen and as soon as you move it a little, that place becomes your d-pad (and a little d-pad graphic appears beneath your finger). This means I can play holding my device in any way I like and with either hand. And to perform actions such as talking with NPCs, a single tap anywhere does the trick. I found this pretty amazing, that you're able to completely control an RPG of moderate complexity, with a single thumb.

---
Tags: mobile, ui-design
---


# Question
Title: Maya 2012: Is it possible to convert a single polygon to solid object?
Is it possible to somehow extrude a single polygon into creating a solid object (ex: converting square polygon to cube)?

# Answer
> 4 votes
1) select polygon 2) Edit Mesh-\>Extrude

---
Tags: models, maya
---


# Question
Title: How to implement a symmetric 3d field of view algorithm for a roguelike
I've been thinking about adding 3d support in my roguelike. It would still be top-down like other roguelikes, yet it would have layers, such that things like platforms, tunnels, and bridges, etc, could be added to levels. Whether I do this hinges on whether I can get the fov routine I'm using working with the layers.

Note that I don't care that it doesn't make sense to some of you that I'm trying to have a 3d field of view routine for a 2d roguelike. The roguelike does have a 3d space, and I want to determine what the player can see, even if what the player can see can't logically be displayed. Let me worry about how to handle that problem.

I would be grateful for some advice in how to approach this problem. Perhaps this is utterly crazy, and I should just make a 2d roguelike...

**Update**:

I erroneously stated before that the problem with Bresenham's line algorithm was with artefacts. I should have mentioned that I needed the fov routine to be symmetric. Such a requirement can't be met by Bressenham's line algorithm.

# Answer
Real time strategy games routinely deal with this problem (take, for example, Starcraft 1 which was pseudo-3D) - maybe you could find some literature on how they managed it.

What I would do is probably pre-calculate some form of a 'visibility mesh' (akin to a navigation mesh). Each region of the mesh would link to regions that are visible to it. You should be able to lift a lot of logic from light-map generators (or possibly find a light-map library). Ideally you would place a large amount of lights in 'walkable' areas and calculate the light map for each, following this you would resolve similar areas into a single mesh.

This would probably result in a large amount of regions near corners - but corridors should be nice and clean.

To determine if two entities can see each other merely check if the meshes that contain them are connected; and that they are within field of view range.
> 3 votes

# Answer
Modifing a FOV algorithm to work in a 3D isn't terribly difficult, you need to have the algorithm take into account all possible directions in a sphere instead of just a circle.

Are you using a symmetric FOV algorithm now? If not, you should switch to one first, then make the modifications. If you put up the code/more information about the algorithm you are using now, we would be able to help you more.
> 3 votes

# Answer
Make the algorithm symmetric, just implement a way of making sure that two points are always fed to the algorithm in the same order, no matter which is the viewer and which is the viewee. This is for instance easily done by giving all points an id and sorting by that.
> 1 votes

---
Tags: c++, roguelikes
---


# Question
Title: Delay The Polling Events Of Xbox360 Gamepad With XInput
My team and I are currently developing a 2D platformer with SDL/OpenGL and we want to add support to the Xbox360 Gamepad with the XInput library from Microsoft, but we are currently having a problem.

First of all, the method for reading the key states it's this one:

```
bool InputMapping::Gamepad::checkKeyState(WORD button)
{
  DWORD dwResult;
  DWORD idPlayer = playerID - 1;

  XINPUT_STATE state;
  ZeroMemory( &state, sizeof(XINPUT_STATE) );

  dwResult = XInputGetState( idPlayer, &state );

  if ( state.Gamepad.wButtons & button)
  {
    return true;
  }

  return false;
}

```

This method returns true or false if the selected key it's pressed or not.

But it seems that the polling of the keys it's ocurring really fast, in the menus, moving through the buttons it's really fast and I can't controlled.

There is a way to limit the time between polling inside of the XInput or I should do it by myself? or what you recommend me?

If I didn't explain me clearly don't hesitate in say that.

Thanks a lot.

# Answer
There is a good reason why polling of controls is fast. Finally it is the only way the user can take action in your game. ;-)

Ok, now the (hopefully) non obvious part: You could either require the user to press and release the button to navigate in the menus. For that you would store a boolean flag if button is pressed and fire your "clicked" event after button is released again.

Same thing could be done by storing game/system time and firing clicked event every x ms.

In both cases I would recommend using this method only in menus and not for controlling the actual game character since that would result in serious lagging.
> 3 votes

---
Tags: c++, input
---


title: Depth Buffer not working in XNA?

text:
# Question
Title: Depth Buffer not working in XNA?
I'm stumped. I have been fighting this for about 2 hours now.

Here are the interesting parts of my code:

```
protected override void Update(GameTime gameTime)
{
    // Allows the game to exit
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        this.Exit();

    var time = gameTime.TotalGameTime.TotalSeconds;
    this.position = new Vector3(
        2.0f * (float)Math.Sin(time),
        2.0f * (float)Math.Cos(time),
        2.0f * (float)Math.Cos(time / 4));

    effect.World = Matrix.Identity;
    effect.View = Matrix.CreateLookAt(this.position, Vector3.Zero, Up);
    effect.Projection = Matrix.CreatePerspectiveFieldOfView(1.5708f, (float)this.Window.ClientBounds.Width / this.Window.ClientBounds.Height, float.Epsilon, 500.0f);

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{
    var count = this.SetUpVertices() / 3;

    this.GraphicsDevice.Clear(ClearOptions.DepthBuffer | ClearOptions.Target, Color.CornflowerBlue, 1.0f, 0);

    this.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
    this.GraphicsDevice.BlendState = BlendState.Opaque;
    this.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

    foreach (var pass in this.effect.CurrentTechnique.Passes)
    {
        pass.Apply();
        this.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, count, VertexPositionTexture.VertexDeclaration);
    }

    base.Draw(gameTime);
}

```

# Answer
You should always make the near plane value as far as you can. I use 0.1f personally because nothing much gets close to my camera but the further from zero the better.

Here's why.

Same with the far; in general make it as near as you can.

As the article states, don't try to "cover all ground" by going from 0.00000001 to 1000000000. Instead try to analyze your needs and split your scene into "near", "middle", and "far" (or whatever) with different matrices to correspond.
> 5 votes

# Answer
Consarnit!

*sigh*... I fixed it.

```
Matrix.CreatePerspectiveFieldOfView(
    1.5708f,
    (float)this.Window.ClientBounds.Width / this.Window.ClientBounds.Height,
    float.Epsilon,  // <-- HERE IS THE PROBLEM! RIGHT HERE!!!1one!1
    500.0f);

```

Apparently, you cannot use `float.Epsilon` as the near plane, for some reason...

Commenters: What would be a sane value then?
> 0 votes

# Answer
I can't comment yet, but from my experience, `0` or `0.01f` both work just fine for the near clipping plane.
> 0 votes

---
Tags: xna-4.0, depth-buffer
---


# Question
Title: Efficient Tile-based collision detection for a lot of squares?
currently I am working on my own take of a tile-based game (think Terraria, but less fantastical (I think that's a word? Sorry if it isn't)).

Anyway, I currently have collision detection working (for corner cases even!) which was a big step for me. There is something extremely gratifying about seeing a sprite not run through a block. But then I had the idea to benchmark. Bad idea.

1,000 squares, no problem. 10,000 squares, for 3 characters was kind of laggy. 100,000 squares (really huge map), for 3 characters was unplayable.

I'm having the issue where I don't want to even consider the blocks that are too far from the player, characters, items, etc., but I don't want to load those in-out of memory constantly.

Here's my algorithm so far, feel free to criticize.

```
foreach (Block in level)
{
    if (distance from block to player > a specified amount)
        ignore this block;
    else
    {
        get the intersection depth between the two bounding boxes
        if (depth of intersection != Zero-vector)
        {
            check y size vs x size
            resolve on smallest axis
        }
    }
}

```

As you will note, when the level size get's bigger, the Order of this algorithm grows by N blocks. I would like to not even consider blocks that aren't even near the player.

I'm thinking maybe use a (0,0) to (mapWidth,mapHeight) double-array of blocks instead of a list, calculating a danger-zone depending on the person's position e.g., if player's position is at (10, 20) it will look from (0, 10) to (20, 30), or so on.

Any thoughts and considerations are awesome, thank you.

# Answer
Yes, you're thinking correctly. You should be using a 2D array of tiles since that allows you to index tiles by position.

```
Block[,] level = new Block[width, height];

```

And since the player can only collide with its surrounding tiles, the number of collision checks you need to do is very small. This of course depends on the size of the player. The Platformer sample does it like this:

```
int leftTile = (int)Math.Floor((float)characterBounds.Left / tileWidth);
int rightTile = (int)Math.Ceiling(((float)characterBounds.Right / tileWidth)) - 1;
int topTile = (int)Math.Floor((float)characterBounds.Top / tileHeight);
int bottomTile = (int)Math.Ceiling(((float)characterBounds.Bottom / tileHeight)) - 1;

for (int y = topTile; y <= bottomTile; ++y)
{
    for (int x = leftTile; x <= rightTile; ++x)
    {
        // Handle collisions with the tile level[x,y] just like you were doing!
    }
}

```

Check the sample if you still have any problems.
> 6 votes

# Answer
When dealing with a large number of collisions, you usually want to adopt a more advanced structure, such as a Quadtree or Hashmap to check for those collisions.

Since tiles are static I would suggest using a Quadtree. A quad tree is made up of quads. Each quad is made up of four rectangles and each of those rectangles are quads. This continues recursively up to a specified size. Each quad can contain a list of tiles which inhabit that area of the screen. That way, when you're checking for collisions you can

1. Restrict the checks to those in the immediate vicinity
2. Restrict checks to only objects which are moving

Now if you don't want to even look at tiles off screen then you could do something like

```
public bool CheckCollision(myPosition) {
    if(quadNodes.Count > 0) {
        // This is not a leaf, keep checking
        foreach(Quad node in quadNodes) {
            if(node.Position is insideViewport && nearPlayer)
                // Continue recursion
            }
        }
    }
    else {
        // This is a leaf, do checks
        foreach(Tile tile in tileList) {
            if(collision)
                return true;
        }
        return false;
    }
}

```
> 2 votes

# Answer
I guess my answer would be your answer! ;-)

If you have player position (and size) you can calculate indices of surrounding tiles (which are the only ones to be checked in detail). This way it should be irrelevant how big your map is, it just depends on the actual size of your player thus resulting in more potential tiles to check.

Maybe check the tutorial on collisions over at riemers.net if you have not already.
> 1 votes

---
Tags: xna, c#, collision-detection, algorithm, bounding-boxes
---


title: How do I play audio with Javascript?

text:
# Question
Title: How do I play audio with Javascript?
I want to add a short audio track to a game of concentration I'm coding. I want the sound to occur when the user has won the game. How do I go about doing this? I would really appreciate the help, thank you.

# Answer
If you're using something like canvas and you're already depending on the browser supporting HTML5, you can use the `audio` element.

```
var win = new Audio('srcfile.wav');
if(playerWon === true){
    win.play();
}

```
> 5 votes

# Answer
Audio in HTML5 is a minefield at the moment, with patchy format support.

We wrote a few blog posts about audio support in HTML5. This chart shows browser support: http://www.scirra.com/blog/44/on-html5-audio-formats-aac-and-ogg#chart

Surprisingly, IE doesn't support playback of WAVs. You should pick audio 2 formats to get coverage on all the platforms.

**Beware using MP3's in games**

It will cost you $2,500 per title in licensing fees if it has more than 5,000 distributions. http://www.scirra.com/blog/64/why-you-shouldnt-use-mp3-in-your-html5-games

We think the best combination to use is AAC/Ogg to cover all browsers.
> 5 votes

# Answer
I found an article describing this library which should fit your needs.

If you don't have sound files yet and want to create them with some fx library then you might want to look at jsfx which I used in my last game typdown (specially these two files are interesting (don't mind the coffeescript, it all compiles to javascript): sounds and game controller
> 3 votes

# Answer
The Web Audio API is perfect for playing audio in javascript, but currently only Chrome supports it.
> 0 votes

---
Tags: javascript
---


title: How to debug a 2D arcade game easily?

text:
# Question
Title: How to debug a 2D arcade game easily?
I am trying to learn pygame. In order to do that, I have downloaded one of their examples :

http://rpg-world.googlecode.com/files/rpg-world-src-0.93.tar.gz

And started to run it in debug mode.

However, I have discovered quite quickly that unlike a classic program, it is hard to debug a computer game, because of the fact that it is hard to control the player by sending keyboard press events.

Any suggestions?

# Answer
A couple of things that I do when debugging games:

1. Use a console to output relevant information.
2. Output debug data directly on top of your game screen.

Since you are dealing with a game loop, breakpoints are sometimes quite difficult to use when debugging such things as character movement. Displaying the data you want to verify on screen while you are moving your character is a great way to visually see what is happening behind the scenes.
> 4 votes

---
Tags: pygame, debugging
---


# Question
Title: Best Game Engine/Framework and Language for 2D actor/sprite intensive game
I'm new to the game dev world.

I have a rather large project in mind (I learn by setting myself challenges :P ) and I'm wondering what the best engine/framework/language is for a 2D game with thousands of sprites/actors on screen at a time. Bare metal type stuff. I need to still be able to zoom in and out with that many actors at once.

This game will have no 3D elements.

Any thoughts?

Suggestions?

# Answer
> 9 votes
**C# with XNA**

Since you're new to this, XNA would have the advantage of also being a *very good* place to get started. From creating a new project to displaying a 2D sprite on screen it takes 5 lines of code:

```
private Texture2D texture;

texture = Content.Load<Texture2D>("sprite");

spriteBatch.Begin();
spriteBatch.Draw(texture, Vector2.Zero, Color.White);
spriteBatch.End();

```

It doesn't get much easier than this. Also has the advantage of having loads of educational samples available for it.

The problem is your performance requirement. But I've managed to draw thousands of sprites before in XNA with no problem. However there was no gameplay code behind it, and my computer is high-end so results would be biased. But with careful optimization it would probably work out. So this is my recommendation.

**C# with SharpDX or SlimDX**

Still staying in the managed C# realm, you could also go back one step and consider using SharpDX which is a new managed wrapper around DirectX, and they claim it to be about around 6 times faster than XNA. That should have enough power for your needs. And it's cross-platform.

There's also SlimDX to consider.

**C++ with DirectX/OpenGL**

And if you keep going further in that direction, you'll finally reach the pure C++ with DirectX/OpenGL realm. If you decide to go down that route (which by the way, will be much harder to deal with at this stage), there's a few things you can do to make your life easier.

For instance, you could use SDL to create the window for you and take care of input, and FMOD to handle the audio, both of which I have found much easier to work with than their native counterparts.

I also don't know what it's like nowadays, but the last time I worked with these, I found it was pretty easy to do 2D stuff in DirectX thanks to the D3DXSprite class which IIRC was quite similar to XNA's SpriteBatch, while with OpenGL I had to implement everything from scratch (i.e. messing around with textured quads, orthographic projections and implementing the batching).

# Answer
> 8 votes
I recommand SFML, as it allows you to easily manage 2D sprites and zoom/unzoom (thanks to an existing "camera" class). With these abstractions, I've found it simpler to use than XNA. I don't have hard stats on the performance, but since it uses C++ and renders through OpenGL, I think it can be faster than XNA.

Coincidentally, I'm working on a similar game using SFML. It can manage 1000+ moving sprites at 50 FPS on my laptop, while running the game logic (collision between sprites, etc).

Here is a screenshot of this SFML program running on my 3-year-old laptop with integrated graphics, at 25 FPS (800x600):

I think there are more than 1000 sprites displayed.

---
Tags: 2d
---


# Question
Title: Cocos2d CCSpriteFrameCache: couldn't load texture file
I am currently doing this Cocos2d tutorial: http://www.raywenderlich.com/1271/how-to-use-animations-and-sprite-sheets-in-cocos2d

...and get the following error messages:

```
2011-12-30 16:36:28.536 AnimBear[11273:10a03] cocos2d: CCTexture2D. Can't create Texture. UIImage is nil
2011-12-30 16:36:28.537 AnimBear[11273:10a03] cocos2d: Couldn't add image:AnimBear_default.png.ccz in CCTextureCache
2011-12-30 16:36:28.537 AnimBear[11273:10a03] cocos2d: CCSpriteFrameCache: couldn't load texture file. File not found: AnimBear_default.png.ccz
2011-12-30 16:36:28.538 AnimBear[11273:10a03] cocos2d: CCTexture2D. Can't create Texture. UIImage is nil
2011-12-30 16:36:28.538 AnimBear[11273:10a03] cocos2d: Couldn't add image:AnimBear_default.png.ccz in CCTextureCache
2011-12-30 16:36:28.539 AnimBear[11273:10a03] cocos2d: CCSpriteFrameCache: couldn't load texture file. File not found: AnimBear_default.png.ccz
2011-12-30 16:36:28.540 AnimBear[11273:10a03] cocos2d: CCTexture2D. Can't create Texture. UIImage is nil
2011-12-30 16:36:28.540 AnimBear[11273:10a03] cocos2d: Couldn't add image:AnimBear_default.png.ccz in CCTextureCache
2011-12-30 16:36:28.541 AnimBear[11273:10a03] cocos2d: CCSpriteFrameCa[Switching to process 11273 thread 0x1410b]
[Switching to process 11273 thread 0x10a03]
che: Frame 'bear1.png' not found
2011-12-30 16:36:28.598 AnimBear[11273:10a03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
*** First throw call stack:
(0x17e4052 0x1975d0a 0x17d136e 0x17d2220 0xc1997 0x3fcf1 0xc16dd 0xc0d7c 0x828b0e 0x8298a6 0x838743 0x8391f8 0x82caa9 0x2798fa9 0x17b81c5 0x171d022 0x171b90a 0x171adb4 0x171accb 0x8292a7 0x82aa9b 0xc085f 0x2135)
terminate called throwing an exceptionsharedlibrary apply-load-rules all

```

I have the following files in the Resource folder:

* AnimBear\_default.png.ccz
* AnimBear\_default.plist

The texture consists of eight(8) bears named Bear1.png - Bear8.png. I have bought and done the texture in Zwoptex, latest version.

The code looks like:

```
-(id) init {

if((self = [super init])) {

    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"AnimBear_default.plist" textureFile:@"AnimBear_default.png.ccz"];
    CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"AnimBear_default.png.ccz"];
    [self addChild:spriteSheet];

    NSMutableArray *walkAnimFrames = [NSMutableArray array];
    for (int i = 1; i <= 8 ; ++i) {
        [walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"bear%d.png", i]]];
    }

    CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];

    CGSize winSize = [CCDirector sharedDirector].winSize;
    self.bear = [CCSprite spriteWithSpriteFrameName:@"bear1.png"];
    _bear.position = ccp(winSize.width/2, winSize.height/2);
    self.walkAction = [CCRepeatForever actionWithAction:
                       [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
    [_bear runAction:_walkAction];
    [spriteSheet addChild:_bear];

}
return self;

}

```

I am completely new to Cocos2d and have been trying to search the web and tried different things but with no success :-(

# Answer
Not sure if that's the issue, but you have an error in your init method. You should put all your initialization within the `if((self = [super init])) {` block.

So remove the first two lines from your init block (as they seem to be redudant anyway):

```
-(id) init
{
    if((self = [super init])) {
        [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"AnimBear_default.plist" textureFile:@"AnimBear_default.png.ccz"];
        CCSpriteBatchNode *spriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"AnimBear_default.png.ccz"];
        [self addChild:spriteSheet];

        NSMutableArray *walkAnimFrames = [NSMutableArray array];
        for (int i = 1; i <= 8 ; ++i) {
            [walkAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"bear%d.png", i]]];
        }

        CCAnimation *walkAnim = [CCAnimation animationWithFrames:walkAnimFrames delay:0.1f];

        CGSize winSize = [CCDirector sharedDirector].winSize;
        self.bear = [CCSprite spriteWithSpriteFrameName:@"bear1.png"];
        _bear.position = ccp(winSize.width/2, winSize.height/2);
        self.walkAction = [CCRepeatForever actionWithAction:
                           [CCAnimate actionWithAnimation:walkAnim restoreOriginalFrame:NO]];
        [_bear runAction:_walkAction];
        [spriteSheet addChild:_bear];
    }
    return self;
}

```
> 0 votes

---
Tags: iphone, cocos2d-iphone, objective-c
---


# Question
Title: How to implement cue-stick animation for a pool game?
Hello I am developing a Pool game, and I've been scratching my head about what formula is needed to implement an animation for the cue stick.

The animation of the cue stick should look as if it's being pulled back, as the user starts to change the amount of power that he/she would like to apply to the ball.

# Answer
> 0 votes
In pseudo code, and not very pleasant animation, it could be done like this: I don't really know what you mean by "Animation" I assumed it was the cue moving back depending on the power desired.

```
vector2f starting_position; // Not a local variable, a member variable

mouse_state mouse = get_mouse();

// This checks to see if the right button is down
// it is mutually exclusive with the pulling back of the cue
if (mouse.right_button.state == button_state.DOWN && !cue.pulling_back)
{
    cue.pulling_back = true;
    starting_position = cue.position; // store the initial position of the cue
}

// This will move the cue's position back depending on the
// axis and junk
if (cue.pulling_back)
{
    // figure out the change in y
    // or the respected axis of your choice
    cue.position += mouse.position;
    vector2f change = calculate_change(cue.position, starting_position);
    // power modifed based on change
    cue.power = change * (constants);
}

if (previous_mouse.right_button.state == button_state.DOWN && mouse.right_button.state == button_state.UP
    && cue.pulling_back)
{

    if (starting_position != cue.position)
    {
        // reset the cue position and fire ball using cue's power, etc
    }
cue.pulling_back = false;
}

previous_mouse = mouse;

```

---
Tags: mathematics, animation
---


# Question
Title: Early stages of games development - create 2d animation images for iOS games?
I am in the early stages of developing a game. I don't have an artist or graphics person on board yet. How can I create simple images for animation to work through the early stages of game development? Should I create stick figure images in Photoshop/Pixelmator or are there other ways of using sample artwork or some other tools which can help make images for animation?

# Answer
Any kind of art work that allows you to see what's happening is great. Whatever you need to be able to:

* See that the art is being drawn in the correct place.
* See that the art is not missing any part (cut in half, etc).
* Ensure the art is not inverted.
* Ensure the rotation is correct.

Typically I'll do some kind of colored pattern, with a different color on each edge and text or something in the middle so I can tell if the texture is mirrored.

The colors on each edge allow you to be sure that the rotation is how you want it.

Additionally, if you have textures that are supposed to line up, like for a skybox, I would draw colored lines across the textures where they are supposed to meet, to ensure they are aligned correctly in game.
> 4 votes

---
Tags: animation, tools
---


title: How would I go about using FXAA in XNA?

text:
# Question
Title: How would I go about using FXAA in XNA?
This isn't so much a "give me teh codez" as it is a request for the "right" steps to go through.

I want to implement FXAA in XNA, but I'm a relative newb to the graphics side of game dev, so I'm not sure what the most efficient way to do this would be.

My first hunch is to render the scene into a texture, and then render that texture on a rectangle, with the FXAA code in a pixel shader.

However, I would actually be surprised if there was no more efficient way to do it.

# Answer
> 5 votes
You are almost right about it, but XNA has some built-in features to help you with all of that!

**Render to Texture**

> My first hunch is to render the scene into a texture

Almost. You would start by rendering your scene into a `RenderTarget2D` (which actually inherits from `Texture2D` so it does qualify as rendering to a texture). Something like:

```
PresentationParameters pp = graphicsDevice.PresentationParameters;
RenderTarget2D renderTarget = new RenderTarget2D(graphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);

graphicsDevice.SetRenderTarget(renderTarget);
RenderScene();
graphicsDevice.SetRenderTarget(null);

```

**Apply Shader**

> and then render that texture on a rectangle, with the FXAA code in a pixel shader.

And for this you can just use the `SpriteBatch` class which already creates the quad for you. Load your shader into an `Effect` object and pass it to `SpriteBatch.Begin()`. Also, since the render target *is already* a texture, you can just use it directly! Something like:

```
Effect fxaa = content.Load<Effect>("fxaa");

spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, fxaa);
spriteBatch.Draw(renderTarget, graphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();

```

**Making the Shader Work with SpriteBatch**

As for writing a pixel shader that works with `SpriteBatch`, there's really not much to say (*would be a different story if you were writing a vertex shader though*). Check this sample to get you started. I'll copy one of the examples here:

```
sampler TextureSampler : register(s0);

float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
    // Your pixel shader logic here
}

technique Desaturate
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 main();
    }
}

```

---
Tags: xna, antialiasing
---


# Question
Title: How to create solid human characters in MAYA, so that their hands do not cut into bodies while signaling hand sign?
How to create solid human characters in MAYA, so that their hands do not cut into bodies while signaling hand signs? Or can I make the characters solid in Unity? I create animations in MAYA and import it into Unity for further development.

Thanks for your help!

# Answer
> 3 votes
It is always the responsibility of the animator to not position the character in such a way that their bodies interpenetrate. The software can only do so much for you.

# Answer
> 2 votes
*Solid characters* doesn't mean much, computers aren't that smart yet :).

You likely want to implement collision detection. Each character would have self collision detection and collision detection against other characters. You'd also create procedures to stop body parts from going further when a collision is detected. Unfortunately, this isn't generally something you can just "turn on". It'll take a good amount of work. I won't go into collision detection, since you didn't ask about it.

The easiest solution, as Nicol Bolas said, is to create your animations so that characters don't collide with themselves. Additionally, if you have characters animating next to each other, you'll have to ensure they are positioned to not collide with each other.

Here are a few things you can do to help ensure two animations don't collide:

* Calculate a bounding box for the maximum volume an animation takes place in, make sure characters aren't within each others volumes when they start those animations.
* Create a series of bounding boxes around the limbs and torso that describe the max volume of animations, again, ensure characters aren't in each others boxes. (This method will allow characters to be closer in many situations, but will require more checks.)

# Answer
> 0 votes
There's not much you can do unless you apply some sort of physical constraint model in Maya. I haven't used Maya in a long time, so I can't say exactly how you can do these sorts of physics for rigid objects in Maya.

The best safeguard is to properly rig and animate your characters. Animators and modelers are going to be smarter than computers, so they should be animating them in a way so that their meshes do not intersect from any reasonable angle of view.

If you require some procedural animations, a bounding-box collision system like the one Byte56 explained will help. These boxes can be controlled based on the bone movements of the character's skeleton.

---
Tags: android, unity, animation, maya
---