# Question
Title: Android cocos2d removing a sprite after animation
I have an object going across the screen with an animation using the following code:

```
CCSpriteFrameCache.sharedSpriteFrameCache().addSpriteFrames("ninjastar.plist");
CCSpriteSheet projectileSheet = CCSpriteSheet.spriteSheet("ninjastar.png");
addChild(projectileSheet);
ArrayList<CCSpriteFrame> projectileSprites = new ArrayList<CCSpriteFrame>();

for (int i = 1; i <= 4; i++) {
    projectileSprites.add(CCSpriteFrameCache.spriteFrameByName("ninjastar" + i + ".png"));
}

CCAnimation projectileAnimation = CCAnimation.animation("throw", 0.1f, projectileSprites);
CCSprite projectile = CCSprite.sprite(projectileSprites.get(0));
CCAction projectileAction = CCRepeatForever.action(CCAnimate.action(projectileAnimation, false));
projectile.setPosition(CGPoint.ccp(winSize.width + (projectile.getContentSize().width / 2.0f), actualY));
    actionMove = CCMoveTo.action(actualDuration, CGPoint.ccp(-projectile.getContentSize().width / 2.0f + 320, actualY));
projectileSheet.addChild(projectile);
projectile.setTag(1);
_projectiles.add(projectile);
CCCallFuncN actionMoveDone = CCCallFuncN.action(this, "spriteMoveFinished");
CCSequence actions = CCSequence.actions(actionMove, actionMoveDone);
projectile.runAction(actions);
projectile.runAction(projectileAction);

```

I'm using "spriteMoveFinished" to remove the sprite once it is done going across the screen:

```
public void spriteMoveFinished(Object sender) {
CCSprite sprite = (CCSprite)sender;
_projectiles.remove(sprite);
sprite.stopAllActions();
removeChild(sprite, true);
}

```

However, when the sprite gets to the end of the screen it just stays stuck there on the last frame. How do I remove it completely?

# Answer
The `projectile` is added to `projectileSheet`, but being removed from current layer or scene, rather than removing from `projectileSheet`. The last line of `spriteMoveFinished` should be

```
projectileSheet.removeChild(sprite, true);

```

or better use

```
sprite.removeFromParentAndCleanup(true);

```
> 1 votes

---
Tags: android, animation, sprites, cocos2d, spritesheet
---


# Question
Title: Algorithm for exploring/filling grid map
I'm working on a small game that takes place on a grid map. I'd like to write an AI that is able to explore the grid map by filling as much of its available space as possible.

From any given position there are four possible moves (north, south, east, west), but some of these may be blocked by walls. Also, once I visited a cell I don't want to visit it again. What's more, I want to avoid getting stuck: if moving in one direction means I'm going in a dead end, I'd rather not fill out that part of the grid.

Can you please help me with some pointers as to how I can do this?

# Answer
A flood fill algorithm might be what you are looking for:

http://en.wikipedia.org/wiki/Flood\_fill

This particular algorithm could provide your AI with a "map" of coordinates it would be allowed to travel to. Given the proper instructions, your customized flood fill algorithm would fill based on the rules of your gameboard.

If you are looking for a smarter pathfinding solution, you will be more interested in a A\* algorigthm.

http://en.wikipedia.org/wiki/A\*\_search\_algorithm
> 4 votes

# Answer
You can't "avoid" dead ends. Without looking forward, you'll not know its a dead end... I guess you just don't want your exploring vehicle / person / whatever to stop when a dead end is reached, right? So, I suppose that the "avoid dead ends" rule is meant as "if possible".

I assume you want to develop some kind of strategy game, where one needs to first send some troops to "unknown" areas to know what kind of resources are there etc. And your question is about how to naturally explore this unknown area quickly.

About 15 years ago invented some algorithm that's based on animal behavior. I jokey called it the "Algorithm of the 'shitting' hamster". The name just explains the algorithm quite easily: Imagine a hamster would explore your maze and on every field on the map it moves to, it shits. And well, now it stinks there! The hamster of course doesn't like that and always moves next field it can reach that stinks the least. This ways it will explore the map quite quickly. To give you a better understanding: At each map position it will first move in one of the directions where it did not come from (as it stinks most from there). When it reaches the map field a second time it will take one of the other two directions first. And when it visits the field quite often, it will even go back the way it initially came from. Which means that it will leave the dead ends.

It will even work very well with multiple "hamsters". Or better: imagine it were ants... They will spread into different direction themselves. For the implementation you only need a counter for each field on the map, which counts the number of "visits" (the same counter is used for the entire group).

You can even extend this algorithm to let them find the quickest way back home, by letting each "ant" (or "hamster") count up a "step counter" for each step since it left it's start position. On each map field you store the minimum "step counter" values as following: Initialize the map-values with "maximum". While exploring: If you reach a new map field check if your "step counter" is lower than the stored value on the map, if so ... store your value there. To find a short way home: look for the lowest "step counter" value of the neighboring fields and following the path...

There are lots of ways to extend this to fit special tasks. For example: I adapted this kind of algorithms in the early 90s to simulate some kind of anthill, where ants were exploring a random map that contained some sugar. In the simulation the ants explored the map, until they found sugar and brought it to the anthill (fastest way back home). They also directed the other ants to the sugar they found (by placing some markers on the map that burred out, as soon others were following the path). Eventually, the sugar at one position was depleting and the ants were automatically stopping to follow the "markers" (as they blurred out) and were looking for new resources. So, the basic algorithm has been really practically tested... You just need to be a bit creative to adapt this to your problem.

Okay... I hope you got the key idea and that it hopefully helps you.

Stefan

PS: Let me know if you need more detailed explanations...
> 1 votes

---
Tags: ai, grid
---


title: 2D object move & evade obstacle

text:
# Question
Title: 2D object move & evade obstacle
## Description:

```
Actor{
    int x,y,width,height;
    float speed, angle;
}

```

actor is an object that move around the map
every frame, actor change position(x,y) according to it’s speed & angle

## Problem:

If: Next frame actor A will collide with actor B
Then: A should turn to what angle to evade B?

# Answer
Do you evade in the sense of "to flee" or "to (non-)cooperatively walk around each other"?

The answer to both questions is quite easy:

1) To let A flee away from B... let move A in the direct opposite direction of B relative to A. Which means: The direction vector should be Position(B) - Position(A). You'll then need to calculate the angle from this Vector for you data model (I think using atan(y/x) of the direction vector; or maybe atan(x/y) ... just try).

2) The let them -cooperatively- "walk around each other" just remind, what you do on the street, if you confront someone walking in your direction. You have to decide for a general "evasion"-direction. Which means: left or right in 2D. So either both actors evade on the right... or both of them evade on the left around the obstacle / other actor. This means you have to adapt your moving angle in one direction. The amount depends on the size of your bounding box. Note: I suggest you to use a bounding circle instead of a bounding box (as the corners of the bounding box will cause problems). If you run into performance problems only check the distance in case of collision. Use a hard limit and a soft limit for the obstacle distance. So you'll have 3 states: No Obstacle, Obstacle in Soft Limit, Obstacle in Hard Limit. Then observe the state changes. When the state changes from "No obstacle" to "Obstacle in Soft Limit" adjust your moving angle to evade. If it changes back to "No obstacle" adjust it back to move to your target position... It it changes to "Obstacle in Hard Limit" stop & wait! If you don't have a state, it will be quite complicated... as your actor will turn and turn and turn while it detects a bounding box collision, which makes it actually move in a circle and will maybe even let it crash into the obstacle.

3) For non-cooperative evasion you'll need to additionally 'evade' in a stronger manner as the opponent is not evading (passive, following a static path) or even trying to hit you (i.e. a missile).

Hope this helps Stefan
> 2 votes

---
Tags: physics, algorithm, ai
---


# Question
Title: Shader applied to Texture is not showed in GLSLES
I'm trying to learn the basic of shaders following basic tutorials in Ogre.

I use GLSL ES 2.0 #version 100

I think I have a basic concept problem. I'm trying to render a model + texture without make modifications to be sure that is working, and then start with modifications.

I have the following material:

```
fragment_program Basic_ps_glsles glsles
{
    source Basic_ps.glsles
    profiles glsles

    default_params
    {
        param_named tex0 int 0
    }
}

vertex_program Basic_vs_glsles glsles
{
    source Basic_vs.glsles
    profiles glsles

    default_params
    {
        param_named_auto mvp_matrix viewproj_matrix
    }
}

material Penguin
{
    technique
    {
        pass
        {
            ambient 0.5 0.5 0.5
            diffuse 0.5 0.5 0.5

            fragment_program_ref Basic_ps_glsles glsles
            {
            }

            vertex_program_ref Basic_vs_glsles glsles
            {
            }

            texture_unit
            {
                texture penguin.jpg
                tex_coord_set 0
            }

        }
    }
}

```

And I apply the next Vertex shader:

```
#version 100

//http://www.widget-101.com/opengl/curso-basico-opengl/opengl-glsl/

precision mediump int;
precision mediump float;

attribute vec4 position;
attribute vec4 vertex;
attribute vec4 multiTexCoord0;

uniform mat4 mvp_matrix;
uniform mat4 texture_matrix;

varying vec4 frag_color;
varying vec2 texCoord;

void main()
{
    gl_Position = mvp_matrix*position;
    vec4 transformed_tex_coord = mvp_matrix * multiTexCoord0;
    texCoord = transformed_tex_coord.st;
}

```

And then the next Fragment Shader:

```
#version 100

precision mediump int;
precision mediump float;

uniform sampler2D tex0;

varying vec4 frag_color;
varying vec2 texCoord;

void main()
{
    vec4 color = texture2D(tex0,texCoord);
    gl_FragColor = color;   //vec4(0.0, 1.0, 0.0, 1.0); // frag_color;
}

```

But The texture is not applied to the pinguin. It appear totally black. I think is a problem with the texture coordinates. What I doing wrong with the texture coordinates?

# Answer
The problem is the texture coordinates. Ogre store the data in attribute vec4 uv0; So in the vertex shader:

```
gl_Position = mvp_matrix*position;
texCoord = uv0.st;

```

