title: Issues with Polygon Fixtures in Farseer

text:
# Question
Title: Issues with Polygon Fixtures in Farseer
I've been working with the Farseer Physics Engine (which since posting has become Velcro Physics) to try and build a simple 2D, sidescrolling game. Creating basic rectangle blocks worked easily enough, but I discovered when I tried to create some very simple triangle slopes that my existing 'character' avatar would not collide with them. This baffled me for a while until I began using the debug view to discover that while the body of the triangle appeared where I had placed them, the fixture which determined collisions was offset, as shown below (The debugging view is itself offset from the actual sprites because I'm clearly not smart enough to figure out the proper projection matrix):.

It turns out that whatever coordinates I give for the center of the triangle, the fixture appears at (2x, 2y). For example, in the attached image, there is a triangle sloping up to the left at (-4, -1) in the game's coordinate system. The fixture (light green triangle bordered in magenta) is at (-8, -2).

I know this has to be a simple mistake I'm making, but damned if I can figure it out. Here's how I create a new slope in the level:

```
public override void AddToWorld(FarseerPhysics.Dynamics.World world, Vector2 position)
        {
            body = BodyFactory.CreateBody(world, position);
            body.BodyType = FarseerPhysics.Dynamics.BodyType.Static;

            Vertices vertices = new Vertices();
            if (type == SlopeType.LEFT)
            {
                vertices.Add(new Vector2(position.X - 0.5f, position.Y - 0.5f));
            }
            else
            {
                vertices.Add(new Vector2(position.X + 0.5f, position.Y - 0.5f));
            }
            vertices.Add(new Vector2(Position.X + 0.5f, position.Y + 0.5f));
            vertices.Add(new Vector2(position.X - 0.5f, position.Y + 0.5f));

            FixtureFactory.AttachPolygon(vertices, 1f, body, this);

        }

```

The position parameter is given to be the center, thus the 0.5 offsets to create the triangle's edges.

Any insight would be greatly appreciated; this engine seems powerful but the documentation is definitely lacking.

# Answer
> 4 votes
You are creating a body and attaching a fixture at body-local position e.g. (10, 10).

But the body was created at world position (10, 10). That means the fixture is now at (10, 10) + (10, 10) = (20, 20).

Fixtures are always specified in body-local space; they should be roughly around the (0, 0) area regardless of where you intend to move the body.

---
Tags: box2d, farseer-physics-engine
---


# Question
Title: Vector Art Tool: Size, Position, Shapes, Symbols
I'm looking for a vector art tool for gameart, similar to Flash, but preferably free. It just needs the following capabilities:

* Create vector images (can scale up/down without losing quality)
* Specify shape X/Y to the pixel (eg. set the X to 24.1, like in Flash)
* Draw primitive shapes (square/circle/triangle) with border and colour (or gradient)
* Specify shape width/height in precise pixels
* Export to PNG

Flash can do all this, but it's expensive (and heavy to install). Is there a free alternative that I can use?

This is NOT for pixely, pixel-style art.

# Answer
I guess inkscape is the answer! I downloaded it last night, it does seem like a really nice program. I don't know a lot about it, but I'm fairly sure it does all the things you want it to.
> 5 votes

# Answer
Inkscape: http://inkscape.org/ Seriously, how does everyone know about Sketch-Up but not Inkscape?! It's like the only good free SVG editor ffs!
> 1 votes

# Answer
The web alternativeto is a good place to find alternatives similar to a program.

These are the free alternatives to inkscape, that seems to be the free vector graphics editor reference:
> 0 votes

---
Tags: 2d, tools, vector-art
---


title: Profanity filter for an MMO chat

text:
# Question
Title: Profanity filter for an MMO chat
We are developing an MMO using Smartfox Server. The targeted audience is kids from 7 -12 years.

There is a global chat option in this MMO.
Whatever the user types in a textbox get displayed next to users avatar after he/she hits enter.

We would like to filter abusive language / profanities from this chat.
We could capture the chat and read the text. The problem is getting the list of profanities itself.

Our questions are

1. Where will one get exhaustive list of all profanities?
2. What method is adopted in similar scenario to filter out these?

# Answer
> 46 votes
**Don't.**

**Filters don't work.** At least, *only* filters don't work. Whitelists, blacklists, it doesn't matter. Neither of these will ever prevent kids from harassing each other. The only way to make this work would be to not filter the chat, but to provide large building-blocks for sentences. For example, a kid might select "Do you want to..." and the options for "go to..." and "trade..." would be pulled up. Selecting "go to..." would bring up a list of places in the game.

Disney settled on this method for their MMO "Toontown", after their 14-year old whitelist test subject decided to "stick \[his\] long-necked Giraffe up \[their\] fluffy white bunny." Simply put, you *cannot* blacklist or whitelist enough words to prevent abuse.

---

That all being said, if I were designing a kid's MMO, I would actually implement a stringent blacklist filter, but only as a second line of defense. Your first line of defense should always be moderators and the ability to report abuse. I would weight blacklisted words, with each user getting a secret score of how profane they are trying to be.

Chances are, any user who will try and circumvent your filter will trigger it first. The more obvious profanities, (as opposed to obscure or outdated ones,) or more repeated profanity attempts, put them on a watch list for moderators, or some sort of ban list. This way, moderators can focus on users who seem to be trying to harass others instead of wasting their time reading the comments of still-innocent kids.

# Answer
> 10 votes
In response to people saying to **not** provide the filter, I would argue that you **have to** provide a filter, for no other reason than to cover your own butt with respect to the parents of your intended audience. Just make sure it can be disabled by the user. By implementing a profanity filter (albeit an imperfect and totally optional one), you can say that you've done everything expected of you to protect the sensibilities of your younger audience.

By making it possible to disable, you discourage users from trying to circumvent it using clever punctuation or substitution, since people who favor that sort of language will immediately disable the filter on their own computers, and will have long since forgotten that a filter even exists.

With that understanding, don't worry so much about the implementation. It doesn't need to be foolproof (which is good, because it *can't* be foolproof), but it should be relatively complete and as un-intrusive as possible. That is, you wan't to make sure you don't make the "clbuttic mistake".

The implementation can be extremely simple -- get a word list, and replace any words found in the list with asterisks or something similar. Best to search for whole words only, as well.

As for a word list, that's easy: http://www.google.com/search?q=profanity+word+list

Remember, it doesn't have to be all-inclusive, it just has to be representative of a valiant effort on your part to protect the children.

# Answer
> 4 votes
As I commented, filtering all offensive words is really hard - but you could turn it around, and use a **whitelist** of *allowed* words. Doing a google search, it seems fairly common for children's game to limit what they can type to a list. For instance, Lego Universe uses a whitelist.

Also see: Whitelisting for game chat. And note that whitelists can be circumvented. There is no guaranteed solution.

Considering that it's for young children, and mis-spelling could be a problem - depending on the client interface, you might consider word auto-completion. As the players start typing letters, offer a list of possible words and let them select the correct one.

# Answer
> 4 votes
I would try to implement a solution allowing for a blacklist and a whitelist, where you could add 'cunt' to the blacklist, and 'scunthorpe' to the whitelist for example.

I don't believe that you could *ever* implement a failsafe solution, so I'd try to get the most "popular" words in your dictionary, and make it as easy as possible to add new words to the lists.

The reason for this is that languages, especially english, constantly evolve and something that has been inoffensive for decades could become offensive in the right context.

Try to get the most words possible and go from there, have quick reaction times when people complain and show that this is generally a concern and I doubt you'll have any problems.

It would be a good idea to know exactly what the guidelines are for censorship in the US: MBNL! (me be no lawyer!)

# Answer
> 4 votes
There's an answer from Programmers describing one system for building a profanity filter. He doesn't explain how he actually built it in great detail, but it should be enough to get an idea for implementation.

# Answer
> 4 votes
This is a problem best solved by humans and social design rather than code.

Your best source for an exhaustive list is a live human who is present in the game and monitoring the chat stream. Put people in your game and let them be your ultimate filter.

Spend some time looking into Lane Merrifield's ideas and philosophies behind Club Penguin and about providing service. Here are two writeups from his presentation at the Austin GDC in 2008. I saw it and remember being very impressed with his style of solving human problems with humans and not code.

http://gamasutra.com/php-bin/news\_index.php?story=20234

http://www.raphkoster.com/2008/09/15/agdc08-lane-merrifield-at-their-service/

Specifically because your game is aimed at kids, it's more than just swear filters you'll need to think about. You'll need to worry about people posing as kids who may or may not have bad motives. You'll need to assure parents that their kids are safe. You'll need to assure kids that they are safe too for that matter.

Another plus for humans is that they will understand context. You don't want some kid saying, "My Mom has breast cancer" and getting kicked.

# Answer
> 3 votes
Simple solution to the problem:

1. Remove all spaces and punctuation from your input.
2. Blacklist everything in the Urban Dictionary.
3. Blacklist all homophones etc
4. Blacklist everything that could be use as a euphamism.
5. Write your software to understand the content, intention and tone of what is left.
6. Throw away game and go to market with sentient and omniscient creation from step 5.

# Answer
> 3 votes
Some MMOs for children simply replace chat with a predefined list of emotes and phrases and simply doesn't allow free-form chat. Perhaps the game could be designed to accommodate that.

---
Tags: mmo
---


title: PC game update systems

text:
# Question
Title: PC game update systems
I've almost finished a PC game (I'm releasing it in a day or two). I'd like a way to easily release patches over the net in case I find a bug in the game right after release, or in case I want to add features later on.

I am using *InstallJammer* as my install system. Are there good update/patch programs (preferably free) which can check for and send updates to players over the Internet?

For instance, if a player opens my game, the game first starts the update program that checks for updates. If updates are available, it will let the user know where to get it. I can modify the source code to the game engine I own, but I'd prefer not to re-invent the wheel.

# Answer
Thanks for all of the help guys, but after some looking around, I found a really good updater. It's called Puchisoft Dispatcher. They have a freeware version, and it is really good for non-commercial projects.
> 5 votes

# Answer
May be overkill, but RakNet includes an autopatcher system:

> The autopatcher is a class that manages the copying of missing or changed files between two or more systems. It handles transferring files, compressing transferred files, security, and file operations. It does not handle basic connectivity or provide a user interface.
> 3 votes