Solve the problem
> 0 votes

---
Tags: shaders, glsl
---


# Question
Title: 3G ISPs blocking TCP protocol on port 80?
I want to run a custom TCP protocol over a 3G connection for a game. (Amazon server with mobile clients) I decided to use port 80 because hey, it's open. I'm aware that some paranoid ISPs will have stateful / application level firewalls that will reject TCP traffic based on some rules about non-http traffic or something.

How can I avoid firewall filtering on port 80? I know its probably not possible in all cases.

Is there some minimal fake headers I can use in my data stream to satisfy such a gateway?

Are there any other known protocols that the gateway will blindly forward and which I could masquerade as ?

* To follow up in case it helps anyone: I ended up using a custom binary protocol over port 443. This seemed to satisfy most of the ISP traffic shapers - I haven't gotten any complaints about connectivity.

# Answer
> 1 votes
Or why not actually use HTTP as a communication protocol? You could make your application communicate with the server using SOAP.

When you do not want to do this, you could trick most deep packet inspection software by using port 443 (HTTPS, rarely blocked when normal HTTP is allowed) and pretend to do a HTTPS handshake. Whether or not you actually encrypt the traffic, any deep packet inspection software will likely assume that the traffic is securely encrypted and not attempt to analyze it further.

But keep in mind that traffic on port 80 or 443 which doesn't look like typical web browsing is a telltale sign of malware communicating with command&control servers (they use these ports for the same reason you want to). So your software might trigger intrusion detection systems.

# Answer
> 0 votes
You can do as Phillip suggests and build your protocol over HTTP, or even use one of many existing protocols that work over HTTP such as SOAP.

However, if this is not enough for your needs, I recommend you consider making your game work on your custom protocol on the port of your choice. You can have your game have some basic requirements, such as a non-distopyan ISP. Think of this as just like making a game require only Windows XP and above. Yeah, some people are still running Windows ME, but support for such a minority may not be worth it in the big scale.

You should focus your efforts on making your game fun and exciting. And once your game is popular, if you see there is a large demand in that niche market, then you can add support for those specific networks at a later point in time.

---
Tags: networking, multiplayer, mobile
---


# Question
Title: Monte Carlo Tree Search for simultaneous multiplayer game
I am developing AI for bomberman and i want to implement monte carlo tree search. I read that MTCS can be applied for simultanous multiplayer game. Problem i have is that i dont know how to implement it. For instance, how to store all possible moves in one game state or how to apply UTC selection. Should i call utc selection for all players and final state to select will be combination of their moves? Has anybody any literature to read or article? Thanks

# Answer
> 7 votes
the Monte Carlo Tree Search (MCTS) is applicable but not very good in this case, as the opponents actors are not "random" but will choose the best move they can.

However, if you choose to use MCTS you have to

1. copy the current game state for simulation...
2. loop through all possible moves m in that state

A. For N times do...

* Setup simulation-copy to "saved state"
    * do the move in the simulation-copy.
    * Finish the game by simulating random moves (Monte Carlo Simulation)\*
    * At the end of each simulation, evaluate the result in numbers (seen from the view of the current player, e.g. "lost" = -1, "draw" = 0, "won" = 1).
    * Add result to "sum"

B. Store "Average Result" (= "sum" divided by "N") for move m
3. Select move with highest average result and execute it

As the moves in your simulation are "random" it will possibly take a very long time till one of the player actually looses (by not bombing itself). So you should limit how long a simulation runs at maximum.

You should also use a more complex result evaluation not only based on final results (win/loss, but in case of "draw" you should e.g. subtract the number of bombs that will soon explode nearby).

You'll of course need to copy/simulate the whole game state (for all players). Just choose random moves at each time step for each player and simulate them.

BUT, it's better if you use an algorithm like "minimax". MCTS can be combined with "minimax", if your game contains randomness (as for example random behaviour for items gathered). Have a look at http://en.wikipedia.org/wiki/Minimax for a good reference...

In that case your search algorithm must be implemented recursively (see http://en.wikipedia.org/wiki/Recursion). For bomberman you'll need to adapt minimax a bit, if there will be more than 2 players.

To quickly give the key idea of minimax, let us look at the following example search tree from the above wikipedia article.

Above we have the current game state as a node. It's connected to the possible following states (timesteps are "downwards"), left and right. At each following state you follow the new possible moves until you reach the maximum depth (here: 4) or until the game ends. Then you evaluate the state. In the minimax/negamax algorithm each player does its move in its own time step (knowing the other players move of the previous time steps). A player always chooses the path, that guarantees the -best- result for her/him. This result is recursively returned by the search function. In 2-person games an "evaluation function" is often like "Player A wins" = positive number, "Neither Player wins (draw)" = 0, "Player B wins" = negative number. So player A tries to maximize the result of the evaluation of the game and player B tries to minimize it. We always evaluate the game at the leave nodes (here: depth = 4). Between the depth levels (0 to 4) there are the moves of one player each:

* depth level 0 to 1: Player A
* depth level 1 to 2: Player B
* depth level 2 to 3: Player A
* depth level 3 to 4: Player B

Assume, we are at the leave node (the one in the bottom-left) and have evaluated the game state ("10" at depth level 4). We return the game state evaluation (10) for move variation "left"... then we recursively go into depth for "right", which returns "+Infinite". As this is player B's turn (depth level 3 to 4) he tries to minimize the evaluation. So he would choose "left", as "10" is better because the move "right" would be "+Infinite" (player A wins). So for this node "10" is the result, which is returned, when leaving the recursion. Now we are at depth level 2 and got "10" returned for move "left" - we would recursively call our function for "right", which returns "5". Depth level 2 is Player A's turn... he/she tries to maximize the value and would choose "left" (10). This way we continue until we have an evaluation of the start position. When having recursively evaluated all moves at depth level 0, we will decide for one (here: player A's turn... so he/she would take "right" (-7)) of them an store it as the search result.

This needs to be adapted to bomberman: Evaluation must be done/stored for each player separately. And you'll need to search all combinations of all players moves in one time step. The evaluation of a move "m" for player "p" is calculated by the calculating the minimum of the evaluations (evaluated for player "p") of all move combinations containing move "m" for Player "p". The new evaluation of the state for player "p" is then the maximum of the evaluations for those moves. In other words: When in game state "n" player "p" plays move "m" and the other players play their moves, player "p" will achieve at least a score x (= minimum calculation for own view). A player in state "n" always chooses the move "m" that maximizes its own evaluation. This way you will get "backwards" in time to the current game state and know for all players their best move.

Even thought simple minimax produces optimal results, it's also -very- slow if your search depth becomes high. You should therefore use alpha-beta pruning (http://en.wikipedia.org/wiki/Alpha-beta\_pruning), which causes -roughly- that "bad" move combinations get less and "good" move combinations get more computation time. The speedup with alpha-beta-pruning is about factor 100. But you should more invest in a good evaluation function and not search too deep through all possible moves.

Hope that helps... Don't bother to ask, if you need more help!

Stefan

---
Tags: ai
---


title: Copyright infringement in game title

text:
# Question
Title: Copyright infringement in game title
I'm a wanna-be indie developer, and I am working on my first flash game. But, before I even start with the code, I want to know this: When determining the title of my game, how can I decide if it is copyrighted or not?

For example, at first I thought about "Into the Void" for the title. When I Googled it, I found out that it is a name of a song by Black Sabbath. Is it okay if I use this title, or is it copyright infringement?

# Answer
Short answer: you can use that name for your game legally, as long as you abide by the copyright laws and the name is not trademarked.

For the long answer, we refer to Wikipedia:

> **Copyright infringement** is the unauthorized use of works under copyright, infringing the copyright holder's "exclusive rights", such as the right to reproduce, distribute, display or perform the copyrighted work, spread the information contained within copyrighted works, or to make derivative works. It often refers to copying "intellectual property" without written permission from the copyright holder, which is typically a publisher or other business representing or assigned by the work's creator.

If you really want to avoid any confusion or problems that may occur in the future, try contacting Black Sabbath and ask them if you can use that name for your game. If they say "no", then perhaps consider a lawyer, or just come up with a different name. If they say "yes", make sure to keep your paper trail for reference in the future.

**Relevent Links:**
> 5 votes

# Answer
If you want proper legal advice speak to a lawyer.

However, as far as I know copyright isn't a big issue with titles for games, especially when it clashes with something that's not a game. Trademarks are something you should avoid though.

However if you want people to be able to find your game on a search engine, having a name that hasn't already been used for something well known is probably a good idea, and that should also keep you safe from any legal issues.
> 1 votes

# Answer
The title of a game isn't copyrighted - it is trademarked. Trademark law and copyright law are related but entirely different areas.

While registration of a copyright is optional, a trademark must be registred to be enforceable (there are exceptions, like claiming an unregistred trademark through notoriety, but these are hard to prove in court).

Trademarks registred in the US can be researched on http://tmsearch.uspto.gov/ but keep in mind that trademarks always apply to individual countries. So when you sell a game internationally, you need to make sure that you don't advertise it in any country where the trademark is registred.

Trademarks always apply for specific groups of goods and services. So when I have a trademark "SuperAwesome2000" for toothpaste, kitchen appliances and sportswear, you could still name your game "SuperAwesome2000" without infringing my trademark, because entertainment software is a completely different field. You could even register the trademark yourself, as long as you do it for different product groups than I did. But when you start selling t-shirts advertising your game, we have a problem because you are infringing my trademark on sportswear.

Interesting read in this regard: Apple Corps vs. Apple Computers.

But like in every legal matter: **When in doubt consult a lawyer.**
> 0 votes

---
Tags: game-industry, copyright, trademark
---


# Question
Title: Making enemy boss movement better than just moving randomly
I am making a game where I have a player spaceship on left side and an enemy spaceship (boss) on the right. I need some ideas on what my enemy should do.

If I move my enemy down and up, down and up, etc.. then the player will be able to predict the enemy's movements. On the other hand, I don't really want the enemy to move randomly. It won't look good if the enemy is just moving to and shooting at random places.

I am also thinking of making my enemy move left, and when it reaches the outside of the screen then coming back in from the right side. Let me know what you guys think.

# Answer
From my memory of boss battles, many have *known* but *challenging* movements.

It's OK if a player knows their movements. Random movements could be very frustrating to players who are experienced with arcade shooters. The movements don't have to be solely based on left, right, up, down either. You can have the boss move towards the player slowly, or keep a specific distance or any number of combinations. Often times the movement pattern will change throughout the battle, sometimes based on the boss's health, sometimes based on timers.

All in all, it's something you'll have to try out. **Play testing** is pretty important in these kinds of situations. Make sure you're able to easily change the movement patterns between builds so you can easily test multiple configurations.
> 11 votes

# Answer
I guess it would be nice when the enemy would always shoot at the player, but with a time delay, so that he cannot hit the player when the player moves fast enough, but this would only be nice if the boss fight should be easy to manage, when it should be more difficult, than you can let him shoot in kind of a circle and mix it with shooting at random positions. You can also let the spaceship fly in a circle, but to the right of the screen and then back sounds also good. I would make a mixture of that things, dependent on how difficult you want to make the boss fight. You can also look at the game "Ratchet and Clank: Tools of Destruction". There are some boss fights with spaceships, and it is always different.
> 1 votes

# Answer
I would suggest having a handful of scripted motions which always lead the boss back to a default location. Then when the boss has compled a motion, you can either choose the next one randomly, or you could take it from a predefined pattern if you want the player to be able to learn the behaviour through repeated play.
> 1 votes

# Answer
In most classic shoot-em-ups, bosses have a fixed behavior pattern which they execute without any regard to the actions of the player.

The main challenge here is to learn the pattern and react accordingly.

To give a spin on this you could make the behavior of the boss depending on the actions of the player. Like:

* Have it move or change its move strategy when it takes damage
* Make its weapons fire into the direction of the player
* Or Have weapons which fire only in one direction, but make the boss itself move so that the player is in the weapons field of attack
> 1 votes

# Answer
Prepare some patterns and do tests with all of them with multiple game testers (or just some friends) multiple times per pattern (e.g. 6 times per pattern). For each pattern, record the success rate and the learning rate (e.g. average success rate first and second half of the test). Also let the testers rate the boss movement pattern as "too easy", "easy", "okay", "harder", "hard", "too hard", "nearly impossible".

The preparation of the patterns could be done by once controlling the boss yourself like the player character and record the actions. Implement some kind of "arena" where you directly enter the boss fight and one can control/record the boss. This way your boss will probably become more "natural", that means less "programmatic".
> 1 votes

---
Tags: ai
---


# Question
Title: How to predict future location of a Car in a Navigation Mesh based pathfinding system?
I am developing a car based shooting game in which the Cars have to shoot each other 3/4 times and eliminate it from the game.

I am trying to develop the AI for my cars now. The problem is how can I predict the future location of one of the user cars in a Navigation Mesh based path finding system ? I know its current velocity and direction but since we don't have a grid structure how can I predict its location in the next 2 or 3 seconds ?

One of the solutions I could think of was find the X,Y position of the user's car using his current velocity and direction and then approximate to which node does the point belong. Is there any better system than this which could be employed ?

Any help would be appreciated. Thanks :)

# Answer
> 3 votes
I guess you mixed up "path finding" and "object state" (e.g. position, speed, direction, ..). Path finding is used to find a path from position A to position B. As far as I understand, the "Mesh based" algorithm is only used to simplify this "path finding" process, when an actor (e.g. a car) wants to move from position A to position B to reduce the maps complexity for the search algorithm.

All this has nothing to do with the actual position of actors during the game. The actors will (in this case) usually move continuously in one direction until they turn at the next corner. So you can take two observed positions (first / second) of the opponent to calculate the movement vector ( movement = second - first). If you divide it by the time between the observations (duration, in seconds) and multiply it by a time span x (in seconds), you get the relative position of the opponent, if it continues to move that way for x seconds. The estimation is calculated by: estimated = second + (second - first) * ( x / duration), where first, second, estimated are vectors and x, duration are scalars (time spans in seconds). The time spans don't need to be seconds but need to have the same unit (e.g. frames, time steps, ...).

Regards Stefan

---
Tags: collision-detection, ai, path-finding, planning, navmesh
---


title: Minimax for Bomberman

text:
# Question
Title: Minimax for Bomberman
I am developing clone of Bomberman game and I am experimenting with different types of AI. First I used searching through state space with A\* and now i want to try different approach with Minimax algorithm. My problem is that every minimax article i found assumed players alternates. But in Bomberman, every player make some action at the same time. I think i could generate all possible states for one game tick, but with four players and 5 basic actions (4 moves and bomb place) it gives 5^4 states at first level of the game tree. That value will raise exponentially with every next level. Am I missing something? Are there any ways to implement it or should i use totally different algorithm? Thanks for any suggestions

# Answer
> 8 votes
Real-Time Strategy games like bomber man have a difficult time with AI. You want it to be intelligent, but at the same time it cannot be perfect.

If the AI is perfect, your players will get frustrated. Either because they always lose or you get .3 frames per second.

If it is not intelligent enough, your players will get bored.

My recommendation is to have two AI functions, one that determines where the AI goes, the other that determines when is best to drop a bomb. You can use things like movement prediction to determine if an enemy is moving towards a spot that will be dangerous if a bomb is dropped in the current location.

Depending on difficulty you can modify these functions to improve or decrease difficulty.

# Answer
> 4 votes
As you have noticed, Bomberman is much too complex to be simulated as a turn-based game. Extrapolating any possible own decision plus every possible decision of every other player just doesn't work out.

Instead of that you should rather use a more strategical approach.

You should ask yourself: How does a human player make decisions while playing bomberman? Usually, a player should follows four basic priorities:

1. avoid explosion areas of bombs
2. place bombs so others can't avoid their explosion areas
3. collect powerups
4. place bombs to blow up rocks

The first priority can be fulfilled by creating a "danger map". When a bomb is placed, all tiles covered by it should be marked as "dangerous". The sooner the bomb explodes (keep chain reactions in mind!), the higher the danger level. Whenever the AI notices that it is on a field with a high danger, it should move away. When it plots a path (for whatever reason) fields with a high danger level should be avoided (can be implemented by artificially adding a higher path cost to them).

The danger map calculation can be further enhanced to protect the AI from stupid decisions (like entering areas which are hard to escape from when another player is near).

This should already create a reasonable defensive AI. So what about offense?

When the AI realizes that it is reasonably safe right now, it should plan offensive maneuvers: It should consider how it can increase the danger map around the other players by placing bombs itself. When choosing a location to plant a bomb, it should prefer close locations so it doesn't have to move so far. It should also disregard bomb locations when the resulting danger map doesn't allow for a reasonable escape route.

# Answer
> 4 votes
> I think i could generate all possible states for one game tick, but with four players and 5 basic actions (4 moves and bomb place) it gives 5^4 states at first level of the game tree.

Correct! You need to search all 5^4 (or even 6^4, as you can walk in 4 directions, stop and "put a bomb"?) actions for each game tick. BUT, when a player already decided to move, it takes some time till the move is executed (e.g. 10 game ticks). During this period the number of possibilities reduces.

> That value will raise exponentially with every next level. Am I missing something? Are there any ways to implement it or should i use totally different algorithm?

You can use a Hash-Table to only calculate the same game state "subtree" once. Imagine player A walks up and down, while all other players "wait", you end up in the same game state. It's the same as for "left-right" or "right-left". Also moving "up-then-left" and "left-then-up" results in the same state. Using a Hash-Table you can "reuse" the calculated score for a game state that has already been evaluated. This reduces the growth speed quite a lot. Mathematically, it reduces the base of your exponential growth function. To get an idea of how much it reduces the complexity let us look at the moves possible for only one player compared to reachable positions on the map (=different game states) if the player may just move up/down/left/right/stop.

depth 1: 5 moves, 5 different states, 5 additional states for this recursion

depth 2: 25 moves, 13 different states, 8 additional states for this recursion

depth 3: 6125 moves, 25 different states, 12 additional states for this recursion

To visualize that, answer yourself: which fields on the map can be reached with one move, two moves, three moves. The answer is: All fields with a maximum distance = 1, 2 or 3 from start position.

When using a HashTable you only have to evaluate each reachable game state (in our example 25 at depth 3) once. Whereas without a HashTable you need to evaluate them multiple times, which would mean 6125 evaluations instead of 25 at depth level 3. The best: Once you calculated a HashTable entry you can re-use it in later time steps...

You can also use incremental deepening and alpha-beta pruning "cut" subtrees that are not worth searching in more depth. For chess this reduces the number of searched nodes to about 1%. A short introduction to alpha-beta pruning can be found as a video here: http://www.teachingtree.co/cs/watch?concept\_name=Alpha-beta+Pruning

A good start for further studies is http://chessprogramming.wikispaces.com/Search . The page is related to chess, but the search and optimization algorithms are quite the same.

Another (but complex) AI algorithm - that would be more suitable to the game - is "Temporal Difference Learning".

Regards

Stefan

PS: If you reduce the number of possible game states (e.g. very small size of the map, only one bomb per player, nothing else), there is a chance to pre-calculate an evaluation for all game states.

--edit--

You could also use offline-calculated results of the minimax calculations to train a neuronal network. Or you could use them to evaluate/compare hand-implemented strategies. For example you could implement some of the suggested "personalities" and some heuristics that detect, in which situations which strategy is good. Therefore you should "classify" situations (e.g. game states). This could also be handled by a neuronal network: Train a neuronal network to predict which of the hand-coded strategies is playing the best in the current situation and execute it. This should produce extremely good real-time decisions for a real game. Much better than a low-depth-limit search that can be achieved otherwise, since it doesn't matter that much how long the offline-calculations take (they are before the game).

-- edit #2 --

If you only recalculate your best moves every 1 second, you could also try to do more higher level planing. What do I mean by that? You know how many moves you can do in 1 second. So you can make a list of reachable positions (e.g. if this would be 3 moves in 1 second, you would have 25 reachable positions). Then you could plan like: go to "position x and place a bomb". As some others suggested you can create a "danger" map, which is used for the routing algorithm (how to go to position x? which path should be prefered \[there are some variations possible in most cases\]). This is less memory consuming in comparision to a huge HashTable, but produces less optimal results. But as it uses less memory it could be faster because of caching effects (better use of your L1/L2 memory caches).

ADDITIONALLY: You could do pre-searches which only contains moves for one player each to sort out variations that result loosing. Therefore take all other players out of the game... Store which combinations each player can choose without loosing. If there are only loosing moves, look for the move combinations where the player stays alive the longest time. To store/process this kind of tree structures you should use an array with index-pointers like this:

```
class Gamestate {
  int value;
  int bestmove;
  int moves[5];
};

#define MAX 1000000
Gamestate[MAX] tree;

int rootindex = 0;
int nextfree = 1;

```

Each state has a evaluation "value" and links to the next Gamestates when moving (0 = stop, 1 = up, 2 = right, 3 = down, 4 = left) by storing the array index within "tree" in moves\[0\] to moves\[4\]. To build your tree recursively this could look like this:

```
const int dx[5] = { 0,  0, 1, 0, -1 };
const int dy[5] = { 0, -1, 0, 1,  0 };

int search(int x, int y, int current_state, int depth_left) {
  // TODO: simulate bombs here...
  if (died) return RESULT_DEAD;

  if (depth_left == 0) {
    return estimate_result();
  }

  int bestresult = RESULT_DEAD;

  for(int m=0; m<5; ++m) {
    int nx = x + dx[m];
    int ny = y + dy[m];
    if (m == 0 || is_map_free(nx,ny)) {
      int newstateindex = nextfree;
      tree[current_state].move[m] = newstateindex ;
      ++nextfree;

      if (newstateindex >= MAX) {
        // ERROR-MESSAGE!!!
      }

      do_move(m, &undodata);
      int result = search(nx, ny, newstateindex, depth_left-1);
      undo_move(undodata);

      if (result == RESULT_DEAD) {
        tree[current_state].move[m] = -1; // cut subtree...
      }

      if (result > bestresult) {
        bestresult = result;
        tree[current_state].bestmove = m;
      }
    }
  }

  return bestresult;
}

```

This kind of tree structure is much faster, since dynamically allocating memory is really really slow! But, storing the search tree is quite slow either... So this is more an inspiration.

# Answer
> 0 votes
Would it help to *imagine* that everybody does take turns?

Technically, in the underlying system, they actually do, but since things are interleaved and overlapped, they *appear* to be running simultaneously.

Also remember that you don't have to run AI after *every* frame of animation. Many successful casual games only run the AI algorithm once every second or so, providing the AI-controlled characters with information on where they're supposed to go or what they're supposed to do, then that information is used to control the AI characters on the other frames.

---
Tags: ai
---


# Question
Title: How do I rotate a structure of hexagonal tiles on a hexagonal grid?
My 2D isometric game uses a hexagonal grid map. In reference to the image below, how do I rotate the light blue hexagon structures by 60 degrees around the pink hexagons?

EDIT:

Main hex is (0,0). Other hexes are children, count of them is fixed. I'm going to define only one position (in this case its right) and calculate other directions if needed (left-bottom, right-botom, right-top, left-top and left). Other hexes are defined like: Package.Add(-1,0), Package.Add(-2,0) and so on.

```
switch(Direction)
{
case DirRightDown:
    if(Number.Y % 2 && Point.X % 2)
        Number.X += 1;
    Number.Y += Point.X + Point.Y / 2;

    Number.X += Point.X / 2 - Point.Y / 1.5;
    break;
}

```

In this code `Number` is the main hex and `Point` is the hex that I want to rotate, but it doesn't work:

# Answer
As Martin Sojka notes, rotations are simpler if you convert to a different coordinate system, perform the rotation, then convert back.

I use a different coordinate system than Martin does, labeled `x,y,z`. There's no wobble in this system, and it's useful for lots of hex algorithms. In this system you can rotate the hex around `0,0,0` by “rotating” the coordinates and flipping their signs: `x,y,z` turns into `-y,-z,-x` one way and `-z,-x,-y` the other way. I have a diagram on this page.

(I'm sorry about x/y/z vs X/Y but I use x/y/z on my site and you use X/Y in your code so in this answer the case matters! So I'm going to use `xx,yy,zz` as the variable names below to try to make it easier to distinguish.)

Convert your `X,Y` coordinates to the `x,y,z` format:

```
xx = X - (Y - Y&1) / 2
zz = Y
yy = -xx - zz

```

Perform a rotation by 60° one way or the other:

```
xx, yy, zz = -zz, -xx, -yy
     # OR
xx, yy, zz = -yy, -zz, -xx

```

Convert the `x,y,z` back to your `X,Y`:

```
X = xx + (zz - zz&1) / 2
Y = zz

```

For example, if you start with (X=-2, Y=1) and want to rotate 60° right, you'd convert:

```
xx = -2 - (1 - 1&1) / 2 = -2
zz = 1
yy = 2-1 = 1

```

then rotate `-2,1,1` 60° right with:

```
xx, yy, zz = -zz, -xx, -yy = -1, 2, -1

```

as you see here:

then convert `-1,2,-1` back:

```
X = -1 + (-1 - -1&1) / 2 = -2
Y = -1

```

So (X=-2, Y=1) rotates 60° right into (X=-2, Y=-1).
> 15 votes

# Answer
Let's first define a new number. No worries, it's an easy one.

* *f*: *f* × *f* = -3

Or, to put it simply: f = √3 × *i*, with *i* being the imaginary unit. With this, a rotation by 60 degrees clockwise is the same as multiplication by **1/2 × (1 - *f*)**, and rotation by 60 degrees counter-clockwise the same as multiplication by **1/2 × (1 + *f*)**. If this sounds strange, remember that multiplication by a complex number is the same as rotation in the 2D plane. We just "squash" the complex numbers in the imaginary direction a bit (by √3) to not have to deal with square roots ... or non-integers, for that matter.

We can also write the point (a,b) as a + b × *f*.

This lets us rotate any point in the plane; for example, the point (2,0) = 2 + 0 × *f* rotates to (1,-1), then to (-1,-1), (-2,0), (-1,1), (1,1) and finally back to (2,0), simply by multiplying it.

Of course, we need a way to translate those points from our coordinates to those we do the rotations in, and then back again. For this, another bit of information is needed: If the point we do the rotation around is to the "left" or to the "right" of the vertical line. For simplicity, we declare that is has a "wobble" value *w* of 0 if it's to the left of it (like the center of the rotation \[0,0\] in your bottom two pictures), and of 1 if it's to the right of it. This extends our original points to be three-dimensional; (*x*, *y*, *w*), with "w" being either 0 or 1 after normalisation. The normalisation function is:

NORM: (*x*, *y*, *w*) -\> (*x* \+ floor(*w* / 2), *y*, *w* mod 2), with the "mod" operation defined such that it only returns positive values or zero.

Our algorithm now looks as follows:

1. Transform our points (*a*, *b*, *c*) to their positions relative to the rotational centre (*x*, *y*, *w*) by calculating (*a* \- *x*, *b* \- *y*, *c* \- *w*), then normalising the result. This puts the rotational centre at (0,0,0) obviously.
2. Transform our points from their "native" coordinates to the rotational complex ones: (*a*, *b*, *c*) -\> (2 × *a* \+ *c*, *b*) = 2 × *a* \+ *c* \+ *b* × *f*
3. Rotate our points by multiplying them with one of the rotational numbers above, as needed.
4. Ra-transform the points back from the rotational coordinates to their "native" ones: (*r*, *s*) -\> (floor(*r* / 2), *s*, *r* mod 2), with "mod" defined as above.
5. Re-transform the points back to their original position by adding them to the rotational centre (*x*, *y*, *z*) and normalising.

---

A simple version of our "triplex" numbers based *f* in C++ would look like this:

```
class hex {
    public:
        int x;
        int y;
        int w; /* "wobble"; for any given map, y+w is either odd or
                  even for ALL hexes of that map */
    hex(int x, int y, int w) : x(x), y(y), w(w) {}
    /* rest of the implementation */
};

class triplex {
    public:
        int r; /* real part */
        int s; /* f-imaginary part */
        triplex(int new_r, int new_s) : r(new_r), s(new_s) {}
        triplex(const hex &hexfield)
        {
            r = hexfield.x * 2 + hexfield.w;
            s = hexfield.y;
        }
        triplex(const triplex &other)
        {
            this->r = other.r; this->s = other.s;
        }
    private:
        /* C++ has crazy integer division and mod semantics. */
        int _div(int a, unsigned int b)
        {
            int res = a / b;
            if( a < 0 && a % b != 0 ) { res -= 1; }
            return res;
        }
        int _mod(int a, unsigned int b)
        {
            int res = a % b;
            if( res < 0 ) { res += a; }
            return res;
        }
    public:
        /*
         * Self-assignment operator; simple enough
         */
        triplex & operator=(const triplex &rhs)
        {
            this->r = rhs.r; this->s = rhs.s;
            return *this;
        }
        /*
         * Multiplication operators - our main workhorse
         * Watch out for overflows
         */
        triplex & operator*=(const triplex &rhs)
        {
            /*
             * (this->r + this->s * f) * (rhs.r + rhs.s * f)
             * = this->r * rhs.r + (this->r * rhs.s + this->s * rhs.r ) * f
             *   + this->s * rhs.s * f * f
             *
             * ... remembering that f * f = -3 ...
             *
             * = (this->r * rhs.r - 3 * this->s * rhs.s)
             *   + (this->r * rhs.s + this->s * rhs.r) * f
             */
            int new_r = this->r * rhs.r - 3 * this->s * rhs.s;
            int new_s = this->r * rhs.s + this->s * rhs.r;
            this->r = new_r; this->s = new_s;
            return *this;
        }
        const triplex operator*(const triplex &other)
        {
            return triplex(*this) *= other;
        }
        /*
         * Now for the rotations ...
         */
        triplex rotate60CW() /* rotate this by 60 degrees clockwise */
        {
            /*
             * The rotation is the same as multiplikation with (1,-1)
             * followed by halving all values (multiplication by (1/2, 0).
             * If the values come from transformation from a hex field,
             * they will always land back on the hex field; else
             * we might lose some information due to the last step.
             */
            (*this) *= triplex(1, -1);
            this->r /= 2;
            this->s /= 2;
        }
        triplex rotate60CCW() /* Same, counter-clockwise */
        {
            (*this) *= triplex(1, 1);
            this->r /= 2;
            this->s /= 2;
        }
        /*
         * Finally, we'd like to get a hex back (actually, I'd
         * typically create this as a constructor of the hex class)
         */
        operator hex()
        {
            return hex(_div(this->r, 2), this->s, _mod(this->r, 2));
        }
};

```
> 5 votes

---
Tags: 2d, rotation, maps, hexagonal-grid
---


title: Hexagonal grid/tiles tutorials

text:
# Question
Title: Hexagonal grid/tiles tutorials
Are there any platform or language agnostic (preferably step by step) tutorials regarding creating hexagonal grid based maps/games? I'm mainly interested in grid/tiles basics and not advanced game engine stuff. So far I have found these:

# Answer
I have been working on a hex tile game and found these tutorials useful:

Good luck with your project!
> 20 votes

# Answer
This guide didn't exist when the question was asked, but here's my guide to hex grid math:
> 45 votes

---
Tags: tiles, hexagonal-grid
---


# Question
Title: Hardcore or casual? Help me understand please
I am working on an easy casual physics puzzle on iOS for kids and thought of this question.

In my honest opinion casual kids games must have simple gameplay - one tap or command for a step, several steps/decisions for a stage. But how thin is the line between casual and hardcore games for iOS?

For example, Angry Birds - on first stages it's easy and fun, but then it gets challenging - you need to calculate and determine how to strike with each birdy. For the player that means some heavier calculations, so does it become not so casual eevn though financial statistics say that it is?

Please, help me to understand, how can I make my game more complicated or involved but let it be still as simple as it can be. Feel free to say about some global things, without detailising. TY!!!

upd. Game is kind of physics puzzle in space. There are stars on gamefield, that behave like balls attached to rubber strings - you can move them in any direction on short distance, and after release they fly away in choosed direction. There's no gravity, so stars don't fall to the bottom of screen and stay on their place after momentum is over. Also there's teleporters (black holes), that deliver stars from A point to B point (other end of black hole), star wind, that transfer captured stars to some destination, etc. There's a authority thought, that this mechanics can be too hard for little kids too understand, also that no-gravity feature is hard to understand for kids. Still, everything is cute, music is calm, and main character, who operate with stars, is ultracute. The main goal is to put stars in direct order in the "goal line" in the middle of screen. Player got score bonus for doing minimum of star moves (hitting goal line with one move for each star), and there's no game over, so kids can have as much attempt to put each star in direct place as many times, as they need.

# Answer
> 2 votes
In case you cannot share detailed information, the best bet in how to increase difficulty is getting verbal and non-verbal feedback from your players. Measurement is king and smart measurement rules them all (but it's also difficult, so be prepared).

Test them with your kids, your family. Deliver the game without saying anything to see if they can figure out the purpose and mechanics of the game. That way you can see if the mechanics and the game is self-explanatory (please don't put a lot of text because that's not game design at all). See what things they enjoy the most, which ones produce frustration and such.

In case your game has a mechanic that combines several type of reasoning or simpler mechanics, the way to go is to introduce them one at a time and build experience level by level. When you think is time to introduce the new mechanic, do it and when some level of mastery is achieved introduce levels when you have to combine those mechanics. By the end of the day you'll have several levels to complete (that's why you say Angry Birds feels simple at the beginning and it must).

On the other hand, casual games (IMHO and experience) are more aimed at the idea of playing it a little bit and then "go back to life" to whatever you were doing. Just like casual relationships (sort of). The fact is that you cannot underestimate kids, specially when new generations are getting fast the hangs of technology and videogames. The fact that they don't understand what zero-gravity means underneath, doesn't mean that they cannot understand what the effect implies in a game. Your train of thought should be aimed to the players and to deliver a good experience (whether they finish the game or not).

In game design, you give the tools to develop the required skills to master the game. Is their duty to use, exploit and master them. Otherwise, what's the point?

# Answer
> 0 votes
In my opinion, the line between hardcore and casual can be vast or very small depending on what the context is.

In games such as Angry Birds, the majority of players would say that you are playing a casual game because that's how the majority plays the game.

If you are trying to achieve a game that is alike to Angry Birds, what I suggest is making the goal easy to achieve but hard to perfect. If you could give more details as to what the goal of your game is, its more plausible for me to create a situation where the game can be casual and hardcore at the same time.

# Answer
> 0 votes
It sounds cute! It reminds me a little of Universe Sandbox, or Solar. Anyways the way that you want to go is fine. You have to give them a little leway here and there. For example, the new Luigi's Mansion is a great example of this, it's hilarious, funny, but still manages to keep a level of seriousness which keeps the player tied to the game. Kids like to play with their favorite characters after all, and I can't tell you how many times I got stuck in that game at a puzzle, about to give up, when Luigi starts to whistle the theme and convinces me to find how to beat it.

The gist of it is:

you gotta make it difficult, make the player want to throw their Ipod across the room, but just before they reach boiling point, you give them a push in the right direction, be it a comet streaking towards the right goal/objective, or something that one of the characters does to catch your eye, this is called baiting the player, you present a hard challenge and just before they quit, you throw a hint, subtle, but noticeable.

Some games do this blatantly however, there is an art of hiding a hint in a place where it wont be noticed until the player starts to look for clues, some bad examples include Navi from Legend of Zelda ("hey, overhere!") and Cortana (in some aspects).

You want the kids to be sucked in, and to try and learn the physics and prowress of your game, so start out small, like angry birds, and slowly get harder as the game progresses!

---
Tags: ios, puzzle
---


title: Ray Tracing in 3D - generating a ray

text:
# Question
Title: Ray Tracing in 3D - generating a ray
A ray is shot from the camera eye to the camera screen at point (i,j) how do I get the coordinates of that point in 3D world coordinates?

The best I could find online is for point S S = Q + au + bv

Q being the camera direction and u,v are the UV plane of the camera.. not sure how to find their coordinate and if I need them in world coordinates or something else.

If you could clarify this issue, it would be great.

Thanks.

# Answer
> 5 votes
You can calculate the ray from camera for any pixel `px,py` with the following formula:

```
ray.origin = camera.getPosition();
relativeX = px * 2 / screenWidth - 1; // [0, screenWidth] -> [-1, 1]
relativeY = py * 2 / screenHeight - 1; // [0, screenHeight] -> [-1, 1], might need to be flipped depending on the coordinate system
ray.direction = vector(relativeX * sin(FOV_X / 2),
                       relativeY * sin(FOV_Y / 2),
                       1);
ray.direction.normalize();
camera.getOrientation().transform(ray.direction);

```

This creates the rays first with identity camera and then transforms it according to the camera orientation. If your camera is a 4x4 matrix, `camera.getPosition()` should return the fourth column/row from the matrix and `camera.getOrientation()` should return the 3x3 upper left part of the matrix. If you have ModelToView matrix, then camera matrix is the inverse of that. If the 3x3 part of your camera matrix has only rotation but no scaling, it's simply transpose of the matrix.

A more general approach is to invert the projection matrix also. For example vertex shader might be transforming coordinates with:

```
position = projection * worldToCamera * modelToWorld * vertexPosition;

```

modelToWorld matrix is not relevant in this case, so basically this is the same as:

```
position = projection * worldToCamera * worldPosition;

```

Which can be unprojected by

```
worldPosition = inverse(worldToCamera) * inverse(projection) * position;

```

or

```
worldPosition = inverse(projection * worldToCamera) * position;

```

If you unproject two vectors with different screen space z values (e.g. `px,py,-1,1` and `px,py,1,1`), you get two vectors in world space, which defines a line in 3D space for the ray you are looking for.

---
Tags: raycasting, raytracing
---


# Question
Title: Simple 2D Collision Detection Algorithm Library
I'm building a simple OpenGL game and I was looking for some simple collision detection library for objects like squares, triangles and circles. Any suggestions?

*PS: Preferably a library that is very well documented and provide examples of 2D collision detections.*

# Answer
> 6 votes
Box2D is very popular and well documented with lots of examples. Of course it's a full on physics library so it'll give you a good amount of flexibility for expanding later if you want. But you don't need to use those features if you don't want them.

For learning more about the algorithms and how to implement them yourself you can check this out.

Additionally this is a nice resource for showing how to detect intersections between various shapes. Which plays an important role in collision detection.

# Answer
> 4 votes
I think box2d is best 2d physic engine. Which can easily provide collision detection.

# Answer
> 0 votes
theoretically, you could store the position of the objects you want to detect collision with in an array.

then just have a simple Boolean(or even void if the game is simple enough) to detect whether a collision has taken place between the object your checking and your sprite/other object that could be doing the colliding.

ex:

```
int checkCollision()
{
for(int I=0; I<maxObjects; I++)
{
      if(object1_x >= object[I] && object1_x <= object[I] + object[I].width )
      {
           return 1;
      }
  return 0;
}
}

```

this is really messy, but if you want to come up with your own method of detecting collision, you could do something along the lines of that.

I do however recommend using Box2D, much easier.

---
Tags: c++, collision-detection, c
---


# Question
Title: Hill-jumping game mechanic like Tiny Wings
I'm a huge Tiny Wings fan and I'd like to understand the game mechanic at a deeper level. **What are some good resources for the basic Box2d (or similar) physics behind the hill-jumping game mechanic?**

I've used some basic features of Box2d. I imagine the flying character is just a circle, tapping the screen increases the downward force on the character, and the hills are some sort of curve object from the physics engine.

**Edit #1** Here's more info: I'd like to understand which objects from the Box2d physics library are used to create the bare-bones hill-jumping mechanic. This mechanic would look like a "curvy" horizontal line that just scrolls across the screen. The most basic shape for this line that comes to mind is a sine wave so that's probably a good starting point.

Then there's the character that moves around. Note the character's horizontal position is fixed while the vertical position moves up and down. I'm curious about which Box2d body shape, type etc is used for this character. What are some values for the coefficient of friction that work well? How about the density etc.

I've searched around the web for tutorials that ideally will answer the above questions and perhaps provide additional resources regarding efficiency, camera motion and so on.

# Answer
You should check out this tutorial by Ray Wenderlich. It uses Cocos2d + Box2d to show how to write a game like Tiny Wings.

The first part of the tutorial explains how to create dynamic textures: http://www.raywenderlich.com/3888/how-to-create-a-game-like-tiny-wings-part-1

Second part is how to use Box2d for the gameplay: http://www.raywenderlich.com/3913/how-to-create-a-game-like-tiny-wings-part-2
> 2 votes

---
Tags: box2d, game-mechanics
---


# Question
Title: SDL text or additional images not loading
I've got a basic side scroller that allows the user to run and jump around. I've used various tutorials to get this far, but I can't seem to get any text to render, no matter what method. I also can't get any images to render outside of my draw() function which is rendered at run time, which I think is my problem. (Is it possible to recall the function again to load another image?)

I can't just give a line of code to show the issue since the whole program is interwoven together:

http://pastebin.com/d1CNiVf5

I'm not asking for someone to go through the code and fix everything, just if you could point me in the right direction, or at least know what is causing the problem that would be great!

(Sorry about having all the code in one file, I'm bad a modularising it and kept on getting errors early on in the project because of it. So for learning purposes it's going to be in one file for now).

Edit: At the moment the priority is to get projectiles working. I've tried SDL\_UpdateRect and similar but nothing has helped so far.

Edit #2: SO I've created a new function and have called it on top of the map, like it should do. But now I get a strange output: http://youtu.be/8piWyjfDgbI

# Answer
```
SDL_FillRect(screen , &bullet[i].b , 0xFFFF66);

```

This will fill your `screen` surface in the SDL\_Rect `&bullet[i].b`

Then later in the same frame, you use `drawImage` To draw the map over the entire size of `screen`, covering up the projectiles you filled it up with.

I suggest you add a separate SDL\_Surface\* for your projectile and draw them in your `draw()` function.
> 2 votes

---
Tags: 2d, sdl, c, side-scroller
---


# Question
Title: Can I make a downloadable .exe app for my game if I make it in HTML5?
I was going to make a MMORPG in HTML5 and javascript but I think I'm going to make a singelplayer first after all.. It would be nice to make the game in html5 anyway so the transition to making an mmorpg in future will be smoother.

But I would like the game to be downloadable app which is then installed like most games are.. Not a unzippable container containing a .js file.. I also want to be able to put the game up on steam.

I also don't really want the source code to be open for anyone to see if I let them download the game in a zip file where the .js and .html files are inside.

Is there a way of accomplishing this? Otherwise I will probably have to use some other language for making my game in some framework/engine like unity/xna/game maker but like I said I would prefer just using html5 and javascript with my own custom code.

# Answer
> 0 votes
Yes, this can be done using node-webkit. One example of this in the real world is a game called Lava Blade which is available on both Windows and Mac.

---
Tags: html5, single-player
---


# Question
Title: Start timer in two clients the same time
I want to create a client/server turned-based game where each player will have 5 seconds in order to play. If extends this time will be other player's turn to play. In order to do this, I have created a timer in both clients. I have created a method to the server that will send a message to both clients to start their timers. When clients will receive the message they will start counting. The problem is that due to the network lag I cannot be sure that both clients started counting in the same time. Is there a way in order to ensure this?

P.S.: When I say "the same time" I mean the same second. I'm not referring in millisec or microsec.

Thanks in advance!

# Answer
> 0 votes
Note that your current solution will likely start both timers within 1 second of eachother, probably even within a few hundred milliseconds. Getting this more accurate is a difficult problem to solve with certainty, but you can get it "close enough" for games, although it's still not easy. I would also note that timing mechanisms on two different machines may not always match, so either read up on that, or experiment with your method. I had problems where one machine's Timer object would run faster than the exact same code on a slower machine.

To sync the start-time of timers on two different machines, I would go about this in a few steps:

1. Use a time sync protocol like NTP to get the clocks in sync
2. The server would send out a message to indicate a future time that would indicate when to start the game. This must be far enough in the future to allow for lag hiccups.
3. When the future date is hit, both clients start

---

## How NTP works (roughly):

One of your machines will act as the authoritative clock (likely your server). By clock, I simply mean some method to measure the passing of time, it does not have to be your wall clock. In games, "time" is often measured from the start of the game.

**The problem:** If your server sends the current time to the clients, they will receive this information after some period of time (~RTT / 2) and the server's time will have moved forward already. It's impossible to know what the Round Trip Time (RTT) will be for any given packet. So how can the client's time ever match the servers exactly?

**The solution:** It can't match exactly, but you can get it close by measuring how long it takes for packets to get between the server and client and use that to adjust the time sent from the server. So, the server will send the current time, then after some unknown delay the client will have what used to be the server's time. The client then sends an acknowledgement to the server, and when the server gets this, it calculates the RTT based on the amount of time that has passed since the first packet, then sends the RTT back to the client where it can be used to adjust the time.

eg:

```
//Server Time is T0
Server sends out T0

-- Packet travels with a delay of 100ms

//Server Time is T100
Client receives T0 from the server
Client sends an acknowledgement to the server  (ACK for short)
Client sets time to T0, even though it is wrong

-- Packet travels with a delay of 100ms

//Server Time is T200, Client time = T100
Server receives ACK and calculates RTT as 200ms (Current Time - Start Time)
Server sends RTT of 200ms to client

//Server Time is T300, Client time = T400
Client receives message from server about RTT being 200ms
Client adjusts clock to T300  (Client Time - (RTT / 2))

// Server Time is T400, Client time = T400
And there was much rejoicing

```

The RTT is usually calculated multiple times and an average is used.

---

So, once the clocks are in sync (roughly), the server can send out a command to start the game at some future time. Both clients should receive this message with ample time to spare, then start their timers at the same real-world time.

# Answer
> 0 votes
I don't know what platform you are using but you should find out if you have access to a time function that returns the number of seconds since January 1st 1970.

IE:http://www.cplusplus.com/reference/ctime/time/

With that, you send your start time to the clients who can then figure out total elapsed time.

Otherwise you'll have to do some fancy math to determine average ping time and use that to offset the start time when the client receives a next turn message.

---
Tags: client-server, turn-based, timer, synchronization
---


title: Making 2D Games

text:
# Question
Title: Making 2D Games
I am starting out on making my own games. I am very interested in making 2D side scrolling games, such as SNES/Mega Drive games and eventually I want to create my own Metroid/Cave Story inspired game.

However I don't want to just use a program that will do all the work for me, I want to learn and improve my programming skills as I go along also.

I was wondering if you had any suggestions of how to go about this, I would be really grateful for some answers :)