# Answer
If you game is very data orientated, it could be easy to make your own loader to verify and download data from a server, then launch the game. It shouldn't take too long in a managed language.

I made one a while back where the client downloaded a map of what the game folder shoulld look like, files, md5's, etc. And then looked through local files to see which ones it needed to download from the server.

Not very secure or optimized, but you get the point.

I also recall in my youth using Patch Maker by Clickteam. I'm not sure what it's capabilities are nowadays but it's free and can update binary files, you just distribute it as a setup file.

Maybe some of the bigger install tools allow you to create manual patches, Inno Setup is free and quite complete, maybe you may have more luck there.
> 2 votes

---
Tags: deployment, patching
---


# Question
Title: How to create a game save file format in c++ using STL
Hey so i just learned about the i/o part of the STL, more specifically fstream. Although I can now save binary info and classes i've made to the hard drive, i am not sure how to define how the info should be read.

I saw the answer for making a file format from \[this\]\[1\] post:

> Typically you would define a lot of records/structures, such as BITMAPINFOHEADER, and specify in what order they should come, how they should be nestled, and you might need to write a lot of indicies and look-up tables. Such files consists of a number of records (maybe nestled), look-up tables, magic words (indicating structure begin, structures end, etc.) and strings in a custom-defined format.

What i want to know specifcally is how to do this with **the STL and C++...** Since the format is meant simply for the use of a game i would think it would be much easier though. The format should:

* Be traversable (i can look through it and find the start of structure and maybe check it's name
* Be able to hold multiple classes and data in a single file
* have identifiable starts and ends to sections: such as the space in text files
* Maybe have it's own icon to represent it??

**How do i do this in c++ ?**

# Answer
> 9 votes
try using boost serialize! other than that what you are asking for is how to implement serialization and that's a real complicated thing! I've recently implemented an implementation for serialization and it's no easy case to talk about.

there is also another way to only save one class into file which contains all the information you need, which makes saving/loading classes much more simpler.

by the way icon is not anything related to file format it's something OS generates per file, and usually icons are stored somewhere between OS files. except for windows executable files(as far as I know). windows executable files are like a zipped folder, containing the actual binary operations, icon data for some various resolutions, and maybe some other data related to OS itself.

---
Tags: c++, file-format, data-structure, file
---


title: velocity question from book iPhone

text:
# Question
Title: velocity question from book iPhone
I am reading an iphone game dev book and I have a question about velocity.

mainly it is this line

```
playerVelocity = ccp(playerVelocity.x * dec + acceleration.x * sens, 0);

```

Why do you mutiple the playerVelocity.x by the deceleration. the book says it works by reducing the current velocity so it is easier to change direction and then add the ( acceleration.x * sens. )

this piece of code is using the accelerometer.

```
float dec = 0.4f; //lower = quicker to change direction;
float sens = 6.0f; //higher more sensitive;
float maxVel = 100;

playerVelocity = ccp(playerVelocity.x * dec + acceleration.x * sens, 0);
NSLog(@"%@", NSStringFromCGPoint(playerVelocity));

if(playerVelocity.x > maxVel)
{
    playerVelocity.x = maxVel;
}
else if(playerVelocity.x < - maxVel)
{
    playerVelocity.x = - maxVel;
}

```

# Answer
> 1 votes
by acceleration I think you are referring to the value IPhone accecelometer returns.

dec value may be used for two reasons :

1. to simulate friction.
2. to make velocity changes more smooth.

dec value also creates some upper and lower bounds for player velocity. note that if `-1 < acceleration.x < 1` we can assume velocity should be somewhere between -10 and 10.

for more information I need to know the code other than that lines.

---
Tags: iphone, cocos2d-iphone
---


# Question
Title: is it possible to make a MMO starting with scalable hosting?
I made a really basic 2D RPG. I want to know whether I can turn it into a free to play MMO.

I cannot afford to rent a server with enough capacity to serve a big number of players but I'm wondering whether I could get a hosting plan that starts cheap but scales enough to eventually handle a big numer of users so I have minimum fixed costs and I can cover expenses on the go with ads or whatever.

Is there such a thing? Thanks

# Answer
> 3 votes
I'm running my 3D (m)MORPG off of a cheap mono core Atom server (~18€/month) and if ever I get a lot of players I'll just hire a bigger server (a recent bi-quad Intel will be more than 50 times more powerful). Actually, even the Atom is overkill ATM so just go with what you can.

That said, I don't know what language you are using nor what kind of framework you have (Is it inhouse? Is it effective?).

# Answer
> 1 votes
I think you should consider google's app engine. It uses google infrastructure, is fast and was proven to be fast enough for handling real-time game. It is simply scalable and you can use it for free at the begining, when the trafic starts to be bigger, you start to pay.

---
Tags: mmo, server, hosting
---


title: Maintaining Consistent Scale (2D games)

text:
# Question
Title: Maintaining Consistent Scale (2D games)
How do people making 2D games maintain a consistent scale for everything in their game?

Say I'm coding an RPG. A house needs to be proportionally bigger than a person; an item, smaller. Everything from enemies to locations to people.

Is there a technique to doing this -- like picking a single item like the player sprite and scaling everything relative to that?

# Answer
> 8 votes
There's no real technique as such. The easiest way is to have a set pixel:real world units scale. If your character is 90 pixels tall, you'd have your ratio at about 45:1 in metres (assume your character is 1.8m, or 6 feet~).

Then you can build everything from this. Your house may be 10m wide, so it would need to be 450 pixels in width.

The main thing here is to build a single scale which is independent of what you started it from. It's easier to work with '10m in real objects is X pixels' than '10m in real objects is X times the player height'. What if you switch to a dwarf?

# Answer
> 4 votes
I agree with The Communist Duck, but there are other issues. Generally in 2D RPG and strategy games, closed areas and areas that access thru doors are smaller than what it should be. You may need to do that as well to make your towns smaller and easier to navigate. Similarly and potion would be bigger than what it should be to allow user to see and pick it up. Citing The Communist Duck's answer, a potion of 10cm hight will be 5 pixels. So the scale cannot be consistent all the time.

Most of the time these does not apply to 3D RPGs.

---
Tags: 2d, world-design
---


title: Recognizing a hexagonal clickbox

text:
# Question
Title: Recognizing a hexagonal clickbox
I'm working on a game that is going to involve *gasp* hexagons.

At present, I have a hexagon image that I am using (all sides are the same length...it fits into a 50px by 50px image).

I am somewhat new to C# and really new to XNA, but is there some sort of easy method that I can call rather than doing a convoluted if statement based on points and angles?

# Answer
A hexagon is a rectangle with clipped corners. The way I've seen this done, and I've heard the Civilization series does it this way with orthogonal maps, is to create a bitmap with a white space (orthogonal or hexagonal), and a red, green, blue, and yellow corner. (Or whatever colors you like.)

Hexagonal: or

Orthogonal:

Then, just determine which rectangle the cursor is over, and test the color of the pixel at that location. If it's white, they're hovering over that space. Each other color is mapped to an offset, and they're hovering over that hexagon instead. This way is efficient, takes little geometry, and can be used for any arbitrarily tessellating space.
> 18 votes

# Answer
There's no XNA method that does a hexagon hit test.

This article explains how to write a function that does the test, and gives you the function:

**How to Check if a Point is Inside a Hexagon**

Here is a summary from that article:

And the function that does the test goes like this:

1. Test the bounding box around the hexagon, early out if it does not intersect it.
2. Transform the point into a local quadrant as shown above.
3. Perform the following `isInside` test for the local quadrant.

---

```
public function isInside(pos:Vec2Const):Boolean
{
    const q2x:Number = Math.abs(pos.x - _center.x);
    const q2y:Number = Math.abs(pos.y - _center.y);
    if (q2x > _hori || q2y > _vert*2)
        return false;
    return 2 * _vert * _hori - _vert * q2x - _hori * q2y >= 0;
}

```

See the article for full details.

---

Here are some other useful related sources:
> 18 votes

# Answer
Here i got a method that can be used to detect clicks inside any polygon:

```
public bool PointInPolygon( Vector2 p, Vector2[] poly )
    {
        Vector2 p1, p2;
        bool inside = false;

        if( poly.Length < 3 )
        {
            return inside;
        }

        Vector2 oldPoint = new Vector2( poly[poly.Length - 1].X, poly[poly.Length - 1].Y );

        for( int i = 0; i < poly.Length; i++ )
        {
            Vector2 newPoint = new Vector2( poly[i].X, poly[i].Y );

            if( newPoint.X > oldPoint.X )
            {
                p1 = oldPoint;
                p2 = newPoint;
            }
            else
            {
                p1 = newPoint;
                p2 = oldPoint;
            }

            if( ( newPoint.X < p.X ) == ( p.X <= oldPoint.X )
                && ( (long)p.Y - (long)p1.Y ) * (long)( p2.X - p1.X )
                 < ( (long)p2.Y - (long)p1.Y ) * (long)( p.X - p1.X ) )
            {
                inside = !inside;
            }

            oldPoint = newPoint;
        }

        return inside;
    }

```

You need to give the corners of your hexagon in a vector2 array (poly) and the clicked position (p) to the method.
> 1 votes

---
Tags: c#, xna, hexagonal-grid
---


title: What are the Elements of an MMO Game?

text:
# Question
Title: What are the Elements of an MMO Game?
I would really appreciate it if there aren't any answers like "Making MMOs is too expensive", "Don't even try making an MMO!" etc.

I'm trying to point out the elements/jobs that establish an MMO game.

So, Here's what I've come up with:

1. **Server Engine Design** -
some daemon that gets players' actions and returns "what happens".
e.g Client says: "I hit the monster".
Server says: "You inflict 2 Damage".
2. **Database Design** \- The Server also needs to store all the information in a DB.
3. **Client Software Design** \- probably mainly in charge of displaying graphics,
4. **Game-play Design** \- Writing the storyline, balancing the different character classes, the game's internal economic system, designing the entire game world - a big one :)
5. **Graphic Design** \- Creating all the graphics.
6. **Customer Support** \- To interact with the users, get feedback etc.
7. **Artificial Intelligence** \- program the A.I for NPCs

Some may not be in low-budget games.
Nonetheless, is there more elements/jobs required for an MMO Game?

I know this is a big question but I hope a lot of motivated Game Designers like me will read this question and it will help them.

Regards, fiftyeight

# Answer
> 3 votes
Some stuff off the top of my head. Note that in real game development with large teams, people will often cross roles, so that more than one person does a task and a person does more than one task.

Audio. Voice acting, music, sound effects, and so on.

Graphics programming. Distinct from programming the core features of the client application and drawing/modelling the art. Someone needs to develop shaders and special graphical techniques.

Web design and development. No MMO is complete without a web presence.

Management. Someone needs to coordinate between the different groups and make sure they are able to do their jobs.

Accounting. MMOs are complicated when it comes to money, especially in these days of free-to-play.

Documentation. Hundreds of help files, internal documents, and tutorial bubbles.

Localization. Do you want non-English speakers to play? You'll need a decent translator.

Marketing. Distinct from customer support. Marketing gets players to your game.

I would split "server engine design" into several chunks. The person who designs the back-end data models is probably not the person who focuses on managing the massive data replication and distribution issues with real-time MMOs.

Like Aerathis said, Gameplay Design needs to be split up. Your User Experience person will not be your story writer will not be your low-level gameplay designer will not be your economist (and so on for the mapper, the person who designs and balances classes, and so on).

# Answer
> 6 votes
The only feature that distinguishes an MMO from any other type of game, online or not, is **lots of players** that can interact with each other in the same world. Everything else is simply "what are the elements of a game?"

# Answer
> 2 votes
QA. For a project this size QA is definitely worth mentioning, since this is the size of project where it's going to make a very large difference. Also I, personally, would probably break Game-play Design up into several jobs. You are definitely right that it is certainly a big one, but it's definitely large enough that you're going to want separate people doing combat and systems and story scripting, things like that.

# Answer
> 0 votes
You will likely also have a need for Managing the servers, a sort of SYSADMIN. So when the need arises, hire a new server (hardware) and infuse it with database, server (software) etc., fusioning servers if that need arises + backup strategies, maintaining the OS and so on.

You'd like to have some sort of security strategy too, complicated as it spans several domains (the server soft of course, connections and reliability of the physical server, web services and even ingame hacks and exploits).

---
Tags: mmo, project-management
---


# Question
Title: Avoiding impossible states in an adventure game
I'm looking at creating a fairly complex choose-your-own adventure style of game, but I'm looking for a technique or method to help with the game design.

It will be a multi-branching story, and at times the branches will fold back in on themselves, and your major actions will be remembered and items will be collected. For example, if the player goes to the swamp and the forest before going to the castle he has picked up a dinosaur bone, killed a unicorn and grown an extra arm. If a player gets to the castle via the caves and the crypt he has picked up a bicycle and a strange smell. Now when developing puzzles for the castle I don't want to create a situation where two impossibilities are requires, for example - an extra arm and the smell are needed to kill an ogre.

Other than documenting the events and items very very carefully is there a process, a technique I can use in a spreadsheet or a piece of software that can help me?

# Answer
> 11 votes
Sounds kind of like a directed graph problem.

Start at the beginning, for each branching in the story record the items you currently have and then branch the graph. From there follow each branch and do the same, once you get to another branch record your current items and branch the graph. This will end up with a pretty dense graph with lots of duplicated nodes (but each node got there from a different graph sequence) but you should get no loops.

At the end you should have a graph of all the items you can have at any given point in your story and from all possible ways to get there.

Now, with your completed graph: for each of your problems that require items X+Y+Z find all the nodes that have that problem and see if the items recorded can satisfy that condition. If there's a failure simply walk back up the graph to find all the decisions that got you there without the proper items to solve that problem.

With any luck your original design is already laid out like this, at least conceptually, so the code should mirror reality and be easy to verify.

The processing time of the graph searches might get a bit heavy if you're building a large game, so build this like a utility that can take a while to run and outputs results into a report for you to use.

# Answer
> 0 votes
this may seem an odd answer but you can easily check for impossible events using compilers (for example c++)! let me explain how: you have exactly one header file for every stage. and game ends in `main.cpp` file. whenever you can go from `stage a` to `stage b`, you just have to include file relate to `stage a` in `stage b`. whenever you get a new item in a stage you just define a value for that item. whenever you lost or use an item you just have to undef it. in the end in each stage you just have to use all the defined values for the items needed in that stage. here is a sample how to use this in code :

a.h

```
#define itemA

```

b.h

```
#include <a.h>
#undef itemA
#define itemB

```

c.h

```
#include <a.h>

itemA;

#include <b.h>

itemB;

```

main.cpp

```
#include <c.h>
int main()
{
}

```

although it may need some changes before really used but i guess you can create some code like this. you can also use inheritance and use classes for each stage instead of the approach i suggested. other than these i think you have to develop a tool yourself.

---
Tags: puzzle, adventure-games
---


# Question
Title: Count number of CCSprite added to a CCLayer
Does cocos2d has a method that returns the amount of CCSprites added to a CCLayer?

A have SceneControlLayer object, and I added some CCSprites to it.

```
@interface SceneControlLayer : CCLayer {
}

@implementation SceneControlLayer

-(id)init {

CCSprite *spr1 = [CCSprite spriteWithFile:@"spr1.png];
[self addChild:spr1 z:1 tag:1];

CCSprite *spr2 = [CCSprite spriteWithFile:@"spr2.png];
[self addChild:spr2 z:2 tag:2];

...

}
@end

```

How do I retrieve an array of sprites added to the layer? Could I retrieve all the objects added through addChild and test its type?

Since I'm starting with cocos2d/objectivec, please, give some examples how to do it...

I also thought that I could create an array, and, besides adding it to the layer, add it to the array also. But I'm not so sure if it's a good option.

TIA,

Bob

# Answer
> 4 votes
Every `CCNode` has a `children` property, which is a CCArray, containing all children. Since `CCLayer` is a subclass of `CCNode`, you can get the number of children added to the layer using: `[[layer children] count]`

**Update:** If you're not checking that sprite count very frequently, you can simply iterate through the `children` array and count the number of children that are actually sprites (using `isKindOfClass`). If you need to access these sprites constantly (eg. in every update) it would probably be wiser to also store them in a separate array.

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


title: Would a box2D sensor fit my needs?

text:
# Question
Title: Would a box2D sensor fit my needs?
I have a object in my game that when the main character hits it, all I want to do is have the object explode and then notify the character object that a hit has occurred.

Would I use a `b2Body` and set it as a sensor for this or would I achieve this some other way?

I'm using cocos2d by the way.

# Answer
Yes - it would work nicely. Don't forget that you will need to create a ContactListener for your application in order to be notified of the collision.

Here's an implementation I used from before, to get you started - it might need some tweeks due to being a year old

```
#import "Box2D.h"
#import "b2Contact.h"
class ContactListener : public b2ContactListener
{
public:
    ContactListener();

    void* userData; /// Use this to store application specific body data.
    void BeginContact(b2Contact* contact); // When we first contact
    void EndContact(b2Contact* contact); // When we end contact
};

#import "ContactListener.h"
#import "Box2D.h"
#import "b2Contact.h"
#import "GameScreen.h"

// Implement contact listener.
ContactListener::ContactListener(){};

void ContactListener::BeginContact(b2Contact* contact)
{
    // Box2d objects that collided
    b2Fixture* fixtureA = contact->GetFixtureA();
    b2Fixture* fixtureB = contact->GetFixtureB();
    // Sprites that collided
    CocosNode* actorA = (CocosNode*) fixtureA->GetBody()->GetUserData();
    CocosNode* actorB = (CocosNode*)  fixtureB->GetBody()->GetUserData();

    // This is only true if for example a sprite touched something in your box2d simulation that was not a sprite such as the ground
    // You may not want to return here, so keep that in mind
    if(actorA == nil || actorB == nil) return;

    // Information about the collision, such as where it hit exactly on each body
    b2WorldManifold* worldManifold = new b2WorldManifold();
    contact->GetWorldManifold(worldManifold);

    // Maybe you wanna handle it differently but for this example, we're going to simply use our global object (see previous post)
    // To store the gamescene where these bodies exist and tell it they collided
    [[Global instance]._gameScene onActorDidStartContact:actorA against:actorB at:worldManifold];
}

    // Implement contact listener.
void ContactListener::EndContact(b2Contact* contact)
{
    // Box2d objects that collided
    b2Fixture* fixtureA = contact->GetFixtureA();
    b2Fixture* fixtureB = contact->GetFixtureB();
    // Sprites that collided
    CocosNode* actorA = (CocosNode*) fixtureA->GetBody()->GetUserData();
    CocosNode* actorB = (CocosNode*)  fixtureB->GetBody()->GetUserData();

    // This is only true if for example a sprite touched something in your box2d simulation that was not a sprite such as the ground
    // You may not want to return here, so keep that in mind
    if(actorA == nil || actorB == nil) return;

    // Information about the collision, such as where it hit exactly on each body
    b2WorldManifold* worldManifold = new b2WorldManifold();
    contact->GetWorldManifold(worldManifold);

    // Maybe you wanna handle it differently but for this example, we're going to simply use our global object (see previous post)
    // To store the gamescene where these bodies exist and tell it they collided
    [[Global instance]._gameScene onActorDidEndContact:actorA against:actorB at:worldManifold];
}

-(void) onBunnyDidLandOnCar:(GameObject*)actor
{
     // Nothing to see here, game ended already
    if(self._gameIsOver) return;
    // Cast the actor as the car
    Car* car = (Car*) actor;
    // Check if landing was valid
    if(car._body->GetPosition().y + 3.0f > _junny._body->GetPosition().y) { // Too far below the roof of the car to count as landing on it
        //NSLog(@"onJunnyDidLandOnCar: Too far below");
        return;

// Do some other stuff
...
}

```
> 1 votes

# Answer
Yes, that sounds like something a sensor should be used for.

As far as I'm aware, sensors should be used for any objects that don't actually cause a collision response with objects it collides with.

In this case, you don't want the player to actually be moved when it hits the sensor (or the reverse). A sensor is definitely what you want.
> 0 votes

---
Tags: box2d, cocos2d
---


title: Pygame How To Use Collision?

text:
# Question
Title: Pygame How To Use Collision?
Can someone tell me how to implement collision in Pygame?
For example I have a sprite called A and another one called B.
How do I detect if they collide in Pygame?

# Answer
> 5 votes
Take a look at:

http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.collide\_rect

And the several methods following it. You can test against a rectangle, circle, mask, sprite, or group of sprites.

You probably want

```
pygame.sprite.collide_mask(SpriteLeft, SpriteRight): return bool

```

Which checks if two sprites collide based on their bitmasks.

# Answer
> 2 votes
I use collisions based on rectangles. Both sprites need a .rect assigned to them.

Then check for a collision

* pygame.sprite.collide\_rect(A, B)

(returns a boolean if there is a collision)

Alternatively you can use the rectangle to check for a collision, eg

* A.rect.colliderect(B.rect)

(returns a boolean if there is a collision)

I use rect collisions because they're faster than bitmap checks.

Pygame rect docs http://www.pygame.org/docs/ref/rect.html

---
Tags: python, collision-detection, pygame
---


title: MIDI or other Software Instruments?

text:
# Question
Title: MIDI or other Software Instruments?
Nowadays, most music seems to be prerecorded, but that means they are rather static and take up a lot of space.

I wonder if MIDI is still a viable option (especially considering consoles or iOS) and if I can expect General Midi 1 to be available everywhere? (Note: Referring to the software instruments for sound generation from notes)

Alternatively, are there vendors of embeddable software instruments that can generate the desired sound at runtime?

The whole point is to re-create a dynamic soundscape in which instruments can change their volume, speed or pitch - this can be partially simulated with individual tracks, but it doesn't offer the same flexibility.

# Answer
The soundtrack for the original Unreal Tournament took the form of tracker music, which packages together both audio samples and sequencing information for triggering those samples.

http://en.wikipedia.org/wiki/Tracker\_%28music\_software%29

http://en.wikipedia.org/wiki/Module\_file

You might also look to the demoscene for inspiration. Soundtracks created in tracker software are the rule rather than the exception, and runtime synthesis is frequently employed as well.
> 3 votes

# Answer
I'm not sure every platform does have a complete set of General MIDI instruments, or an engine with which to play them, and if they did, I expect a lot of them would sound as bad as they did 10 years ago.
> 3 votes

# Answer
Yes, MIDI is still heavily used in the music industry. At the low end, you'll find tools like Garage Band. At the high end, you'll find tools like Reason. These can either output standard audio files, or can be used to create MIDI data which can be played back in other tools (or games!)

For use in games, you might consider a library like TiMidity++ for playing back midi music in a cross-platform way, optionally using a custom set of music instrument sample sound. If you're a fan of SDL, then SDL\_mixer is an easy-to-use sound library which wraps around TiMidity++ and a few other sound libraries.
> 1 votes

---
Tags: music, midi
---


# Question
Title: Common pattern to scale "real units" to pixels?
This is a follow-up question to this other one.

I would like to know **if there is a common/typical/best pattern to scale my representation of the world** (currently 160Kmx160Km) **to fit it to the drawing area** (currently 800x600 pixels).

I can think of at least four different approaches:

**Naïve one** (the way I did it so far). I implemented a global function `sc(vector)` that will simply return a scaled down copy of the vector passed in. This of course works, but obliges me to write code like:

```
drawCircle(sc(radius), sc(position))

```

**Wrapping functions**. I could define several functions, each of them wrapping the original middleware one. For example I could define `myDrawCircle` that would first scale the arguments that need scaling, and then call `drawCircle` with the latter. This would make my code perhaps more readable and easier to maintain, but I should write a lot of wrapping functions, which sound silly.

**Function decorator**. I could simply decorate the existing middleware functions, providing automatic scaling for all the parameters that are an instantiation of the class `Vector3D`, but the problem is that those functions also work with the same parameters being `list` or `Vector2D` too, and the decorator would have no way to know which lists need to be scaled (the radius for example) and which not (the RGB values).

**Surface initialisation**. When defining the surface I am going to draw on, I could define the scaling factor (so that I would then use metres and not pixels as parameters). This would work transparently for me and would be my solution of choice, but of course it should be implemented in the middleware, so it's not an real option.

...anyhow: since this is a very common problem, I wonder if there is an established pattern that elegantly solves this problem that I failed to find.

PS: For this project I am using python (with pygame), but - although a python/pygame-specific answer is very appreciated, I'm more interested in the general/high-level description of the pattern rather than its concrete implementation.

Thank you in advance for your time and expertise.

# Answer
> 6 votes
The standard way of doing that is to set up a transform matrix to do the conversion during rendering. For 3D rendering it's the view transform matrix for the camera that does it.

Most 2D APIs have a way of specifying a view transform too, as either a 2x3 matrix or as a separate scale, translation and rotation.

A quick look at the pygame documentation suggests you'll have to implement a view transform matrix yourself. Does it let you derive your own class from it's surface class to enable you to add that functionality?

# Answer
> 2 votes
> since this is a very common problem, I wonder if there is an established pattern that elegantly solves this problem that I failed to find.

Usually people do not attempt to perform run-time scaling in 2D games. I don't agree that it's a common problem. If people want a mini-map or some other fixed rescaling, there is often a new set of graphics done for this purpose. It's rare that you need any single routine to run at 2 different zoom levels in a 2D game.

If you use a 3D API, you can get this functionality for free - just change the camera/viewport parameters.

PyGame is a very old API and unfortunately is only really suited to 2D. Even if you could work out adequate scaling systems for the different zoom levels, the performance will not be good enough and the appearance is likely to be unacceptably bad.

I would advise that if you want to zoom in and out a lot, you move to a modern 3D API as soon as possible. I would recommend pyglet but there are likely to be others too.

---
Tags: maps, pygame, resolution
---


# Question
Title: How to handle physics of moving platforms in a platformer?
So after a few hours of searching on the internet, I have yet to find a pleasing answer on how to handle moving platforms in a 2d platform game. So I decided to make a simple prototype where you interact with 2 different platforms, one that moves vertically and one horizontally. I would love some help to dissect and see what isn't working, and how to fix them. I have submitted the .fla file + .as file below, accompanied with a link to the playable .swf.

The goal is to make the Hero interact with the platforms as if they were solid objects that he can stand on, pushed alongside with, jump on/under etc etc.

The problems with my prototype are these:

* When you stand on the horizontally moving platform, without moving (not touching any keys), the Hero moves along with platform, **but with a slight delay** causing hero to slide back a little.
* When you stand on the horizontally moving platform, and jump, you move along with the platform midair (some games prefer having it like this, but it doesn't feel natural and is not wanted here). Which might be caused by the Hero retaining the velocity on the X-axis from the platform.
* When you jump up to the bottom side on the vertically moving platform, whilst the platform is moving downwards, you sink inside it for a brief second. Hero penetrates through as if the collision was non existent for a moment.
* When you jump on vertically moving platform, the veloctiy on Y-axis is retained, so when you walk off the platform, you fall down at a higher speed. With the speed of the retained velocity, + gravity that is added (this is mostly because I cant figure out a way to reset velocity on Y-axis to 0 when you land on the platform, *without* the player freezing midair).

I'm a novice programmer so I am sure there are BETTER ways to do this, and I would love to hear them all. Any ideas on how to improve the code or other methods in which you can implement moving platforms into a Tilebased game are welcome. In the end, I am trying to find a solid way to handle moving platforms in 2d platformers.

Playable SWF: http://dl.dropbox.com/u/28271061/PlatformerhowtoFLA.html (Move with arrow keys, Jump with X key, Run with Z key)

Sourcecode AS-file: http://dl.dropbox.com/u/28271061/Platformerhowto.as

SourcefileFLA: http://dl.dropbox.com/u/28271061/PlatformerhowtoFLA.fla

If you prefer just to read the code through Pastie online: http://pastie.org/2266764

# Answer
> 17 votes
Let's separate your problem into its distinct issues...

## A word on code quality

Your code currently has your platforms directly controlling your player's velocity *and even the world's gravity constant*. It's hacky, and it's procedural when it should be object-oriented. Once you start expanding this game things are going to get ugly *fast*.

You need to refactor your code. Implement a player class, a platform class and a floor class. Separate their concerns: have the player interpret keyboard controls and control how he runs and jumps, and have the platforms *alter* his momentum as necessary (by adding their own speed to the player's already-determined speed, when necessary).

Have your player determine where it is in regards to a floor-type object (platforms and floors would both have a `BodyType = BodyTypes.Floor`, or something) and determine on its own where it is in regards to the object, how it should react and whether it's falling or on the ground.

This may deserve a separate topic as it's quite a separate issue from everything you've brought up. However, you're going to have to do it at some point.

## Horizontal/vertical inertia when leaving a platform

To solve your vertical and horizontal velocity problems, note two things:

* Regarding horizontal speed: Your code only sets the horizontal speed to 0 when the player hits the ground (on Pastie line 200) or a platform.
* Regarding vertical speed: Your player has a constant falling acceleration. When he walks off the vertical platform, this falling acceleration just keeps getting added to his already downward movement.

Your player is simply suffering from *inertia*: his momentum is maintained until something stops it.

**Solution:** Both issues would be resolved by jSepia's solution to How do I handle moving platforms in a platform game? as it would *completely separate* the player's movement process from how the platforms move him. You simply *would not* fall faster walking off a vertical platform and *would not* preserve your horizontal momentum jumping off a horizontal one, because the platforms will no longer affect your player's *vx* and *vy*.

Note: You may have some difficulty implementing jSepia's solution before your code is refactored.

## Slipping side-to-side around the horizontal platform

Your player isn't actually moved horizontally quite as fast as the platform moves. It's not obvious to me why. This problem would *also* probably be solved by implementing jSepia's solution and properly refactoring your code (the latter would simply make the cause obvious).

## Collision detection: overlapping with the vertical platform

See Pastie line 381: every step it's resetting the player's *vy* to 0 as long as the player's colliding with the underside of the vertical platform. In the following step, *vy* is increased by the gravity acceleration and then the player's moved (and then it's reset to 0 again).

This means for as long as your player's colliding with the bottom of the platform, he's moving down at a constant speed (the gravity constant). The vertical platform is faster than that so it overlaps him. If the vertical platform moved over a longer distance it would slide right through him until the player was registered as standing on the platform.

**Solution:** Don't reset the player's *vy* to 0. Just set the player's *vy* to the platform's vertical speed (*if the platform is travelling downwards*). Your player will then be moving away from the vertical platform *at least* as fast as the platform, and accelerate away from it.

---
Tags: physics, actionscript-3, platformer, moving-platforms
---


# Question
Title: Android Fling Gesture, Animation And Collision - Resources?
I'm starting work on a 2D Android game where the player will put their finger on a game piece and do a fling gesture to throw the piece across the gameboard.

I've gone through some Android interpolation animation tutorials and have the fling working, and the game piece (currently the only item on the board) moving almost as intended.

However, I'm utterly flumoxed as to how I would work collision detection into this, as it seems to me that the fling gesture, and the resulting movement of the piece is a complete, uninterruptable action.

Are there any existing Android resources that implement 2D ball physics whilst also allowing things to be moved by flinging? The next move in the game would only be made once all game pieces had come to rest, so it's only the initial action that requires the fling.

Failing that, could someone kindly point out some good resources that might be relevant to my question? My Google hunting has pretty much just liquified my brain.

# Answer
> 1 votes
The default Fling and Animations provided by the Android API are there for common animations. Here, you wan't something quite specific so I would suggest using a Fling detection as an input in a Physic simulation engine.

---
Tags: collision-detection, android, physics, animation
---


title: RTS Game Protocol

text:
# Question
Title: RTS Game Protocol
I've been thinking about a multi player RTS game. The part that I can't seem to get around is keeping unit movement synced. If I move unit A to spot XY, I have to communicate that back to server that relays to the other client.

I'm curious what the communications would look like. Would you just communicate to the server that I'm moving unit A to XY from JZ? Maybe you need to communicate movement coord by coord instead? What's the most efficient methodology to communicate movement of units from one client to the other?

***EDIT***

This is a reposted question from stackoverflow. I found that this site was probably a better place for the question.

One of the better answers from that post:

I assume you're intending to use the Client-Server networking paradigm? In which case you cannot trust the clients to handle the actual positioning of units, you must delegate that task to the server. You then take the command list from each client per-tick, and compute the movement of each unit, once this has been completed, next tick you relay the position of each unit relevant to each client (either on a whole-map basis, or per-view basis), and start the process again.

# Answer
> 27 votes
You don't want to sync the positions of all the units from the server to each client; that will take up *way* more bandwidth than you need. You'd also have to deal with interpolating/extrapolating unit positions, etc. **Almost no professional RTS's use client/server!**

Instead, you want to send only the players' commands. Rather than moving the units immediately when the player clicks, you'll queue the move-command to be done at some point in the future - usually just a couple of frames. Everyone sends their commands to everyone. A couple of frames later, everyone executes all the commands, and because the game is deterministic, they all see the same result.

The downside is that every player is as slow as the slowest player - if anyone falls behind in sending out commands, everyone has to slow down and wait for him to catch up (in Starcraft 2, this is the *"XXX is slowing down the game"* dialog).

---

In fact, there is one more thing that is usually done: **eliminate the server altogether**. Have every client send their commands to every other client. This reduces lag *(instead of a command going from you--\>server--\>opponent, it just goes from you--\>opponent)* **and** makes coding easier, since you no longer need to code a separate server. This sort of architecture is called peer-to-peer (P2P).

The downside is that now you need a way of resolving conflicts, but since players' commands are independent of each other in most RTS's, this usually isn't much of a problem. Also, it doesn't scale well - every time you add a new player, *every* player needs to send him their commands. You're not going to be making an MMO RTS using P2P.

---

This setup *(sending only commands using P2P)* is how most RTS's, including Starcraft, C&C, and AoE work, and is the only way AoE could possibly support 1500 units on a 28.8kbps connection.

Here are a few more tips for writing a P2P RTS:

* For obvious reasons, this setup can only work if your game uses fixed-step time \- you don't want the results of a calculation to be dependent on the framerate! Fixed-step is easier to work with for most things, so this shouldn't be a problem.
* In order for this to work, the results of every command must be **completely deterministic**.
    + This is usually pretty easy if you restrict yourself to one system (such as 32-bit Windows) and force all clients to use the same executable: make sure any random-number generators have the same seed and are always called in the same order; be extremely careful when iterating over unordered collections; etc.
    + This is *extremely* difficult if you plan on making the game playable across different platforms, or (as is often the case with Linux) allow the clients to compile the code themselves. Not only are different system libraries pretty much guaranteed to use different implementations of `rand()`, `cos()` etc, but pretty much **all** floating-point math is out of the question *(see here, here, and here)*! In that case, you may be better off using client-server.
* You're going to want to send out all unit positions every once in a while, at least while debugging, to detect desync bugs (which, trust me, you *will* have). Whether you keep that in the final game is up to you - I would sync at least some units (or use some sort of checksum), to detect attempted-hacking.

# Answer
> 14 votes
I've made a TCP-networked RTS, in which I **passed the commands themselves, rather than the results of the commands**. For instance, a player gives a move order. If the move order is valid according to that client, it is sent to the server. The server then sends it back to all clients, who validate and execute it.

So all client machines run the game themselves, the server code accepts messages and sends them back to all clients. If a client gives a move order, it won't start executing it until it is received back from the server.

The server sends a 'tick' number at which to execute the command as well, which is a few ticks ahead of the 'current' tick. This way all commands can be executed at the same 'tick' on all machines.

One benefit this method is that it doesn't depend on any individual client machine to validate the command. If I passed the results of the move, I might be able to hack it to move my units faster. All clients have to execute the same command and if one machine executes it differently, it will be obvious.

Validating the command client-side before sending it to the server isn't necessary, but in theory it saves network traffic. I used the same validation code to tell the UI that the move was possible, so it didn't require writing extra code.

As for what the messages might look like. I wasn't concerned with ultra efficiency as it was my first networked game. I passed commands as strings. The commands would be formatted like this: `"<player_id>:<command>:<parameters>"`

For a contrived example, a move command might look like this: `"3:move:522:100:200"`. This means Player `3` wants to `move` unit `522` to (`100`,`200`).

The server passes the command on to all clients, including the one who sent it, with a tick number attached like this: `"153238:3:move:522:100:200"`.

Then the clients would all execute this command when tick 153238 is executed.

---
Tags: movement, rts
---


# Question
Title: Does an indie game developer really need to know graphics programming beyond the basics?
I've been working on a 2D game for the iPhone and learning a lot about game design in the process. I've looked at some of the most popular games for the iPhone ( angry birds, cut the rope, doodle jump, tiny wings, etc..) and have noticed that they're all 2D. Now I understand that some graphics knowledge is needed to create these games, but does a indie game developer really need to know graphics programming beyond the basics?

I feel there are two reasons that 2D games have greater success on mobile. One, lack of controller. Two, casual games need a more casual experience and 2D games cause less visual processing on the brain.

I'm asking this question because I'm still in school getting a cs degree and trying to decide on taking a real-time rendering course that will focus on GLSL and GPU programming or artificial intelligence. I've actually already taken a computer graphics course, but it focused on theory and we touched opengl very little. We implemented the graphics pipeline ourselves.

I get the feeling that studying color theory and basic drawing skills would be more helpful than GLSL or OpenGL ES 2.0 to master the aesthetics part of game design.

I could be short sighted though, because games like Braid and World of Goo might of relied a lot on graphics programming and I would love to be able make games of the same quality of these two.

# Answer
> 11 votes
Short answer: **No**. You can "be" an indie game developer without knowing anything about graphics.

More practically, it depends on the kind of graphics you want in your game.

If you want "fancy" graphics, meaning graphics that require whatever knowledge you're referring to, then someone has to know it. You either know it yourself and write the code, or you use a library written by someone\[s\] who knew it.

In any case, it will help to know "it", but of course we each have only so much time and you can't learn everything. The real question is, is there something else you'd be better off devoting time to learning, and the answer is that it really depends on what *you* want to do. You said you want to make a game of the quality of "Braid and World of Goo", and I'm not qualified to tell you what you need to know to do that. Maybe someone else will be.

# Answer
> 1 votes
You will need some basic knowledge in any case, but that can be obtained quite easy. But for your course decision I recommend you to consider another course. Yes both can be helpful, but i doubt they will be helpful in your case. First of all, AI course will be related with pure AI while in games it is mostly expert systems. For the real time rendering course, it will be so deep that you will not be able to use that knowledge. Yes its a good thing to know but you dont really need that if you are not planning to write a game engine. Of course I can give more advice if I can see curriculum. I am both a graphics and game programmer. Most of the time knowledge on one subject does not help with another. If you want to be a good indie developer, learn how to write a striking story or design natural feeling control mechanisms, or focus on a unique game which will be enjoyable and challenging enough (but no more).

If you ask me angry birds require more physics knowledge than graphics. I cannot comment other games since I dont know anything about them.

---
Tags: software-engineering, graphics-programming, game-industry
---


title: Bitmap & Object Collision Help

text:
# Question
Title: Bitmap & Object Collision Help
Is it possible to detect when an object and a bitmap collide. I have an arraylist of sprites that I am shooting with an image. I tried using this method here but as soon as the bitmap appears the sprite disappears, this is in the Sprite class:

```
public boolean isCollision(Bitmap other)
{
    if(other.getWidth() > x && other.getWidth() < x + width && >other.getHeight() > y && other.getHeight() < y + height);
    return true;
}

```

# Answer
You have two major, basic problems. First, this won't even compile because of this part: `&& >other.getHeight() > y &&` (notice the `>` before `other`). Secondly, this:

```
if(something);
return true;

```

will always return `true`. What you probably meant was this:

```
if(something)
    return true;
return false;

```

which, since `something` is just a `boolean` expression, is the same as

```
return something;

```

Both Eclipse and Netbeans have an "AutoFormat" option that would have made this error immediately obvious, while simultaneously fixing your horrendous formatting.

---

After you fix those, you still have problems with your logic, but those at least can be easily discovered with a debugger.
> 1 votes

# Answer
The following statement will always be false:

```
other.getWidth() > x && other.getWidth() < x

```

x can not be both greater and smaller than width.

As for the rest of your question, it seems to be two folded. You seem to be both having problem with checking the collision and with displaying it.

To solve your collision problems I would need to know more. What kind of collision do you want? (Should sprites collide with a background image that is divided into two colors, red for collidable?) And how are you handling sprite-sprite collisions currently?

To solve your displaying problem I would need to see more of your drawing functions.

(on an other note, who keeps upping every question asked on gamdev even if they are short unclear questions?)
> 0 votes

---
Tags: collision-detection, java, android
---


# Question
Title: Anyone know of an online resource with spritesheets from classic games?
I'm looking for spritesheets for classic retro games, and old home computer games (c64, amiga etc.) Does anyone know of a source online?

# Answer
> 6 votes
http://spriters-resource.com/ has tons of different spritesheets from games.

# Answer
> 2 votes
I like the first one the best. http://www.videogamesprites.net/ http://www.retrogamezone.co.uk/nes.htm http://www.spriters-resource.com/nes/A.html

# Answer
> 1 votes
Google for "STOS sprites" and "AMOS sprites".

STOS and AMOS were basic variants for the Atari ST and Amiga respectively - both had large communities and there were a lot of sprite collections available in the public domain.

Also, try Googling for "TOSEC". There are some torrents (probably illegal) that collect virtually everything ever released for the Atari ST, the Amiga etc. That includes some large collections of public domain disks, some of which will contain sprite collections. If you're only looking to collect the PD stuff, you're probably on the right side of the law (if anyone cares anyway).

The big problem then is probably converting all those ancient file formats. It may be easier to view them in an emulator and get screenshots.

# Answer
> 0 votes
This is not from old games but it sure has some sprites: http://www.reinerstilesets.de/

---
Tags: 2d, graphics, sprites, spritesheet
---


# Question
Title: A* only for horizontal / vertical movement
anyone can share a link for a tutorial or article about optimizing A\* for horizontal / vertical movement (no diagonal). Is not as easy as change the G values to 10 everytime.

Thanks

# Answer
I found the info needed here: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#S7
> 0 votes

# Answer
A\* is a graph search; the algorithm doesn't know or care whether you're searching a grid (with or without permissible diagonal movement) or a free-form graph. To "optimize" for the case where diagonal movement isn't allowed, make sure to never return diagonally-adjacent nodes when computing the neighbors of the current node. Between that and selecting an appropriate heuristic for your scenario, there's little in the way of optimizations available specifically for the 4-directional grid case (as far as I'm aware).
> 8 votes

---
Tags: path-finding
---


title: OpenGL or Canvas?

text:
# Question
Title: OpenGL or Canvas?
I'm writing a 2D snake-like game for android (Hungry Birds, already in the market), and now I'm wondering if I should port it to OpenGL so that the performance can stay stable while I continuously add additional features to it. I'm still an apprentice (17yo), so I don't know any "complicated" math yet (matrix transformations, vector math etc). Should I risk the porting?

# Answer
If you don't want (or have time) to learn all the math, i'd suggest you keep on working with Canvas, or using a Game engine that wraps OpenGL and do all the complicated math for you (for example Andengine)
> 3 votes

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


title: Cutting a body in box2d

text:
# Question
Title: Cutting a body in box2d
After cocos2d, I'm looking at box2d... And I have some questions:

I was wondering **how to cut a body into pieces.**

1. How do I determine the intersection point of the body with the cut line?
2. Create a new body in some "update\_body\_method"?

On the second question I have answer, for example between two points create vector from first point to second point.

# Answer
> 2 votes
There is an implementation of this in the C# library Velcro Physics (formerly Farseer Physics), which is based on Box2D: CuttingTools.cs

`/src/VelcroPhysics/Tools/Cutting/Simple/CuttingTools.cs`

```
// This is a high-level function to cuts fixtures inside the given world, using the start and end points.
public static void Cut(World world, Vector2 start, Vector2 end, float thickness)

// Split a fixture into 2 vertice collections using the given entry and exit-point.
public static void SplitShape(Fixture fixture, Vector2 entryPoint, Vector2 exitPoint, float splitSize, out Vertices first, out Vertices second)

```

---
Tags: box2d, physics-engine
---


# Question
Title: Where would I update a graphical representation of a b2Body in Box2D's solver?
Hey i'm trying to make a class called `BodyRep` Which is supposed to use SFML too **sync a graphical representation and Box2D Bodies orientation/location.**

To do this i plan to ovveride some Box2D function so that it does it's original steps, plus one extra: *to update the graphical representaions orientation based on the new Body orientation.*

However I found this is not as easy as it seems as my class must be a descendent of another class that does the actual updates to the bodies in the World, so it CAN ovveride the function. On top of that, I know there is a ton of itterating in Box2D's solver, and i don't want my graphical reps. being updated if they don't have to yet....

**So... What CLASS should I Descend from and what FUNCTION should I ovveride?**

* if you have any other ideas on how i could accomplish my goal of syncronization between SFML and Box2D bodies, feel free to suggest them! =)

# Answer
Box2D's body classes *are not open for subclassing* (nor are most of its other classes). They come out of a factory method on b2World, and they cannot (should not) be copied.

Generally, you should be using *composition* rather than inheritance:

```
struct BodyRep {
    b2Body *physics;
    sf::Sprite *visual;
};
....
for (BodyRep &e : drawable_bodies) {
    b2Vec2 pos = e.physics->GetPosition();
    e.visual->SetPosition(pos.x, pos.y);
    // + whatever other properties you need, e.g. size.
    window.Draw(*e.visual);
}

```
> 3 votes

---
Tags: box2d
---


# Question
Title: What is the name of this power or value-oriented gameplay mechanic?
I would like to identify the name of a certain gameplay mechanism. It is fairly commonly seen but probably best illustrated with card games:

A game played with a pack of cards usually has card values ordered in the following way:

```
A > K > Q > J > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2

```

Sometimes the lowest-ranked card (in this case `2`) is specially ruled to trump the highest-ranked card (in this case `A`). Is there a proper name for such a mechanism?

# Answer
> 11 votes
It sounds like you are describing an extension of the rock-paper-scissors mechanic whereby every piece/card/token can defeat at least one other piece/card/token.

(Your question made me think of Stratego, and specifically of the few pieces like the low-ranked Spy who can defeat the otherwise-top-ranked Marshal and the Miner who can defuse bombs.)

# Answer
> 3 votes
It may be that it really is just referred to as **trumping**, and that the mechanism would simply be "having a **trump**", or **trump rule variation** as AttackingHobo suggested.

This Wikipedia article discusses the idea, but it seems to usually refer to suit trumping.

---
Tags: game-mechanics, balance, card-game, game-design
---


title: How do I use a PC Dance Pad with Xna?

text:
# Question
Title: How do I use a PC Dance Pad with Xna?
I have a Dance Pad and I want use it in XNA as a controller. It has a USB connection.

Can someone help me?

# Answer
iirc, XNA does not have support itself for non-XInput controllers. This means you'll have to use another API to access your dance pad (and you'll be limiting yourself to the PC in that case).

Here is a blog post describing some options for non-360 controller support in XNA 3.1. The techniques should scale to 4.0.
> 6 votes

---
Tags: xna, input
---


title: Implementing material deformation

text:
# Question
Title: Implementing material deformation
I want to implement deformation of plastic material, like plasticine for example. Where should I start to study? What technique should I use?

Thank you for any advice.

**EDIT**

I want to use it in real-time in kind of a 3D game, not a physics simulation. When I "push" on the plasticine, it is expected to spill. I want to rotate it or any other actions.

Look at this video: http://www.youtube.com/watch?v=mDbVHEg5qC4

# Answer
Is this for use in a real-time game or as a high-accuracy simulation? If you're just looking at it as an effect for a game, then it's quite possible that you could get away with using a procedural texture, determined by CPU, combined with a vertex-shader to move your vertices about as desired at run-time.

If you're interested in accuracy, then you would need to take into account various material properties, such as Young's Modulus, limit of elasticity, Hardness, etc. (I'm not a material scientist so I don't know all of the variables affecting plastic/elastic deformation). I guess you'd first determine how accurate you want your simulation to be, and then just use this article to find out what variables you need, and then search for each of those variables for each material you want (this site is useful). You would then presumably have a very-high polygon object, or tessellate it as necessary.

I also imagine you would have to have per-vertex collision detection, to ensure you don't end up with impossible shapes (self-intersection tests etc.), also, you could use the tessellation feature in DirectX 11, as mentioned earlier, to help smoothen your shape as you deform it (a cube only needs 6 faces, but when morphed you'll need to add more faces).

Hope this helps, I'd like to see how your project progresses! :)
> 3 votes

---
Tags: mathematics, physics
---


# Question
Title: XNA: My bullets lag the game the first time they're fired, but not after
I'm working on a SpaceWar-esque project to get comfortable with XNA. I have a Ship DrawableGameComponent and a Bullet DrawableGameComponent. The player's Ship is created at the start of the game, and the Bullets are created for each Ship as part of its constructor.

In my Ship constructor, I have the following code:

```
for (int i = 0; i < 5; i++)
{
    activeBullets[i] = new Bullet(game);
}

```

The relevant part of my Ship's shoot() function is as follows:

```
activeBullets[bullet].Visible = true;
activeBullets[bullet].Enabled = true;
activeBullets[bullet].position = this.position;

```

The first five times I shoot() (that is, once for each bullet object that the ship is allotted), there is lag that I think is due to the bullet sprite being loaded. I've tried setting Visible and Enabled to true in the ship constructor loop where the Bullets are instantiated, but the first-five-shots lag persists. Any shots beyond the first five are completely lag-free.

How do I load the Bullets properly ahead of time so that there is no lag on the first shots?

# Answer
> 9 votes
`DrawableGameComponent`'s come with a certain amount of overhead - aside from the memory, every time you add a component to the collection it must be resorted *(because components have a `DrawOrder`)*. You don't want to be constantly adding and removing components.

For this reason, you don't want `Bullet` to be a `DrawableGameComponent`. Instead, you should make something like a `ProjectileManager`, which loads all the projectiles (including their textures), and manages creating/destroying/updating/drawing them. This simultaneously solves your texture-loading problem, as the textures can *(and should)* be loaded only once, in `LoadContent()`.

If this does not work, then the textures are not your problem, and we'll need more information to help you further.

# Answer
> 0 votes
It appears that my Update function was being called at least twice before anything was being displayed, and that even though the bullets were part of the collection they were becoming disabled before being drawn and thus textures not loaded (?!?).

By setting the lifetime (which is decremented once per Update, and when lifetime = 0 the bullets are no longer Visible/Enabled) of each Bullet to 3 or greater (this may vary depending on CPU speed?) when I instantiate the Bullets as part of the ship class, the textures are properly loaded at the beginning of the game.

I'm still not sure why manually setting them to Enabled/Visible at creation doesn't force the texture to be loaded.

---
Tags: xna, loading, preload
---


# Question
Title: Whats the best cross-platform game engine that supports Linux?
What is the best cross-platform game engine, being the most commercially supported, there is for free available for development on Linux? I'm planning on creating multiple, non-commercial, fps games to gain real industry experience in C++ game development.

# Answer
> 2 votes
Firstly, "best" is a rather subjective term, personally, I enjoy working with the Source engine (at least, the client and server which plug in to the base source engine, and determine your game play), making a MOD with a recent industry-standard engine is probably the closest you'll get to working within the confines of a restricted codebase in the industry. Others swear by the Quake engine for it's open-source qualities, and other's prefer various other engines.

If you are looking for industry experience, then I would say that it would be extremely advisable to develop your own engine, to get an idea of the scale of development that goes into producing a marketable industry-quality game. You will learn how to handle graphics development, AI development, handling performance and optimization of your code, understanding what goes into making a game cross-platform, and hopefully, have an enjoyable time. If you do decide to go down this route, I would recommend OpenGL for it's cross-platform ability, however, most games are written for Windows, so DirectX with an OpenGL fallback is also a possibility (this also allows you to learn about dynamic linking of DLLs etc.)

Although you may only be interested primarily in one field (AI Programming, Weapons programming, Physics programming etc.), building your own game-engine demonstrates to a potential employer that you are, firstly, passionate about game programming and dedicated enough to do something about it, and secondly, have a well-rounded understanding of game development, which is extremely desirable especially for a senior programmer).

Personally, other than the Source engine, I've never used another's engine for an FPS, however, I have heard good things about the cafu engine, which is supposed to be cross-platform and relatively recent (and with good access to it's rendering process etc.)

I hope this helps you to make a decision, and good luck with your future career in the gaming industry! :)

EDIT: With regards to your edited question, I believe OGRE has a lot of commercial support, and has a regularly updated code-base (and fulfills all of your other criterion). However, I would still recommend writing your own engine, for the reasons highlighted above. :)