Also any suggestions on what programming language I should use, would be helpful, as I've been told either C++ or Java

Thank you

James

# Answer
> 1 votes
start with Java, it's going to be A TON easier than c++. although c++ doesn't have any dependencies, java is better to start out with when creating a game like you've described.

c++ honestly wouldn't be necessary in this case

# Answer
> 1 votes
If C# is an alernative ( it is quite similar to Java ) you could check out C#/XNA. It's very easy to make games in it. It helps you with several topics such as intersection, sprites and audio. But you will handle all the logics yourself.

C#/XNA will be easy to start with. Make a few games with it. If you want to handle more of the game engine yourself, you could move on to something different after a while.

# Answer
> 1 votes
Java is an excellent option to start with given the fact that you can put to good use that experience into creating games for Android if you want to. Besides, it's better to start with Java being strong-typed but developer-friendly when it comes to memory management. The best approach is to learn Java and Java2D. You can load your image files but have to work out the game loop on your own. After that, you can jump into Android game development.

I'd recommend making a couple old games: breakout, tetris, snake and then work with an API or Framework (like libGDX for Android). Why? Because it's better to write games than engines. Unless you're really interested in computer graphics, for example, there is little reason to make a whole complicated game using OpenGL and your language of choice, reinventing the wheel.

# Answer
> 1 votes
If you are very new to all of this I strongly recommend using Greenfoot, it is an environment for learning Java by making games. They have many tutorials and will ease you into Java and Game development.

http://www.greenfoot.org/door

---
Tags: c++, java, 2d, software-engineering
---


# Question
Title: How to create a path-finding compatible road map from user input?
I'm currently working on an agent simulation (inspired by the recent SimCity release). Now, basically I understood how agents work but I do not understand how to put them into context. Agents travel along roads on a map and pursue their own goals.

As in SimCity, I want the *player* to be able to create his own roads. If I used grids, I would run into a problem caused by user input: Imperfect grids will be created where two roads would need to share one "box". This would be even worse with bevels.

(Grey = Street, Orange = Agent *road*, Dots = Immobile Agents)

Is there another, more clever way of building a road map that would support this kind of map and is compatible with path-finding?

Thanks a lot!

Paul

# Answer
> 6 votes
You don't need to use a grid, you can easily extract node information from the roads (or keep it when placing roads). Path finding only cares about connectivity. Once you get to one node, which nodes can you go to next?

Red dots are nodes in your path finding algorithm. The orange lines define their conectivity.

The Green agent wants to go from its current location to `K`. If finds a path along `G-H-I-J-K`. The Blue agents wants a path to `A`, it finds its path along `G-E-F-B-A`.

The grid is still useful for placing your nodes, as it keeps the spacing for regular sized buildings, helps the user make straight lines and so on. But I wouldn't use the grid for path finding, use the nodes that have been placed.