---
Tags: c++, first-person-shooter, cross-platform, linux
---


# Question
Title: Cocos 2D putting things on the cocos thread or not?
We are using Cocos 2D for Android and are unsure if it's a good thing to execute our non-ui tasks on the Cocos thread as a way to get the animations in our game to pause.

What is the recommended practice?

# Answer
So as it turns out you should put as little on the Cocos thread as you can. Things you schedule here get run for every frane! It's sometimes an easy way to get things synced between GUI and background logic, but it will make your game slow.
> 1 votes

# Answer
Thread are something that you have to avoid as long as possible. sure they make all the thing easier in some conditions but they may also create some enexpeted behavior that are really hard to trace. so for your example i prefer some flag to stop update functions to do their animate jobs since you can easily implement it that way.

in general specially for iphone/android that using threads doesn't give any boost in performance (and sometimes might even reduce fps) I prefer to do all the jobs by hand. except some very rare cases such as loading game content while playing animations there is no need to use threads at all, so you have to avoid using them.
> 0 votes

---
Tags: android, multithreading, cocos2d
---


title: 2D Platformer AABB collision problems

text:
# Question
Title: 2D Platformer AABB collision problems
I have a problem with AABB collision resolution.

---

I resolve AABB intersection by resolving the X axis first, then the Y axis. This is done to prevent this bug: https://i.stack.imgur.com/NLg4j.png

---

The current method works fine when an object moves into the player and the player has to be pushed horizontally. As you can see in the .gif, the horizontal spikes push the player correctly.

---

When the vertical spikes move into the player, however, the X axis is still resolved first. This makes "using the spikes as a lift" impossible.

When the player moves into the vertical spikes (affected by gravity, falls into them), he's pushed on the Y axis, because there was no overlap on the X axis to begin with.

---

Something I tried was the method described in the first answer of this link: 2D rectangular object collision detection

However the spikes and moving objects move by having their position changed, not velocity, and I don't calculate their next predicted position until their Update() method is called. Needless to say this solution didn't work either. :(

---

I need to solve AABB collision in a way that both of the cases described above work as intended.

This is my current collision source code: http://pastebin.com/MiCi3nA1

I'd be really grateful if someone could look into this, since this bug has been present in the engine all the way back from the beginning, and I've been struggling to find a good solution, without any success. This is seriously making me spend nights looking at the collision code and preventing me from getting to the "fun part" and coding the game logic :(

---

I tried implementing the same collision system as in the XNA AppHub platformer demo (by copy-pasting most of the stuff). However the "jumping" bug occurs in my game, while it doesn't occur in the AppHub demo. \[ jumping bug: https://i.stack.imgur.com/NLg4j.png \]

To jump I check if the player is "onGround", then add -5 to Velocity.Y.

Since the player's Velocity.X is higher than Velocity.Y (refer to the fourth panel in the diagram), onGround is set to true when it shouldn't be, and thus lets the player jump in mid-air.

I believe this doesn't happen in the AppHub demo because the player's Velocity.X will never be higher than Velocity.Y, but I may be mistaken.

I solved this before by resolving on the X axis first, then on the Y axis. But that screws up the collision with the spikes as I stated above.

# Answer
> 9 votes
OK, I figured out why the XNA AppHub platformer demo doesn't have the "jumping" bug: **the demo tests the collision tiles from *top to bottom***. When up against a "wall" the player may be overlapping multiple tiles. The resolution order is important because resolving one collision may also resolve other collisions (but in a different direction). The `onGround` property is only set when the collision is resolved by pushing the player up on the y-axis. This resolution will not occur if the previous resolutions pushed the player down and/or horizontally.

I was able to reproduce the "jumping" bug in the XNA demo by changing this line:

```
for (int y = topTile; y <= bottomTile; ++y)

```

to this:

```
for (int y = bottomTile; y >= topTile; --y)

```

(I also tweaked some of the physics-related constants, but this should not matter.)

**Perhaps sorting `bodiesToCheck` on the y-axis before resolving the the collisions in your game will fix the "jumping" bug.** I suggest resolving the collision on the "shallow" axis of penetration, as the XNA demo does and Trevor suggests. Also note the XNA demo player is twice as tall as the collide-able tiles, making the multiple collision case more likely.

# Answer
> 9 votes
The simplest solution for you will be to check both collision directions against every object in the world before resolving any collisions, and just resolve the smaller of the two resulting "compound collisions". This means that you resolve by the smallest amount possible, instead of always resolving x first, or always resolving y first.

Your code would look something like this:

```
// This loop repeats, until our object has been fully pushed outside of all
// collision objects
while ( StillCollidingWithSomething(object) )
{
  float xDistanceToResolve = XDistanceToMoveToResolveCollisions( object );
  float yDistanceToResolve = YDistanceToMoveToResolveCollisions( object );
  bool xIsColliding = (xDistanceToResolve != 0.f);

  // if we aren't colliding on x (not possible for normal solid collision
  // shapes, but can happen for unidirectional collision objects, such as
  // platforms which can be jumped up through, but support the player from
  // above), or if a correction along y would simply require a smaller move
  // than one along x, then resolve our collision by moving along y.

  if ( !xIsColliding || fabs( yDistanceToResolve ) < fabs( xDistanceToResolve ) )
  {
    object->Move( 0.f, yDistanceToResolve );
  }
  else // otherwise, resolve the collision by moving along x
  {
    object->Move( xDistanceToResolve, 0.f );
  }
}

```

**big revision**: From reading commentary on other answers, I think I've finally noticed an unstated assumption, which will cause this approach not to work (and which explains why I couldn't understand the problems that some -- but not all -- people saw with this approach). To elaborate, here is some more pseudocode, showing more explicitly what the functions I referenced before are supposed to actually be doing:

```
bool StillCollidingWithSomething( MovingObject object )
{
  // loop over every collision object in the world.  (Implementation detail:
  // don't test 'object' against itself!)
  for( int i = 0; i < collisionObjectCount; i++ )
  {
    // if the moving object overlaps any collision object in the world, then
    // it's colliding
    if ( Overlaps( collisionObject[i], object ) )
      return true;
  }
  return false;
}

float XDistanceToMoveToResolveCollisions( MovingObject object )
{
  // check how far we'd have to move left or right to stop colliding with anything
  // return whichever move is smaller
  float moveOutLeft = FindDistanceToEmptySpaceAlongNegativeX(object->GetPosition());
  float moveOutRight = FindDistanceToEmptySpaceAlongX(object->GetPosition());
  float bestMoveOut = min( fabs(moveOutLeft), fabs(moveOutRight) );

  return minimumMove;
}

float FindDistanceToEmptySpaceAlongX( Vector2D position )
{
  Vector2D cursor = position;
  bool colliding = true;
  // until we stop colliding...
  while ( colliding )
  {
    colliding = false;
    // loop over all collision objects...
    for( int i = 0; i < collisionObjectCount; i++ )
    {
      // and if we hit an object...
      if ( Overlaps( collisionObject[i], cursor ) )
      {
        // move outside of the object, and repeat.
        cursor.x = collisionObject[i].rightSide;
        colliding = true;

        // break back to the 'while' loop, to re-test collisions with
        // our new cursor position
        break;
      }
    }
  }
  // return how far we had to move, to reach empty space
  return cursor.x - position.x;
}

```

This is not a "per object pair" test; it doesn't work by testing and resolving the moving object against each tile of a world map individually (that approach will never work reliably, and fails in increasingly catastrophic ways as tile sizes decrease). Instead, it is testing the moving object against every object in the world map simultaneously, and then resolving based upon collisions against the whole world map.

This is how you ensure that (for example) individual wall tiles within a wall never bounce the player up and down between two adjacent tiles, resulting in the player being trapped in some non-existant space 'between' them; the collision resolution distances are always calculated all the way to empty space in the world, *not* merely to the boundary of a single tile which might then have another solid tile on top of it.

# Answer
> 6 votes
# Edit

## I have improved it

It seems the key thing I changed is classifying the intersections.

Intersections are either:

* Ceiling bumps
* Ground hits (push out of the floor)
* Mid-air wall collisions
* Grounded wall collisions

and I resolve them in that order

Define a ground collision as player being at least 1/4 way on the tile

So this is a ground collision and the player (**blue**) will sit on top of the tile (**black**)

But this is NOT a ground collision and the player will "slip" on the right side of the tile when he lands on it

By this method the player will no longer get caught on the sides of walls

# Answer
> 3 votes
**Forenote:**
My engine uses a collision detection class that checks collisions with all objects real time, only when an object moves, and only in the grid squares it currently occupies.

**My Solution:**

When I ran against problems like this in my 2d platformer, I did something like the following :

-(engine detects possible collisions, quickly)
-(game informs engine to check exact collisions for particular object)\[returns vector of object\*\]
-(object looks at depth of penetration, as well as previous position relative to other object's previous position, to determine which side to slide out of)
-(object moves, and averages it's velocity with object's velocity (if the object is moving))

# Answer
> 2 votes
In video games I have programmed the approach was to have a function telling if your position is valid, ie. bool ValidPos(int x,int y, int wi,int he);

The function checks the bounding box (x,y,wi,he) against all geometry in the game and returns false if there is any intersection.

If you want to move, say to the right, take the player position, add 4 to x and check if the position is valid, if not, check with +3,+2 etc until it is.

If you also need to have gravity you need a variable that grows as long as you dont hit the ground (hitting ground: ValidPos(x,y+1, wi,he) == true, y is positive downwards here). if you can move that distance (ie. ValidPos(x,y+gravity,wi,he) returns true) you are falling, useful sometimes when you shouldn't be able to control you character when falling.

Now, your problem is that you have objects in your world that moves so first of all you need to check if your old position is still valid!

If it is not, you need to find a position that is. If objects ingame can't move faster than say 2 pixels per game revolution, you would need to check if position (x,y-1) is valid, then (x,y-2) then (x+1,y) etc etc. the whole space between (x-2,y-2) to (x+2,y+2) should be checked. If there are no valid position then it means you have been 'crushed'.

HTH

Valmond

# Answer
> 2 votes
I have a few questions before I start answering this. First, in the original bug in which you got stuck in the walls, were those tiles on the left individual tiles as opposed to one large tile? And if they were, was the player getting stuck in between them? If yes to both those questions, just make sure your **new position is valid**. That means you'll have to check if there's a collision on where your telling the player to move. So solve the minimum displacement as described below, and then move your player based on that only if he **can** move there. Almost too under the nose :P This will actually introduce another bug, which I call "corner cases". Essentially in terms of corners (like the bottom left where the horizontal spikes come out in your .gif, but if there were no spikes) would not resolve a collision, because it would think that none of the resolutions you generate lead to a valid position. To solve this, simply keep a bool of whether the collision has been resolved, as well as a list of all the minimum penetration resolutions. Afterwards, if the collision has not been resolved, loop over every resolution you generated, and keep track of the maximum X and maximum Y resolutions (the maximums don't have to come from the same resolution). Then resolve the collision on those maximums. This seems to solve all your problems as well as the ones I've encountered. Here's the code I use in my update:

```
    List<Vector2> collisions = new List<Vector2>();
        bool resolved = false;
        foreach (Platform p in testPlat)
        {
            Vector2 dif = p.resolveCollision(player.getCollisionMask());

            RectangleF newPos = player.getCollisionMask();

            newPos.X -= dif.X;
            newPos.Y -= dif.Y;

            if (!PlatformCollision(newPos)) //This checks if there's a collision (ie if we're entering an invalid space)
            {
                if (dif.X != 0)
                    player.velocity.X = 0; //Do whatever you want here, I like to stop my player on collisions
                if (dif.Y != 0)
                    player.velocity.Y = 0;

                player.MoveY(-dif.Y);
                player.MoveX(-dif.X);
                resolved = true;
            }
            collisions.Add(dif);
        }

        if (!resolved)
        {
            Vector2 max = Vector2.Zero;

            foreach (Vector2 v in collisions)
            {
                if (Math.Abs(v.X) > Math.Abs(max.X))
                {
                    max.X = v.X;
                }
                if (Math.Abs(v.Y) > Math.Abs(max.Y))
                {
                    max.Y = v.Y;
                }
            }

            player.MoveY(-max.Y);

            if (max.Y != 0)
                player.velocity.Y = 0;
            player.MoveX(-max.X);

            if (max.X != 0)
                player.velocity.X = 0;
        }

```

Another question, are the spikes you show one tile, or individual tiles? If they are individual thin tiles, you may have to use a different approach for the horizontal ones and vertical ones than what I describe below. But if they're whole tiles this should work.

---

Alright, so basically this is what @Trevor Powell was describing. Since you're using only AABBs, all you have to do is find how much one rectangle penetrates the other. This will give you a quantity in the X axis and the Y. Choose the minimum out of the two, and move your colliding object along that axis that amount. That is all you need to resolve an AABB collision. You will NEVER need to move along more than one axis in such a collision, so you should never be confused about what one to move first, as you will only be moving the minimum.

Metanet software has a classic tutorial on an approach here. It also goes into other shapes as well.

Here's an XNA function I made to find the overlap vector of two rectangles:

```
    public Point resolveCollision(Rectangle otherRect)
    {
        if (!isCollision(otherRect))
        {
            return Point.Zero;
        }

        int minOtherX = otherRect.X;
        int maxOtherX = otherRect.X + otherRect.Width;

        int minMyX = collisionMask.X;
        int maxMyX = collisionMask.X + collisionMask.Width;

        int minOtherY = otherRect.Y;
        int maxOtherY = otherRect.Y + otherRect.Height;

        int minMyY = collisionMask.Y;
        int maxMyY = collisionMask.Y + collisionMask.Height;

        int dx, dy;

        if (maxOtherX - minMyX < maxMyX - minOtherX)
        {
            dx = (maxOtherX - minMyX);
        }
        else
        {
            dx = -(maxMyX - minOtherX);
        }

        if (maxOtherY - minMyY < maxMyY - minOtherY)
        {
            dy = (maxOtherY - minMyY);
        }
        else
        {
            dy = -(maxMyY - minOtherY);
        }

        if (Math.Abs(dx) < Math.Abs(dy))
            return new Point(dx, 0);
        else
            return new Point(0, dy);
    }

```

(I hope it's simple to follow, because I'm sure there are better ways to implement it...)

isCollision(Rectangle) is literally just a call to XNA's Rectangle.Intersects(Rectangle).

I've tested this with moving platforms and it seems to work fine. I'll do some more tests more similar to your .gif to make sure and report back if it doesn't work.

---

# Answer
> 1 votes
It's simple.

**Rewrite the spikes. It's the spikes' fault.**

Your collisions should happen in discrete, tangible units. The problem as far as I can see it is:

```
1. Player is outside spikes
2. Spikes move into intersection position with the player
3. Player resolves incorrectly

```

**The problem is with step 2, not 3!!**

If you're trying to get things to feel solid, you should not let items slide into each other like that. Once you are in a position of intersection, if you lose your place, the problem becomes harder to solve.

The spikes should ideally check for the existence of the player and, when they move, they should *push* him as necessary.

An easy way to achieve this is for the Player to have `moveX` and `moveY` functions which understand the landscape and will shove the player by a certain delta **or as far as they can without hitting an obstacle**.

Normally they will be called by the event loop. However they can also be called by objects in order to push the player.

```
function spikes going up:

    move spikes up

    if intersecting player:
        d = player bottom edge + spikes top edge

        player.moveY(-d)
    end if

end function

```

Obviously the player still needs to react to the spikes if *he* goes into *them*.

The overarching rule is, **after any object moves, it should end in a position without intersection.** This way, it's impossible to get the glitches you are seeing.

---
Tags: c#, 2d, collision-detection, physics, aabb
---


title: How can I fix my combo system?

text:
# Question
Title: How can I fix my combo system?
I'm working on my combo system and I keep getting this weird problem. It's a pretty basic setup: when the player hits the attack button it changes the character's current action to "attack", if the player hits an enemy then an int (f) is set to the next combo number, after the attack finishes the character's current action turns to "standing" and an if statement makes the combo int equal to f.

So basically it reads like this:

```
switch (action)
{
    case "attack":
        if (combo == 0)
        {
            if (enemy.Hit(playerSquare))
            {
                f = 1;
            }
            else
            {
                f = 0;
            }
            if (animationDone)
            {
                action = "stand";
            }
        }
        else if (combo == 1)
        {
            same
        }
        else if (combo == 2)
        {
            same
        }
        break;
}

if (action != "attack")
{
    combo = f;
}

```

My setup works, however, if I press the attack button too quickly it either doesn't add to the combo int (keeping it at the same number as before) or adds to it twice (depending on whether or not I slow it's update rate.) I'm sure there's probably an easy way to fix this and I'm not seeing it or maybe there's a better way to do this that I haven't considered yet, so I'm hoping you guys can help out. Any suggestions?

# Answer
I strongly suggest you to use a state machine to model your combo system. If your state machine library does not have it, you can add a timestamp to process your transition or timeout to force a status change. Using a state machine you can model every complex combo without big troubles.
> 5 votes

# Answer
I don't really understand how your states work, but your code seems like a really complicated way to do this. Why not do something like:

```
switch (action)
{
    case "attack":
        if (animationDone){
            action = "attackComplete";
            break;
        }

        if(enemy.Hit(playerSquare)){
            f++; // increase f with every successful hit
        } else {
            f = 0; // reset the combo-counter
        }
        break;

    case "attackComplete":
        combo = f; // store previous combo
        f = 0; // reset f
        action = "stand";
        break;

    case "stand":
        // do whatever here
        break;
}

```

But this might not solve your problem at all, since the way `f` is increased entirely depends on when and where you call that code.
> 0 votes

---
Tags: xna, c#, game-design
---