Nodes are created at each end point and each intersection. Agents not on a road can find the road nearest to them. Likely you'd want to force them to be connected to a road at some point, and may even want to create additional "minor" nodes for each connected structure or object that can contain agents.

---
Tags: movement, path-finding
---


# Question
Title: How do I draw something when the mouse is clicked?
Right now, I'm doing this:

```
public void buttonsClicked()
{
    if (lastMouseState.LeftButton == ButtonState.Released
    && currentMouseState.LeftButton == ButtonState.Pressed)
    {
        buttonWasClicked();
    }
 }

public void buttonWasClicked()
{
    MouseState mouseState = Mouse.GetState();
    spriteBatch.Begin();
    Vector2 pos = new Vector2(mouseState.X, mouseState.Y);
    spriteBatch.Draw(smallPotTexture, pos, Color.White);
    spriteBatch.End();
 }

```

I want this to draw `smallPotTexture` where I click. However, the above code doesn't work. What's the proper way to do this?

I'm guessing it has something to do with the fact that I use `spriteBatch.Begin`, maybe I'm not allowed to do that this way?

# Answer
> 3 votes
> I'm guessing it has something to do with the fact that I use spriteBatch.Begin, maybe I'm not allowed to do that this way?

You'd be correct. The `spriteBatch` should only be used from within a `Draw` method, and I'm guessing that `buttonWasClicked` is called from an `Update()` method?

You'll need to store some information in the `buttonWasClicked` method that can later be used in the `Draw()` method.

Note that infinite loops and sleeps should not be used in XNA. XNA (and most other game frameworks) uses a Game Loop which will call `Update` followed by `Draw` once per frame, over and over again. This gives a chance for everything to update and everything to draw. I would also avoid threads unless you really know what you're doing.

Ralph has given you the codez.

# Answer
> 1 votes
You actually need to draw your smallPotTexture in the protected override void Draw. So the best for you to do is.

```
    protected override void Update(GameTime gameTime)
    {
        MouseState mouseState = Mouse.GetState();
        if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
        {
            pos = new Vector2(mouseState.X, mouseState.Y);
        }

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        spriteBatch.Begin();
        spriteBatch.Draw(smallPotTexture, pos, Color.White);
        spriteBatch.End();
        base.Draw(gameTime);
    }

```

pos will be declared as a Vector2D above in the Game class

---
Tags: xna
---


# Question
Title: Create sprite and place in pre-defined places using mouse
So, I have a table. I want to be able to click on a button that allows a mode where I place a sprite on the table, on places that are predefined. How do I do that? I was thinking I could constantly update the mouseState when the button is pressed, and if the mouse is within a ceratin rectangle of a position where you can put it, it will snap to it and if you click, it will create a sprite in that position.

The thing is, I don't really know how to do this in practice.

Some guidance would be great!

# Answer
> 1 votes
I'm assuming your setup is similar to the following(however if it is not, you should be able to follow the following explanation)

If you want to display place-holder sprites (the faded-out sprites you were talking about) then you need either a list or an array to store the sprites positions, and draw them with the alpha value of your choice.

Add some rects to the chart as well. Make sure their width,height,and position are correct or else you might end up with some weird results in terms of dragging sprites onto the chart.

The logic behind dragging sprites is pretty simple - based on the your description. Let us assume that the 3 circles on the grey panel are sprites. The mouse needs to be able to know when it is hovering over these sprites(or buttons - however you want to think about them). I would recommend making a class that handles the dragging and placing of the 3 sprites for functionality.

Within this class you should define a Rect(meaning Rectangle) for these buttons. This class should also know when the mouse is on the image(meaning if the mouse is within the rect you have created for that image). If the mouse is on the image and the mouse is being clicked (with the left mouse button for example) then you should create a duplicate image of the sprite that has just been clicked. If the sprite is not within any of the Rects on the chart and the mouse button is released you should get rid of the texture. If the mouse is released and the mouse is within on of the rects on the chart then you should "snap" the sprites position to the rects position(maybe even scale the sprite based on the rects position if you want to be safe).

---
Tags: xna, sprites
---


title: Is GNU GCC used for AAA games?

text:
# Question
Title: Is GNU GCC used for AAA games?
GNU GCC is a very common compiler, but it seems like almost no one uses it for bigger projects like AAA games. To me, it's works just fine, never had a problem with it. But I wonder why all AAA games seem to use commercial compilers such as Intel Studio? Why does it matter? GNU GCC also optimizes the code for all systems rather then just Intel, so why do they bother with things such as Intel Studio?

# Answer
Intel's compiler is just a different compiler. GCC++ and VC++ produce production quality code, just as well as Intel's ICC does. The main difference lies in 4 key areas:

* a) Features supported (mostly differing on C++11 features)
* b) Executable size
* c) Runtime
* d) Compile time

When you're trying to squeeze every last bit of performance out of (mostly) Intel CPU's, AAA studios are willing to pay for that and some spring for ICC. See here for a great anecdotal story. Pay attention to his drawbacks section as well, where ICC is accused of running less-than-well on non-genuine Intel instruction set CPU's (e.g. AMD's).
> 9 votes

# Answer
Many non-PC platforms, including some consoles and handhelds, use a modified GCC as their primary/only compiler.

On the PC, most game dev houses just use Visual Studio's compiler. The choice of compiler typically has little impact on runtime speed compared to engine design and graphics, they all paid for Visual Studio anyway due to its feature set as an IDE, GCC is comparatively harder to install and get started with. and it doesn't do much to improve iteration time and productivity. There's just not a compelling enough of a reason to use GCC compared to the alternatives that everyone is already invested in.
> 10 votes

# Answer
Yes, it can be used for AA games.

The reason almost every AAA games out there (if not all) use commercial compilers is the fact that commercial products usually have support and you can complain or get help 24/7 or just ASAP when dealing with any problem you might have and in the AAA industry, times means money. Big teams and companies, specially the latter, don't want to rely on the community when big money is at stake. It's better to invest in support by contract.

On the other hand, the engines rely on SDKs. If the SDK don't support a compiler, it means that you are on your own and it's not profitable to do the workaround.

Finally, optimization. If you know that a lot of players use Intel, the heck you want to deliver your game graciously for them.
> 4 votes

---
Tags: c++, game-industry, c, mingw
---


title: For loop optimisation

text:
# Question
Title: For loop optimisation
Here are some variations of for loops:

1) Standard:

```
for (int i=0; i<limit; i++)

```

2) Using preincrement

```
for (int i=0; i<limit; ++i)

```

3) Inverting the loop

```
for (int i=limit-1; i>=0; i--)

```

4) Using preincrement in the test

```
for (int i=0; ++i<=limit; )

```

5) Mixing 3 and 4

```
for (int i=limit; --i>=0; )

```

So, my question is, should number 5 be used in the majority of cases? It seems highly optimised, but I am wary of gotchas. Could someone please shed some light onto what the compiler will do in these situations? Also, what will happen if i is an iterator, not an int? Or if i is unsigned? I am specifically interested in C++, but if there are differences with other languages, that would be highly interesting too. Thanks

# Answer
As much as I agree that preincrementing is intuitively faster (because the implementation does not involve a copy), I would expect the compiler to actually optimize both calls to become equivalent in a case where there is no ambiguity like that (preincrementing or postincrementing is irrelevant in the calculation).

Furthermore, I sincerely doubt that the for loop itself will become your bottleneck in a game. If you ask such a question because you notice performance problems in your project, then I would advise you to use a profiler (such as VerySleepy for C++) which will explicitly tell you where your program spends most of its time.

After that, you can try and optimize the code that really matters.

By spending time searching for small optimizations like that which will probably not bring any difference to the execution time (because it is not a bottleneck of your application), you are essentially wasting time that you could be spending optimizing bottlenecks. Which brings me back to saying this: *optimize your schedule before your code; profile first, optimize after.*

This being said, I assume that you are just asking this question by curiosity and wondering which one is faster. If this is what you seek, then your question would be more appropriate on StackOverflow, because it is not specifically related to optimization in game development.
> 5 votes

---
Tags: c++
---


# Question
Title: Collision detection problems using AABB's
I implemented a simple collision detection routine using AABB's between my main game sprite and various platforms (Please see code below). It works great, but I'm now introducing gravity to make my character fall and it's shown up some problems with my CD routine.

I think the crux of the matter is that my CD routine moves the sprite back along the axis in which it has penetrated the *least* amount into the other sprite. So, if it's more in the Y axis than the X, then it will move it back along the X Axis.

However, now my (hero) sprite is now falling at a rate of 30 pixels per frame (It's a 1504 high screen - I need it to fall this fast as I want to try to simulate 'normal' gravity, any slower just look weird) I'm getting these issues. I will try to show what is happening (and what I think is causing it - although I'm not sure) with a few pictures: (Code below pictures).

I would appreciate some suggestions on how to get around this issue.

**For clarification, in the above right picture, when I say the position is corrected 'incorrectly' that's maybe a bit misleading. The code itself is working correctly for how it is written, or put another way, the algorithm itself if behaving how I would expect it to, but I need to change it's behaviour to stop this problem happening, hope that clarifies my comments in the picture.**

**My Code**

```
public boolean heroWithPlatforms(){

    //Set Hero center for this frame
    heroCenterX  = hero.xScreen+(hero.quadWidth/2);
    heroCenterY  = hero.yScreen+(hero.quadHeight/2);

    //Iterate through all platforms to check for collisions
    for(x=0;x<platformCoords.length;x+=2){

    //Set platform Center for this iteration
    platformCenterX = platformCoords[x]+(platforms.quadWidth/2);
    platformCenterY = platformCoords[x+1]+(platforms.quadHeight/2);

    // the Dif variables are the difference (absolute value)
    // of the center of the two sprites being compared (one for X axis difference
    //and on for the Y axis difference)
    difX = Math.abs(heroCenterX-platformCenterX);
    difY = Math.abs(heroCenterY-platformCenterY);

    //If 1
    //Check the difference between the 2 centers and compare it to the vector (the sum of
    //the two sprite's widths/2.  If it is smaller, then the sprites are pverlapping along
    //the X axis and we can now proceed to check the Y axis
    if (difX<vecXPlatform){

    //If 2
    //Same as above but for the Y axis, if this is also true, then we have a collision
    if(difY<vecYPlatform){
        //we now know sprites are colliding, so we now need to know exactly by how much
        //penX will hold the value equal to the amount one sprite (hero, in this case)
        //has overlapped with the other sprite (the platform)
        penX = vecXPlatform-difX;
        penY = vecYPlatform-difY;
        //One sprite has penetrated into the other, mostly in the Y axis, so move sprite
        //back on the X Axis
        if (penX < penY){hero.xScreen-=penX*(heroCenterX-platformCenterX>=0 ? -1 : 1);}
        //Sprite has penetrated into the other, mostly in the X asis, so move sprite
        //back on the Y Axis
        else if (penY < penX) {hero.yScreen-=penY*(heroCenterY-platformCenterY>=0 ? -1 : 1);}
        return true;
        }//Close 'If' 2
        } //Close 'If' 1
    }
    //Otherwise, no collision

    return false;
    }

```

# Answer
during my experiments with HTML5 canvas and AABB I found exactly what you are experiencing. This did happen when I attempted to make a platform from adjacent boxes of 32x32 pixels.

**Solutions I attempted by order of my personal preference**

**1 - Divide movements by axis**

My current one, and I think I will continue my game with it. But be sure to check what I call **Phantom AABB** if you need a quick solution without having to modify a lot your current design.

My game world has very simple physics. There is no concept of forces (yet), only displacement. Gravity is a constant displacement to down. No acceleration (yet).

Displacement are applied by axis. And in this consist this first solution.

Each game frame:

```
player.moves.y += gravity;
player.moves.x += move_x;

```

move\_x is set according to input processing, if not arrow key pressed then move\_x = 0. Vales below zero mean left, otherwise to the right.

Process all other moving sprites and decide the values of their "moves" component, they have the "moves" component too.

Note: after collision detection and response, the move component must be set to zero, both x and y properties, because the next tick the gravity will be added again. If you not reset, you will end with a moves.y of two times the desired gravity, and in the next tick it will be three times.

Then enter the displacement applying and collision detection code.

The moves component is not really the current position of the sprite. The sprite has not moved yet even if moves.x or y changed. The "moves" component is a way to save displacement to be applied to sprite position in the correct part of the game loop.

Process first the y axis (moves.y). Apply moves.y to sprite.position.y. Then apply AABB method to see if the moving sprite being processed is overlapping a platform AABB (you already understood how to do this). If it overlaps then move the sprite back in the y axis by applying penetration.y. Yes, as opposed to my other answer, now this move evolved method ignores the penetration.x, for this step of the process. And we use the penetration.y even if it is greater than penetration.x, we aren't even checking for it.

Then process the x axis (moves.x). Apply moves.x to sprite.position.x. And do the opposite than before. You will move the sprite only in the horizontal axis this time by applying penetration.x. As before, you don't care if penetration.x is less or greater than penetration.y.

The concept here, is that if the sprite is not moving, and was initially not colliding, then it will remain like that in the next frame (sprite.moves.x and y are zero). The special case where another game object magically teleports to a position that overlaps the sprite begin processed is something I will handle later.

When a sprite begin to move. If it moving only in the x axis, then we are only interested if it penetrates something by the left or the right. As the sprite is not moving down, and we know this because the y property of the moves component is zero, we don't even check the calculated value for the penetration.y, we only see at penetration.x. If penetration exist in the axis of movement, we apply correction, otherwise we simply let the sprite move.

**What about diagonal displacement, not necessarily in a 45 degrees angle?**

The proposed system can handle it. You only need to process each axis separately. During your simulation. Different forces are applied to the sprite. Even if your engine does not understand forces yet. These forces translates to an arbitrary displacement in the 2D plane, this displacement is a 2D vector in any direction and of any length. From this vector you can extract the y axis and the x axis.

What to do if the displacement vector is too large?

You don't want this:

```
|
|
|
|
|
|
|
|_ _ _ _ _ _ _ _ _

```

As our new moves applying logic process an axis first and then the other, a large displacement may end being saw by the collision code like a big L, this won't correctly detect collisions with objects that are intersecting your displacement vector.

The solution is to divide large displacements in small steps, ideally your sprite width or height, or half your sprite width or height. To obtain something like this:

```
|_
  |_
    |_
      |_
        |_
          |_
            |_
              |_

```

**What about teleporting sprites?**

If you represent teleporting as a large displacement, using the same moves component as a normal move, then no problem. If you don't, then you have to think a way to mark the teleporting sprite to be processed by the collision code (adding to a list dedicated to this purpose?), during response code you can directly displace the standing sprite that was in the way when the teleportation occurred.

**2 - Phantom AABB**

Have a secondary AABB for each sprite affected by gravity that starts at the sprite bottom, has the same width of the sprite AABB, and 1 pixel height.

The idea here is that this phantom AABB is always colliding with the platform below the sprite. Only when this phantom AABB is not overlapping anything gravity is allowed to be applied to the sprite.

You don't need to calculate penetration vector for the phantom AABB and the platform. You only interested in a simple collision test, if it overlaps a platform, gravity cannot be applied. Your sprite can have a boolean property that tells if it is over a platform or in the air. You are in the air when your phantom AABB is not colliding with a platform below the player.

This:

```
player.position.y += gravity;

```

Becomes something like this:

```
if (player.onGround == false) player.position.y += gravity;

```

Very simple and reliably.

You leave your AABB implementation as is.

The phantom AABB may have a dedicated loop that process them, that only check for simple collisions, and do not waste time calculating the penetration vector. This loop must be before the normal collision and response code. You may apply gravity during this loop, for those sprites on the air apply gravity. If the phantom AABB is in itself a class or structure, it may have a reference to the sprite it belongs to.

This is very similar to the other proposed solution where you check if your player is jumping. I giving a possible way of detect if the player has its feet over a platform.
> 1 votes

# Answer
I would combine the platform tiles into a single platform entity.

For example, say you take the 3 tiles from the pictures and combine them into a single entity, your entity would have a collision box of:

```
Left   = box1.left
Right  = box3.right
Top    = box1.top
Bottom = box1.bottom

```

Using that for collision will give you the y as the least penetrating axis throughout most of the platform while still allowing you to have specific tiles within the platform.
> 5 votes

# Answer
Problems like these are common with new collision detection methods.

I don't know too much about your current collision setup, but here is how it should go:

First off, make these variables:

1. Make a X and Y velocity
2. Make a Gravity
3. Make a jumpSpeed
4. Make a isJumping

Second off, make a timer to calculate the delta to affect the velocity of the object.

Third off, do this:

1. Check if the player is pressing the jumping button and isn't jumping, if so add jumpSpeed to the Y velocity.
2. Subtract gravity from the Y velocity each update to simulate gravity
3. If the player y + height is smaller then or equal to the y of the platform, set the Y velocity to 0 and put the player's Y to the platform's y + the player's height.

If you do this, there shouldn't be any problem. Hope this helps!
> 0 votes

---
Tags: android, collision-detection, vector, bounding-boxes, aabb
---


title: XNA Scale and Render Targets

text:
# Question
Title: XNA Scale and Render Targets
I'm working on a top down Strategy/RPG/Tower Defense XNA Game for Windows, and I'm running into an issue while scaling.

My display mode is 1680 X 1050, and that is what I'm setting the PreferredBackBuffer width and height to.

What I'm finding is that when I use my camera object to zoom in and out (changing the scale on a matrix that is passed to the SpriteBatch.Begin method, it changes the scale of my sprites... but I'm still confined to the BackBuffer (0,0,1680,1050)...

Can I use something like a RenderTarget to extend the actual area that is accessible when zooming/panning across the "map"?

I'm looking at making it something like 5000 X 3125...

Any thoughts/examples of how I should approach this?

I've added a video of what I'm experiencing... http://www.youtube.com/watch?v=jIiAeXbAnec

For the record I have also posted this question on Stack Exchange - Stack Overflow

# Answer
> 2 votes
If I understand you correctly, the coordinates you are getting from `Mouse.GetState()` always fall within the bounds of the screen (ie: 0 \< x \< 1680 and 0 \< y \< 1050).

This is normal.

The transformation matrix you are using is taking coordinates in "**world space**" and putting them in "**client space**" (which is the space that `SpriteBatch` then uses to project sprites onto the screen).

`Mouse.GetState()` also returns coordinates in client space. What you want is to find what position those client coordinates represent in world space. So what you have to do is *reverse* the transformation. Here is some (untested) code that shows you how:

```
MouseState mouseState = Mouse.GetState();
Matrix transform = whatever;
Matrix inverseTransform = Matrix.Invert(transform);
Vector2 clientMouse = new Vector2(mouseState.X, mouseState.Y);
Vector2 worldMouse = Vector2.Transform(clientMouse, inverseTransform);

```

(Note: If you get NaN errors, make sure you're not scaling your Z coordinate down to zero, see here.)

---
Tags: c#, xna-4.0, rendertargets, scale
---


# Question
Title: Get MonoBehaviour components from Prefab
I need to assign the script values for the following Prefab in Unity 3.5

```
The structure is the following

```

Kinect\_Prefab

```
 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

 -MonoBehaviour

    ·Script: Missing Mono Script

```

All the components have the same name.

I have tried to obtain all of them in an array, but the `GetComponents` method does not seem to work properly.

```
var mono : MonoBehaviour[];
mono = Kinect_Prefab.GetComponents(MonoBehaviour);

```

The thing is the resulting array is empty.

Any idea what might be wrong?

EDIT: When I do GetComponents(MonoBehaviour) I get the following error

`InvalidCastException: Cannot cast from source type to destination type.`

I have tried receiving the components in var mono : Component \[\] but I still don't receive anything

# Answer
> 0 votes
I might be completely off... but it seems like you have no scripts attached to the `Kinect_Prefab` \- that's why it says `Script: Missing Mono Script`. This means that scripts were previously attached but they were deleted (did you rename them?)

What you have to do, is remove all the existing script components that say that a script is missing, and attach new ones (by dragging scripts on to the prefab object):

Once you've done that, your other scripts will be able to access the `MonoBehavior` objects of the attached scripts.

---
Tags: unity, javascript
---