title: Balancing agressive invites

text:
# Question
Title: Balancing agressive invites
I am designing a trading card game for mobiles, with the possibility to add cards to your collection using Gems, aquired through victories and inapp purchases.

I am thinking to increase the spread of the game with a tracking system on game invites, enabling the user to invite a friend to play the game. If the friend doesn't own the game client (which is free) he will be offered to download it. If he joins the game, the original player earns X amount of gems as an reward.

There can only be one player per mobile device, which should rule out some harvesting.

My question is, how do you think the structure of this would be recieved ? All invites are mail based, unless the player already exists in the game world (then he gets a ingame invitation.)

I have set a flood filter, so a player can only invite a friend (without the client installed) once a month.

# Answer
> 3 votes
I see some issues with your currently planned system:

* Flood filter. Well-intentioned, but too harsh, if sensible at all. Once a month? Much too long. If your player wants to refer people, he wants to refer as many as possible (for reward and/or because he genuinely wants other people to enjoy your game), and you want as many players, most preferably paying ones, as possible. So with that spam filter you set a hard limit on what both parties want to achieve. Bad idea.
* + A much better way of limiting floods is to improve the quality of invites, i.e. as already suggested, give rewards only if the referred player actually spends money on your game. Second, if you're already planning to track the invites, then communicate and apply an anti-spamming policy, such as manually punishing top spam offenders, for example by removing their invite bonuses temporarily or permanently.
* Mail based invites. Certainly works, but why not use social media, like Facebook? Much more efficient and the preferred way of recommending stuff nowadays, and really a no-brainer on smart mobiles, which all your potential players have anyway.
* + Switching from Mail to social media also greatly reduces the ability for and attractiveness of spamming, because such sites typically already have anti-spamming policies in place, and at least there is a reputation at stake for the potential offenders.

As for the actual reward, as suggested, give rewards only for referred players that actually pay. That also removes the rationale behind farming because whoever the actual person behind a device/purchase is, you earn money.

**Important**:

Make both players, the referrer and the referral, benefit from the invite and the first purchase. Give them both some free Gems, or exclusive items, or a discount on their next purchase, or on purchases for the next X dollars (or whatever you real life currency is), maybe even a multi-level referral system like League of Legends has, or whatever. Even something as simple as a prominent "top referrers list", measured by the money the referrals spend, and with no other benefits for the referrer, can help boost your referrals, because people very simply like to be on top of lists.

And, for the love of the Gaming Gods, if you make a **Trading** Card Game, either make the cards tradable or remove the **Trading** bit.

# Answer
> 0 votes
Doesn't work, for the reasons you stated.

What usually happens with well-designed invite systems, is that the invitor gets credited something only once the invited pays for a subscription.

Now, your problem is that there isn't a subscription. What you can do, **if and only of** the items you buy are "bind on pickup" (i.e. not tradable between players), is to credit the bonus to the invitor once the invited actually buys anything.

---
Tags: monetization, distribution
---


title: Finding furthermost point in game world

text:
# Question
Title: Finding furthermost point in game world
I am attempting to find the furthermost point in my game world given the player's current location and a normalized direction vector in screen space. My current algorithm is:

1. convert player world location to screen space
2. multiply the direction vector by a large number (2000) and add it to the player's screen location to get the distant screen location
3. convert the distant screen location to world space
4. create a line running from the player's world location to the distant world location
5. loop over the bounding "walls" (of which there are always 4) of my game world
    1. check whether the wall and the line intersect
        1. if so, where they intersect is the furthermost point of my game world in the direction of the vector

Here it is, more or less, in code:

```
public Vector2 GetFurthermostWorldPoint(Vector2 directionVector)
{
    var screenLocation = entity.WorldPointToScreen(entity.Location);
    var distantScreenLocation = screenLocation + (directionVector * 2000);
    var distantWorldLocation = entity.ScreenPointToWorld(distantScreenLocation);
    var line = new Line(entity.Center, distantWorldLocation);
    float intersectionDistance;
    Vector2 intersectionPoint;

    foreach (var boundingWall in entity.Level.BoundingWalls)
    {
        if (boundingWall.Intersects(line, out intersectionDistance, out intersectionPoint))
        {
            return intersectionPoint;
        }
    }

    Debug.Assert(false, "No intersection found!");
    return Vector2.Zero;
}

```

Now this works, for some definition of "works". I've found that the further out my distant screen location is, the less chance it has of working. When digging into the reasons why, I noticed that calls to `Viewport.Unproject` could result in wildly varying return values for points that are "far away". I wrote this stupid little "test" to try and understand what was going on:

```
[Fact]
public void wtf()
{
    var screenPositions = new Vector2[]
        {
            new Vector2(400, 240),
            new Vector2(400, -2000),
        };

    var viewport = new Viewport(0, 0, 800, 480);
    var projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, viewport.Width / viewport.Height, 1, 200000);
    var viewMatrix = Matrix.CreateLookAt(new Vector3(400, 630, 600), new Vector3(400, 345, 0), new Vector3(0, 0, 1));
    var worldMatrix = Matrix.Identity;

    foreach (var screenPosition in screenPositions)
    {
        var nearPoint = viewport.Unproject(new Vector3(screenPosition, 0), projectionMatrix, viewMatrix, worldMatrix);
        var farPoint = viewport.Unproject(new Vector3(screenPosition, 1), projectionMatrix, viewMatrix, worldMatrix);

        Console.WriteLine("For screen position {0}:", screenPosition);
        Console.WriteLine("   Projected Near Point = {0}", nearPoint.TruncateZ());
        Console.WriteLine("   Projected Far Point = {0}", farPoint.TruncateZ());
        Console.WriteLine();
    }
}

```

The output I get on the console is:

```
  For screen position {X:400 Y:240}:
     Projected Near Point = {X:400 Y:629.571 Z:599.0967}
     Projected Far Point = {X:392.9302 Y:-83074.98 Z:-175627.9}

  For screen position {X:400 Y:-2000}:
     Projected Near Point = {X:400 Y:626.079 Z:600.7554}
     Projected Far Point = {X:390.2068 Y:-767438.6 Z:148564.2}

```

My question is really twofold:

1. what am I doing wrong with the unprojection such that it varies so wildly and, thus, does not allow me to determine the corresponding world point for my distant screen point?
2. is there a better way altogether to determine the furthermost point in world space given a current world space location, and a directional vector in screen space?

# Answer
Perhaps first find the line intersection in world coordinates, and then convert that point to screen coordinates?
> 1 votes

---
Tags: xna, c#, projection, screen
---


# Question
Title: What is the purpose of mesh optimization functions?
I remember there is a specific function in Direct3D which optimizes a mesh or a 3D object in some way. What is the purpose of this function? How does it reorganize vertices to make it better?

# Answer
> 4 votes
The ID3DXMesh interface had Optimize and OptimizeInPlace methods, which is what I presume you are thinking of. The purpose of these methods was to reorganize the mesh data (vertex buffers, index buffers, et cetera) to improve drawing performance.

The details of the optimization performed depended on various flags you'd specify when you call the function. You can find a list of flags here, which will reveal some of the specifics about the kinds of operations performed.

I'd venture to guess that the specific optimizations weren't documented in detail to allow for flexibility in adjusting them as hardware evolved. However, most of them centered around removing unused or duplicated data (to achieve better bandwidth utilization) and to reorganize the buffers to allow for better cache coherency on the card.

---
Tags: 3d, directx
---


# Question
Title: What revenue models exist for online games?
What revenue models exist for online games?

# Answer
> 46 votes
1. Subscription. The easiest model, where you simply require a sum of money from your players each month. Monthly payments are most common, but variants exist. Most famous example - WoW.
2. Freemium subscription. Essentially the same as subscription, but players CAN play for free with some limitations. For example, non-paying players can't visit all locations, or reach maximum level, or somesuch. Dungeon runners used this model, and Dofus IIRC.
3. Box sales. You simply sell boxed version of your game for some fixed amount, and let players who bought it play forever after. Guild Wars does it; also this model is common among team shooters like TF2 and COD:MW2.
4. In-game advertising. Show some ads to players and hope they bring enough money. I'm not aware of games that use advertising as a single, or biggest, source of income.
5. Microtransactions. You sell some virtual items to your players for trivial (or sometimes not) amounts of cash. Some games only sell "cosmetic" items that do not affect gameplay; some sell "helpers" that make the game a little easier; still others sell all kind of game-breaking uber-weapons and such. Almost all Asian games use this model extensively.
6. Virtual currency. A very special case of microtransactions, this is where in-game virtual currency has a fixed rate of exchange with real-world currency, and can be exchanged both ways. The only game that does it, as far as I know, is Entropia Universe.
7. Server leasing. You sell virtual space in your game, allowing players to have their own place in the game. Second Life uses this model.
8. Merchandise. The game itself is free, and you make money by selling game-related merchandise like posters and t-shirts and the like. Kingdom of Loathing is a game that uses this model.
9. Offer walls. A kind of microtransactions, but instead of selling items for cash, you show your players a "wall" of offers from your partners. Something like "Participate in this online survey, and receive some in-game currency". D&D Online had it at one time, and a lot of social games use this model in addition to simple microtransactions.
10. Offer flash games for free to other portal sites. A very very BIG component for a lot of sites. Used to drive traffic to their main sits. It's essentially exchanging content for a link back to your site. (Added by eLouai)

That's all I can think of at the moment, but I'm sure I missed several more.

# Answer
> 9 votes
Freemium \- Make the bulk of your game available for free, but provide paid premium content (e.g. *Fantastic Contraption* and *Quake Live*). There's obviously a bit of a balancing act with choosing how much to give away for free: you have to make sure you give enough so that they can enjoy the game, but not enough to satiate their appetite.

Adware \- Make your game completely free, but with adverts. Ads could be in-game, around the game canvas (for browser games), or could be shown intermittently throughout the game (like television ads). Note that the viability of this is debatable (*Quake Live* was originally ad-based, but turned to freemium when they realised that they weren't making enough money to cover running costs).

Subscription based \- Players pay a regular subscription fee to play (e.g. most MMORPGs). This could also be complemented with an initial free period (e.g. first month free).

# Answer
> 3 votes
Sponsorship and licensing. Example: Flash Game License.

> "Developers can showcase their games and even get valuable feedback about them, while sponsors can browse an extensive game library, choosing exactly the games that fit their needs."

# Answer
> 2 votes
donations ala the humble indie bundle

# Answer
> 1 votes
Micropayments \- allow users to buy in-game items & perks for tiny sums of money.

# Answer
> 0 votes
1. Ads
2. subscriptions
3. sell items, perks, etc.

# Answer
> 0 votes
Crowd source funds using the rewards model. That way people pay you to write the game with up-front money.

---
Tags: online, monetization, business, business-model, revenue
---


# Question
Title: Do game studios hire people based on their math knowledge alone?
I have very little programming skills outside of very basic levels of Java, but I have excellent math and science knowledge. I was wondering what I could offer any potential team if I were to go into video game development? Do people hire people based on their math knowledge alone?

I like to do other things such as writing or drawing, but math and science are the only skills in which I really excel in.

# Answer
> 14 votes
Here is an analogy that may fit your situation:

> I'm a very good story teller. But my audience are Spanish speakers and I only have very basic Spanish speaking skills.

That's the situation you're in. You are very good at one of the core concepts required for graphics/physics/AI programming. But you don't know the language (programming). **If you don't know the language your audience requires, then you'll never be able to apply your skills to that audience.**

So, while you might be able to find a job in the games industry, that company would essentially need some interpreters to work with you. Converting your knowledge into workable code. You'd be far more valuable if you spoke the language too.

# Answer
> 12 votes
> Do people hire people based on their math knowledge alone?

Math is very useful to game developers (programmers developing physics algorithms, designers analyzing stats, etc.) but game companies don't hire mathematicians.

# Answer
> 2 votes
Video game is:

* Physics - Heavy Math
* Graphics - Heavier Math
* I/O - abstracted, simplemath
* Complexity Analysis and Optimization- Moderate Math
* GUIs - simple geometry
* Networking? - Moderate math

If you will be making a game you will be doing math.

If you are exceptionally good at math and science, people would need you to implement their physics frameworks, and graphics can become quite complicated mathematically depending on how fancy the desired effect is. So yes you are a desirable asset as a mathematician, but simple high-school math is good enough to solve most problems in games, especially if the team in question is using a 3rd party game engine and doesn't care about the internals.

# Answer
> 2 votes
Given the interesting conversations on this thread, I've decided to look a bit further into this topic in order to achieve several things. First off, to answer your original questions and secondly to address what appears to be the underlying subject of your interest to enter into game development.

As many people here have stated, 'pure' knowledge of Mathematical concepts at an expert level without any proven software development experience will not prohibit you from getting into the Game Development career track. I would argue that it will significantly limit your options in the process of attempting to get in the door of an exclusive top tier game dev studio. My initial arguments were based on the intent to not deter you from the basis of your original question which was your 'interest' in approaching the field of game dev.

So what I would suggest is that you look further into the subject. Here are some examples of what is currently active in the market based on the search criteria "Mathematician games" on Indeed.com:

http://www.indeed.com/jobs?q=Mathematician+games&l=

Given the time sensitive nature of the link, i've compiled some of the examples below:

> Multimedia Games
>
> **Game Design Mathematician II** Engineering | Austin, TX
>
> Responsibilities Include: providing detailed mathematical analysis of semi-complex games; developing mathematical or statistical models of games to test pay table math models for functionality and adherence to specifications; applying programming principles to create game simulations and calculation programs; developing gaming probabilities and payout tables; performing analysis of game performance and simulations of gaming results; developing production math for proprietary bingo, lottery, and traditional math systems for original titles and platform conversions; documenting the probabilities and statistics for developed games, including par sheets; working with software development teams to ensure correct implementation of games math; developing original game play mechanics; and providing feedback and direction on game concepts.

*Note that this job is filed under "Engineering" and not "Computers/Software" on their site so their company makes a distinction between Software Development and Engineers. In this case, I would argue that your understanding of Java would only be helpful and desirable. Also notice that the role of the position appears to be based on Statistics for casino based games but it supports your original question.*

> Scientific Games
>
> **Senior Game Mathematician**
>
> Department: Video Gaming - Executive Location: Reno, NV
>
> At Scientific Games, we look for people driven by a desire to contribute, be challenged and grow. Our people make Scientific Games a special company and are a key competitive advantage. We are seeking a person to apply their exceptional analytical skills as well as their knowledge of advanced methods and probabilities to ensure a quality math product design for our Video Gaming Machine and Route Gaming System solutions for the growth of our exhilarating Video Gaming business units.
>
> The Senior Game Mathematician provides detailed mathematical description and analysis of gaming products. Designs game specifications and math models and calculates payback percentage, odds and other regulated parameters to ensure accurate payouts and compliance with gaming regulations. Develops mathematical models of games to test the pay table math for functionality and adherence to specifications. Applies programming principles to create game simulations and calculation programs and other duties as assigned. Responsibilities as assigned by the Vice President of Product Development

Here we have another position for casino games. Maybe we are starting to see a trend? So what does that mean to you... Well, firstly it might not be exactly what you are looking for. Is your goal to make good money? If yes then it might mean you can be very successful being involved in the process of creating games played by many people based solely on your background in math. Is your interest in working for a top tier game studio creating the next Gears of War?

If that's your goal then I would argue that once you start down the path of building games for the Casino industry that you could potentially harm your ability to do anything outside of this area. One potential pitfall that you have to think about is getting 'siloed' into a specific career path that makes it difficult to pivot into another area in the same field. It's a potential issue but **nothing i'm stating here is applicable for every situation**. Some will argue against my points given their specific experience. All I aim to provide you with is 'my' specific experience in corporate software development for the past 12 years.

> Konami
>
> **Mathematician** Location: Las Vegas, NV
>
> Department: Research & Development (Games) Description: The Mathematician researches and studies statistically gaming products and creates mathematical models for one or more games on a project basis.
>
> Duties: • Creates the mathematical models of game production based off of corporate directives. • Consults with game designer to develop and complete game themes. • Contributes innovative and original ideas to game or game design team. • Analyze statistically existing or new games and report to game design team. • Maintain proper mathematical models, utilizing Windows based PCs and MS Office. • Facilitates the distribution of approved mathematical material and files to support product release. • Prepares relevant mathematic information for presentation needs, executive review, testing and compliance requirements. • Answer to relevant mathematic questions for game designer, engineer, sales, testing and compliance requirements. • Provides all mathematical resource materials as needed to produce game. • Reports to group leader any discrepancies or problems requiring resolution. • Complies with the company’s regulatory guidelines and corporate policies at all times. • Maintains confidentiality regarding the company, products and employee information.
>
> **Qualifications: Bachelor’s degree in Mathematics or equivalent experience; clear understanding of statistics. Professional working experience in gaming industry or professional programming experience preferred.**

Ok, now it's starting to get interesting. Just look at Konami's site. I think everyone here know who they are and what they've published. But wait, the job is for what? "Casino Games"... Here I would argue that last comment regarding the possibility to 'pivot' inside a company. This is a perfect example of "Getting your foot in the door" and would support the idea of developing your skills in software development alongside having a career with a top tier game company during the day. Remember, you can always learn how to become a good software developer on your 'own time'. I basically learned how to write software on my own and you can do so as well.

Some other points to remember, this is a huge company and can be very selective on who they hire so they emphasize have previous experience and 'shipped games' but that is boilerplate copy that's used on every job opening they have and is not to say that the hiring manager is looking for someone right out of school who is **eager to learn and work hard**. Remember that with experience comes other issues that a hiring manager has to worry about that aren't there with a new hire out of school (potentially: Require pay at higher tier than desirable, potential turnover due to reasons not present in someone right out of school, etc..)

So if you look at the Indeed job list, many of the Math related jobs are in the Casino Industry but hopefully I've given you some scenarios that help you make a good decision but based on some of my original comments, I said that if you are good at math, in theory you should be able to grasp programming at a competent level. What I would also mention if that with any skill/trade, it takes time to get good but it **doesn't mean you can't** get into the game industry. You just have to work at it and your background in math will only help you if you decide to.

Here are a few more examples of Mathematicians being cited by companies with a gaming/graphics focus:

> **DirectX/C++/XML Lead Programmer/Expert** Job is for a Lead Game Programmer but in the responsibilities:
>
> **Collaborate with artists, mathematicians, and other programmers and engineers to suggest enhancements and refinements, test prototypes, and implement fine-tuned game features.**

Another example of Mathematicians being involved in the process of 'implementing game features'.

> High5 Games Backend Developer @ leading social & casino games company
>
> EDUCATION / EXPERIENCE:
>
> Bachelor’s Degree in Computer Science/**Math** and/or Electrical Engineering required; Master’s Degree preferred. Minimum of 3+ years in field and related area.
>
> Company Description High 5 Games is the leading content developer of the gaming industry, selling its engaging products and trademarked concepts to many of the biggest distributors in the world. H5G has patented several unique concepts that have revolutionized the gaming community, and has created more than 100 games that appear in hundreds of casinos over five continents, in places such as Las Vegas, Paris, Madrid, Macau and Buenos Aires. Every H5G product starts out as an idea. From our **talented mathematicians**, software engineers and programmers who construct the necessary platform to the artists whose imaginations allow them to craft intricate new worlds - life at H5G is anything but ordinary – as are the games the company creates. We are an eclectic, talented group of individuals and are always looking for capable people to help grow our business. High 5 Games has produced many of the most popular games in the casino industry – including Cats, Secrets of the Forest, Da Vinci Diamonds, Sirens, Michelangelo, Witches Riches, and White Orchid. In its history, H5G has licensed its products out to several companies, including IGT, Caesars Gaming, Bally Technologies, WMS Gaming, Sigma Gaming, Konami Gaming, Action Gaming, Hasbro, and AC Coin & Slot. As the gaming landscape transforms, High 5 Games has also been an active leader in the internet gaming industry, with its games featured on several legal European websites through WagerWorks / IGT Interactive. We invite you to come visit our website at www.h5g.com and learn more about our company.

Here's another good example of getting your foot into the door. High5 says they employ Mathematicians AND they have licensed games to Konami so say you land a job at High5 and work there for 5 years and then apply at Konami for a job as a Game Developer after you get better with your software skills. It would look good that you have experience with a company that Konami has a business relationship with. You could even interface directly with a team at Konami while working at High5. You could also say that you have 'shipped games' @ High5 even if your role was just as a Mathematician.. you had a role in the game being shipped and you can take credit as such.

So what should you take away from this research? Well, I can only give you my opinion and from the short amount of time I spent on this, the answer to your original question is **YES**, companies that create games hire Mathematicians. Is it the type of games you want to create? I don't have those answers for you but one thing I would suggest is to be careful when making a decision. I can only guess that the Casino Industry is a crazy place to work for, even as a Mathematician or Software Developer but from above, you can see some options for eventually working on mainstream games on consoles and handhelds. Don't sell yourself short, I think it's highly possible to end up as a game developer with just a degree in math. It will take work on your part but it's definitely doable.

# Answer
> 0 votes
Big game studios don't hire pure mathematicians. Considering the question, people with very advanced math skills are a must for developing new technologies. The very best are actually skilled academic researchers, capable to code and deliver at least decent demo applications of their algorithm.

I can only pledge for one thing a game developing company (a big one!) is looking for: a talented and research oriented person that aims to improve and devise new algorithms in these fields: plausible/realistic physics at interactive frame-rates, graphics tricks that introduce a plethora of eye candy effects while making use of less memory and time, excellent knowledge about how things should be communicated on certain network topologies and so on..

Even a state of the art method/algorithm, before it makes it into the gaming industry, it is chopped down a lot, modified for speed and when you look at the actual implementation of that method and compare it with the technical documents/papers/articles it was published in, you will be astonished by how many details are not provided or by what other very complicated tricks are also used. This usually happens a lot. If you have an unique talent for APPLIED mathematics, you can study a field (Game Physics, Rendering) and select a few topics that appeal to you, then go through the state of the art reviews and see how much you understand from those. Knowing what has been done, try to understand the drawbacks and think of, perhaps, ground-breaking, never seen ideas that solve the problem at least 2x better. Then your way is paved, they'll just have to hire a guy to code the algorithms for you. Maybe that's what Havok did (I doubt it, the Havok guys started off as Trinity College Dublin PhD students and had very solid advanced Math skills).

---
Tags: mathematics, career
---


title: 2D Collision masks for handling slopes

text:
# Question
Title: 2D Collision masks for handling slopes
I've been looking at the example at: http://create.msdn.com/en-US/education/catalog/tutorial/collision\_2d\_perpixel and am trying to figure out how to adjust the sprite once a collision has been detected. As David suggested at Sidescroller variable terrain heightmap for walking/collision, I made a few sensor points (feet, sides, bottom center, etc.) and can easily detect when these points actually collide with non-transparent portions of a second texture (simple slope). I'm having trouble with the algorithm of how I would actually adjust the sprite position based on a collision.

Say I detect a collision with the slope at the sprite's right foot. How can I scan the slope texture data to find the Y position to place the sprite's foot so it is no longer inside the slope? The way it is stored as a 1D array in the example is a bit confusing, should I try to store the data as a 2D array instead? For test purposes, I'm thinking of just using the slope texture alpha itself as a primitive and easy collision mask (no grass bits or anything besides a simple non-linear slope). Then, as in the example, I find the coordinates of any collisions between the slope texture and the sprite's sensors and mark these special sensor collisions as having occurred. Finally, in the case of moving up a slope, I would scan for the first transparent pixel above (in the texture's Ys at that X) the right foot collision point and set that as the new height of the sprite.

I'm a little unclear also on when I should make these adjustments. Collisions are checked on every game.update() so would I quickly change the position of the sprite before the next update is called?

I also noticed several people mention that it's best to separate collision checks horizontally and vertically, why is that exactly?

Open to any suggestions if this is an inefficient or inaccurate way of handling this.

I wish MSDN had provided an example of something like this, I didn't know it would be so much more complex than NES Mario style pure box platforming!

# Answer
**Basic approach**

Querying the texture directly might be slow so I would probably store the collision mask separately. The format in which you store it is not that relevant. I don't see any problem with storing it as a 2D array as you mentioned. Something like this for instance would be enough:

```
// Use bool or byte to save space
bool[,] collisionMask = new bool[TileWidth, TileHeight];

```

At load-time I would create all of the mask arrays from the alpha channel of the tile textures but only *once* for each *type* of tile. In other words, do not store this information inside each individual tile, but store it in the tileset instead.

As for scanning for the correct position for the character to stand on, I would just do it the brute-force way - query the mask at the same position as your foot sensor sensor, and then move up pixel by pixel until you find a non-blocked one. Then move your character up by that same amount.

Since tiles probably won't be too big, I don't think there will be much of a performance problem with this simple approach.

**But it's possible to simplify it in some cases**

Depending on the variability of your tiles it's possible that you could simplify the way you store your information a lot. For instance if your tiles always start from the bottom and don't have holes in them you could store their collision masks as a single one dimensional height map array:

```
// Essentially an height map for the tile type
byte[] collisionMask = new byte[TileWidth];

```

Or if they don't always start from the bottom but still don't have holes or multiple "islands" you could store it as:

```
// Use Point.X for bottom height and Point.Y for top height
Point[] collisionMask = new Point[TileWidth];

```

So it all depends on how complex you want your tiles to be.

**When to move the character**

> I'm a little unclear also on when I should make these adjustments. Collisions are checked on every game.update() so would I quickly change the position of the sprite before the next update is called?

Yep. First you move your character. Then you have the collision detection phase, and finally the collision *response* phase. That's essentially what you'll be doing by moving the character up outside the tile.

**Separate axis handling**

> I also noticed several people mention that it's best to separate collision checks horizontally and vertically, why is that exactly?

That's not really much of a problem here because your foot sensor collision response will always be moving the character *up*. You'll be handling collisions with walls separately anyway, using the middle sensor.

I've made this picture for another question but I'll repost it here for context:

Basically if you move diagonally all at once, it can create an ambiguity where the algorithm needs to guess in which direction it should push out of the tile. It's possible to make it intelligent enough to always use the correct direction, but it's easier to just handle movement in each axis separately, as there's no ambiguity that way.
> 2 votes

# Answer
I haven't used XNA and I also haven't thoroughly read your topic, but anyway.

They way I did it (in AS3, but that doesn't matter) is to get the vector of the slope.

Say you want a 45 degrees slope. To get the vector, you just do this:

```
the slope's X - the character's X = the character's Y

```

So, `y=(slope.y-tileHeight/2)+slope.x(+tile width/2)-x(+character width/2)`

and then compensate the character's height, so `-charHeight/2`

and for mirrored slopes, you do this:

```
y=x-slope.x+tileWidth/2

```

Do you get the basic idea? So, the closer the character gets to the right or left side of a slope, how higher the character gets. I find this method a lot more reliable than checking for pixels. Though there is one problem with this, you'll have to make all the angles individually. Not sure if that's a problem for you...

If you still don't get it, don't be afraid to ask!
> 0 votes

---
Tags: xna, 2d, collision-detection, textures, data
---


# Question
Title: How can I imitate interaction and movement in Diablo II?
I'm prototyping a simple browser-based game. It's played from a top down perspective on a 2d canvas.

You left-click on a point on the map, and your character will begin walking to it. If you click on a different point on the map, then your character will begin walking to the new point.

It's similar to Diablo II. (a demonstration video)

How can I best imitate this movement system for a player? Ideas...

* Track current coords and target coords
* If target coords are exactly up, left, right, or down, then increment appropriate direction until you get there
* Implied else: target coords are in a quadrant. To make this movement look natural, character will have to move diagonally. For example, pretend the target is to the northeast. For each game frame, alternate incrementing current coordinates in the north and then east directions.

# Answer
> 2 votes
Your procedure sounds o.k. Whenever the user clicks somewhere on the canvas/map, take the players current position as starting-point and move to the clicked tile.

Instead of having different cases for straight and diagonal movement, you could use the Bresenham's line algorithm to get an optimal line from `A` to `B`.

This is all going to fall apart as soon as you introduce obstacles though (walls, trees, etc.). If that's the case, I suggest you implement some path-finding algorithm to find the path around the obstacles.

# Answer
> 1 votes
Are you familiar with graph theory concepts? Do some googling if you are not familiar.

Diablo II is a tile-based game using isometric tile rendering (as opposed to say Pokemon which is orthographic).

So, your map will need to be split up into tiles. Each tile would be a node in the graph with edges connecting to adjacent tiles. To move from tile A to tile B, you would run some sort path finding algorithm to determine which tiles your character should be walking on to get from A to B while avoid obstacles that occupy a number of tiles. Your character may not walk actual geometric shortest distance so to get a smoother path you need smaller tiles at a performance cost. For some advanced techniques you can refer to this paper which compares performance of several tile formats (hex, octal, square).

If you have no idea what I'm talking about then you probably want to start with something simpler...

# Answer
> 1 votes
I'm pretty sure Diablo allowed diagonal movement. (even though the sprites only faced in discrete directions, movement was basically in any direction). Remember the movement is based on vectors and depends on current framerate as well as character speed.

so basically:

```
on click(x,y):
   direction = {x: x-player.x, y:y-player.y}
   direction = normalize(direction)

on updateframe(elapsedms):
   multiplier = elapsedms / 1000 * player.movespeed
   player.x += direction.x * multiplier
   player.y += direction.y * multiplier

```

# Answer
> 0 votes
I don't know how experienced you are in JS/HTML5 for game design, but this site, it's isometric examples will explain how to make the needed functions for coords and moving around a map. Also how to do collision detection and map editing stuff.

Although the examples are in isometric the functions apply to any graphical game with the similar concepts. The only difference to non-isometric games to isometric games is the maths you apply in the functions. As you aim to do a top down view, the maths is much simpler... isometric is a bit of a mind twister at first.

# Answer
> 0 votes
You might check out how Mozilla's HTML5 game BrowserQuest implemented movement, as it works just like this, and the code is open source and well documented. For example, here is BrowserQuest's pathfinding function.

---
Tags: javascript, html5
---


# Question
Title: What is the best method to serve a real time game on websockets?
The game consists of a world with just one force, gravity. All the players can do is jump and set their velocities with arrow keys. Physical AABBs and sphere's are used for collision.

What is the best method to serve this game on websockets? Dead-reckoning? Sending positions only for play back?

# Answer
> 4 votes
Refer to this article: http://gafferongames.com/game-physics/networked-physics/

In short:

> Physics is run on the server according to a stream of input from clients

This means the actual physics/collision runs on the sever, and client simply sends player input and renders server output to screen. Server continuously broadcasts required rendering information per physics update like object positions.

This is not very simple though several problems/solutions are discussed in the article such as player input lag and choppy client side visuals.

---
Tags: websocket
---


# Question
Title: Resultant Vector Algorithm for 2D Collisions
I am making a Pong based game where a puck hits a paddle and bounces off. Both the puck and the paddles are Circles. I came up with an algorithm to calculate the resultant vector of the puck once it meets a paddle. The game seems to function correctly but I'm not entirely sure my algorithm is correct. Here are my variables for the algorithm:

**Given:**
velocity = the magnitude of the initial velocity of the puck before the collision
x = the x coordinate of the puck
y = the y coordinate of the puck
moveX = the horizontal speed of the puck
moveY = the vertical speed of the puck

otherX = the x coordinate of the paddle
otherY = the y coordinate of the paddle
piece.horizontalMomentum = the horizontal speed of the paddle before it hits the puck
piece.verticalMomentum = the vertical speed of the paddle before it hits the puck

slope = the direction, in radians, of the puck's velocity
distX = the horizontal distance between the center of the puck and the center of the paddle
distY = the vertical distance between the center of the puck and the center of the paddle

**Algorithm solves for:**
impactAngle = the angle, in radians, of the angle of impact.
newSpeedX = the speed of the resultant vector in the X direction
newSpeedY = the speed of the resultant vector in the Y direction

---

Here is the code for my algorithm:

```
int otherX = piece.x;
int otherY = piece.y;
double velocity = Math.sqrt((moveX * moveX) + (moveY * moveY));

double slope = Math.atan(moveX / moveY);
int distX = x - otherX;
int distY = y - otherY;

double impactAngle = Math.atan(distX / distY);

double newAngle = impactAngle + slope;
int newSpeedX = (int)(velocity * Math.sin(newAngle)) + piece.horizontalMomentum;
int newSpeedY = (int)(velocity * Math.cos(newAngle)) + piece.verticalMomentum;

```

for those who are not program savvy here is it simplified:

```
velocity = √(moveX² + moveY²)
slope = arctan(moveX / moveY)
distX = x - otherX
distY = y - otherY

impactAngle = arctan(distX / distY)

newAngle = impactAngle + slope
newSpeedX = velocity * sin(newAngle) + piece.horizontalMomentum
newSpeedY = velocity * cos(newAngle) + piece.verticalMomentum

```

**My Question:**
Is this algorithm correct? Is there an easier/simpler way to do what I'm trying to do?

# Answer
As I said in the comments, for games, all you need is "it seems to function correctly".

I'm not sure if your code is correct (looks a bit off, but I haven't looked at it too closely).

Here's a more efficient formula that avoids trig and square roots:

math formula http://mathbin.net/equations/91525\_0.png

Simplifying into components, where:

distX equation http://mathbin.net/equations/91527\_0.png, same for y:

http://mathbin.net/equations/91527\_1.png

http://mathbin.net/equations/91527\_2.png

In code:

```
 int otherX = piece.x;
 int otherY = piece.y;
 int distX = x - otherX;
 int distY = y - otherY;
 double dotprod=(distX*moveX+distY*moveY)/(distX*distX+distY*distY)
 newSpeedX=2distX*dotprod+moveX
 newSpeedY=2distY*dotprod+moveY

```

## For `newAngle`

AFAICT, you only need this variable for calculating the velocities, but if you need it for something else as well, you may use this:

`newAngle` can be calculated by:

newAngle calculation http://mathbin.net/equations/91528\_0.png

Simplified,

simplified newAngle calculation http://mathbin.net/equations/91529\_0.png

In code:

```
newAngle=arccos(dotprod*Math.sqrt((distX*distX+distY*distY)/(moveX*moveX+moveY*moveY)))

```

Or, you could use your old method to calculate newAngle, this one involves an inverse trig function and a square root, while yours involves two inverse trig functions--pretty much the same load on the computer IMO (both functions are solved via power series usually).
> 1 votes

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


# Question
Title: How to move a line of sprites in a sine wave?
So, I'm spawning a horizontal line of enemies that I would like to have move in a nice wave. Currently I tried:

```
 Enemy.position.X += Enemy.velocity.X;
 Enemy.position.Y += -(float)Math.Cos(Enemy.position.X / 200) * 5;

```

This...kind of works. But the wave is not a true wave. The top and bottom of one pass are not the same (e.g. 5 for the top, and -5 for the bottom (I don't mean literal points, I just meant that it's not symmetrical)).

Is there a better way to do this? I would like the whole line to move in a wave, so it looks fluid. By that, I mean that it should look like each enemy is "following" the one in front of it. The code I posted does have this fluidity to it, but like I said, it's not a perfect wave.

Any ideas?

Thanks in advance.

# Answer
Perhaps it's as simple as:

```
Enemy.position.X += Enemy.velocity.X;
Enemy.position.Y = -(float)Math.Cos(Enemy.position.X / 200) * 5;

```

Notice the `Enemy.position.Y` is just using `=` not `+=`

**EDIT**

Try with this instead:

```
Enemy.position.Y = -(float)Math.Cos(Enemy.position.X / 100);

```

**EDIT again**

With offset to put 0 at the middle of your window:

```
Enemy.position.Y = -(float)Math.Cos(Enemy.position.X / 100) + ScreenHeight/2;

```

OR

```
Enemy.position.Y = StartPosition.Y + (-(float)Math.Cos(position.X / 100) * 100);

```

As you found that to work.
> 4 votes

# Answer
It should be as simple as: `Enemy.position.Y = -(float)Math.Sin(Enemy.position.X)`, no?

This assumes you have a wave of enemies that move horizontally. The path of motion would be the exact same as the plot of y = sin x, or rather Enemy.position.Y = sin(Enemy.position.X).
> 0 votes

---
Tags: xna, 2d, mathematics
---


title: How can I load .FBX files?

text:
# Question
Title: How can I load .FBX files?
I am looking into options for the model assets for my game. I have gotten pretty good with Blender, and want to use C++/DirectX9 (don't need all the excess from 10+), but Blender 2.6 exports .fbx not .x (by nature) and supposedly what is exported from Blender to .x is not entirely stable.

In short how do I import .fbx models (I can work around not having animations if I must) into DirectX9? Is there a middleware, or conversion tool that will maintain stability?

# Answer
The canonical middleware for loading and manipulating FBX data in C++ would likely be the official FBX SDK from Autodesk.
> 5 votes

---
Tags: directx, blender, fbx
---


title: How are these bullets done?

text:
# Question
Title: How are these bullets done?
I really want to know how the bullets in Radiangames Inferno are done. The bullets seem like they are just billboard particles but I am curious about how their tails are implemented. They can curve so this means they are not just a billboard. Also, they appear continuous which implies that the tails are not made of a bunch of smaller particles (I think).

Can anyone shead some light on this for me?

# Answer
> 3 votes
It's easy enough if you're doing 2D with a 3D API, and can draw textured polygons.

Store a history of previous positions, use these to build a triangle strip along the bullet's path. Then texture it, and draw with additive blending

(However, if the bullets make any sharp turns, or you need wide trails, it may get more interesting - you'll have problems creating clean geometry without unwanted overlaps)

# Answer
> 0 votes
One of the many awesome features of XNA is that you can apply texture shaders to 2D sprites, enabling you to achieve cool effects like the one in the image. XNA is based on Direct3D, so you have access to any shaders written in HLSL (High-level Shader Language). If you are new to shaders and their applications, check out this awesome MSDN article that explains how to actually implement them in an XNA draw call.

This site contains an awesome example of a Gaussian blur post-processing effect that can probably be tweaked around a bit to achieve an effect like the one pictured. Note that this particular shader is written in GLSL, however, so while the concepts remain constant, the syntax will differ ever slightly from HLSL.

---
Tags: xna, particles
---


title: Whole map design vs. tiles array design

text:
# Question
Title: Whole map design vs. tiles array design
I am working on a 2D RPG, which will feature the usual dungeon/town maps (pre-generated).

I am using tiles, that I will then combine to make the maps. My original plan was to assemble the tiles using Photoshop, or some other graphic program, in order to have one bigger picture that I could then use as a map.

However, I have read on several places people talking about how they used arrays to build their map *in the engine* (so you give an array of x tiles to your engine, and it assemble them as a map). I can understand how it's done, but it seems a lot more complicated to implement, and I can't see obvious avantages.

What is the most common method, and what are advantages/disadvantages of each?

# Answer
First off, let me say that 2D RPGs are near and dear to my heart and working with old DX7 VB6 MORPG engines (don't laugh, it was 8 years ago, now :-) ) is what first got me interested in game development. More recently, I started converting a game I worked on in one of those engines to use XNA.

That said, my recommendation is that you use a tile-based structure with layering for your map. With any graphics API you use, you're going to have a limit on the size of textures you can load. Not to mention the graphics card texture memory limits. So, considering this, if you want to maximize the size of your maps while not only minimizing the amount and size of textures you load into memory but also decreasing the size of your assets on the user's hard drive AND the load times, you're definitely going to want to go with tiles.

As far as implementation goes, I've gone into detail on how I handled it on a few questions here on GameDev.SE and on my blog (both linked below), and that's not exactly what you're asking so I'll just go into the basics here. I'll also make note of the features of tiles that make them beneficial over loading several large pre-rendered images. If anything is not clear, let me know.

1. The first thing you need to do is create a tilesheet. This is just a big image that contains all your tiles aligned in a grid. This (and maybe an extra one depending on the number of tiles) will be the only thing you need to load. Just 1 image! You could load 1 per map or one with every tile in the game; whatever organization works for you.
2. Next, you need to understand how you can take that "sheet" and translate each tile into a number. This is pretty straightforward with some simple math. Note that the division here is *integer division*, so the decimal places are dropped (or rounded down, if you prefer).
3. OK, now that you've broken the tilesheet into a series of cells (numbers), you can take those numbers and plug them into whatever container you like. For the sake of simplicity, you can just use a 2D array.

```
int[,] mapTiles = new int[100,100]; //Map is 100x100 tiles without much overhead

```
4. Next, you want to draw them. One of the ways you can make this a LOT more efficient (depending on map size) is to calculate only the cells that the camera is currently viewing and loop through those. You can do this by fetching the map tile array coordinates of the camera's top-left (`tl`) and bottom-right (`br`) corners. Then loop from `tl.X to br.X` and, in a nested loop, from `tl.Y to br.Y` to draw them. Example code below:

```
for (int x = tl.X; x <= br.X;x++) {
    for (int y = tl.Y; y <= br.Y;y++) {
        //Assuming tileset setup from image
        Vector2 tilesetCoordinate = new Vector2((mapTiles[x,y] % 8) * 32,(mapTiles[x,y] / 8) * 32);
        //Draw 32x32 tile using tilesetCoordinate as the source x,y
    }
}

```
5. Jackpot! That's the basics of the tile engine. You can see that it's easy to have even a 1000x1000 map with not much overhead. Also, if you have less than 255 tiles, you could use a byte array cutting down the memory by 3 bytes per cell. If a byte is too small, a ushort would probably suffice for your needs.

Note: I left out the concept of world coordinates (which is what your camera's position will be based on) since that, I think, is outside the scope of this answer. You can read up on that here on GameDev.SE.

**My Tile-Engine Resources**
Note: All of these are targeted at XNA, but it pretty much applies to anything – you just need to change the draw calls.

* My answer to this question outlines how I handle the map cells and layering in my game. (See third link.)
* My answer to this question explains how I store the data in a binary format.
* This is the first (well, technically second, but first "technical") blog post about the development of the game I was working on. The whole series contains information about things like pixel shaders, lighting, tile behaviours, movement and all that fun stuff. I actually updated the post to include the content of the my answer to the first link I posted above, so you may want to read it instead (I may have added things). If you have any questions, you can drop a comment there or here and I'd be happy to help.

**Other Tile-Engine Resources**

* The tile engine tutorial from this site gave me the basis I used for creating my maps.
* I haven't actually watched these video tutorials yet because I haven't had the time, but they're probably helpful. :) They may be outdated though, if you're using XNA.
* This site has some more tutorials that (I think) are based on the above videos. It may be worth checking out.
> 19 votes

# Answer
Both tile based systems and a static model/texture system can be used to represent a world and each has different strengths. Whether one is better than the other boils down to how you use the pieces, and what works best for your skillset and needs.

That being said both systems can be used separately, or also together.

A standard tile based system has the following strengths:

* Simple 2D Array of tiles
* Each tile has a single material
    + This material may be a single texture, multiple, or blended from surrounding tiles
    + Can re-use textures for all tiles of that type, reducing asset creation and rework
* Each tile can be passable or not (collision detection)
* Easy to render and identify parts of the map
    + Character position and map position are absolute coordinates
    + Simple to loop through relevant tiles for screen region

The disadvantage to tiles is that you have to create a system for building this tile based data. You could create an image that uses each pixel as a tile, thus creating your 2D array from a texture. You could also create a proprietary format. Using bitflags you can store a large number of data per tile in a fairly small space.

The primary reason most people do tiles is because it allows them to create small assets and re-use them. This allows you to create a much larger picture will smaller pieces. It reduces rework because you are not changing the entire world map to make a small change. For example if you wanted to change the shade of all the grass. In a large image you would have to repaint all the grass. In a tile system you just update the grass tile(s).

All-in-all you will find yourself likely doing a lot less rework with a tile based system than a large graphical map. You may end up using a tile based system for collision even if you don't use it for your ground map. Just because you use a tile internally doesn't mean you can't use models to represent the objects of the environment which may use more than 1 tile for their space.

You would need to provide more specifics on your environment/engine/language to provide code examples.
> 6 votes

# Answer
Drawing the map: Tiles are easy on the engine, because then the map can be represented as a giant array of tile indices. Draw code is just a nested loop:

```
for i from min_x to max_x:
    for j from min_y to max_y:
        Draw(Tiles[i][j], getPosition(i,j))

```

For large maps, one huge bitmap image for the entire map could take up a lot of space in memory, and could be larger than what a graphics card supports for a single image size. But you won't have any issues with tiles because you only allocate graphics memory once for each tile (or one total, optimally, if they're all on one sheet)

It's also easy to reuse the tile information for e.g. collisions. for example, to get the terrain tile at the top-left corner of the character's sprite:

```
let x,y = character.position
let i,j = getTileIndex(x,y) // <- getTileIndex is the opposite function of getPosition
let tile = Tiles[i][j]

```

Suppose you need to check for collisions against rocks/trees etc. You can get the tile at the position of the (character position + character sprite size + current direction) and check if it's marked as walkable or not walkable.
> 3 votes

---
Tags: tiles, maps
---


# Question
Title: Why can't a blendShader sample anything but the current coordinate of the background image?
In Flash, you can set a DisplayObject's blendShader property to a pixel shader (flash.shaders.Shader class).

The mechanism is nice, because Flash automatically provides your Shader with two input images, including the background surface and the foreground display object's bitmap.

The problem is that at runtime, the shader doesn't allow you to sample the background anywhere but under the current output coordinate. If you try to sample other coordinates, it just returns the color of the current coordinate instead, ignoring the coordinates you specified. This seems to occur only at runtime, because it works properly in the Pixel Bender toolkit.

This limitation makes it impossible to simulate, for example, the Aero Glass effect in Windows Vista/7, because you cannot sample the background properly for blurring.

I must mention that it is possible to create the effect in Flash through manual composition techniques, but it's hard to determine when it actually needs updated, because Flash does not provide information about when a particular area of the screen or a particular display object needs re-rendered. For example, you may have a fixed glass surface with objects moving underneath it that don't dispatch events when they move. The only alternative is to re-render the glass bar every frame, which is inefficient, which is why I am trying to do it through a blendShader so Flash determines when it needs rendered automatically.

**Is there a technical reason for this limitation, or is it an oversight of some sort? Does anyone know of a workaround, or a way I could provide my manual composition implementation with information about when it needs re-rendered?**

The limitation is mentioned with no explanation in the last note in this page: http://help.adobe.com/en\_US/as3/dev/WSB19E965E-CCD2-4174-8077-8E5D0141A4A8.html It says:

> "**Note:** When a Pixel Bender shader program is run as a blend in Flash Player or AIR, the sampling and outCoord() functions behave differently than in other contexts.In a blend, a sampling function will always return the current pixel being evaluated by the shader. You cannot, for example, use add an offset to outCoord() in order to sample a neighboring pixel. Likewise, if you use the outCoord() function outside a sampling function, its coordinates always evaluate to 0. You cannot, for example, use the position of a pixel to influence how the blended images are combined."

# Answer
> 0 votes
It's because "blend shaders" are things that don't actually exist.

Imagine if someone decided to implement "vertex shaders" in say, the GeForce 256. There's no hardware support for them, so it would either be implemented on the CPU, or the language would have to have a *lot* of limitations. Vertex positions would have to pass through one or two matrix multiples; you couldn't do any other math to them. Texture coordinates could get exactly one matrix multiply. Or you could take texture coordinates by multiplying the vertex position by a matrix. Or you could use a special function to generate it. But you couldn't use regular math.

And so on.

There are no "blend shaders" in real hardware. Therefore, a blend shader is bound by the limitations of the actual hardware, which doesn't allow for programmable blending. Blending hardware operates on a specific sample(s) within a specific pixel. It is given a value from the fragment/pixel shader, and it is given a value from the framebuffer. Any apparent additional functionality from blend shaders is carefully created by modifying the actual fragment/pixel shader used by the hardware.

Even so, you're still stuck with the basic limitations of blending.

---
Tags: shaders, actionscript-3, blending, fragment-shader
---


title: How to render 2D particles as fluid?

text:
# Question
Title: How to render 2D particles as fluid?
Suppose you have a nice way to move your 2D particles in order to simulate a fluid (like water). Any ideas on how to render it?

This is for a 2D game, where the perspective is from the side, like this. The water will be contained in boxes that can be broken in order to let it fall down and interact with other objects. The simplest way that comes to my mind is to use a small image for each particle. I am interested in hearing more ways of rendering water.

# Answer
Check out how PixelJunk Shooter did it (including simulation) in this presentation (PDF) at GDC2010.

---
> 28 votes

# Answer
George Duckett's answer is far more direct and really well presented if you need fully-simulated water in your game. For simulated shallow-water physics with minimal accuracy (less realism, more playful), this image gave me an incredible moment of clarity:

http://www.patrickmatte.com/stuff/physicsLiquid/
> 12 votes

# Answer
Or, for a quick and easy approach: Use metaballs!
> 6 votes

# Answer
Grant Kot has put some of his fluid simulation code up on Github with implementations in both javascript (canvas) and C++ with OpenFrameworks: https://github.com/kotsoft

He has a few demos up on his youtube account: http://youtu.be/HqWheJSEiaw

I have no idea how it works, but I know it runs fast and there's all sorts of variations to build with it. A good keyword to search for might be "multigrid particles".
> 5 votes

---
Tags: 2d, particles, water
---


# Question
Title: Map displacement transformation to texture space?
I am trying to displace geometry in object space without giving the appearance of texture warping.

My idea is to displace the UV lookup by a relative amount to the geometry displacement.

Any ideas on how I can do this?

# Answer
Not sure but maybe Triplanar mapping can get you going in the right direction.

The link might not be the best but the graphics are good and explicit, here is another one with code.
> 1 votes

---
Tags: mathematics, coordinates, uv-mapping, displacement-mapping
---


# Question
Title: Flash AS3 sidescrolling tiles optimization
I'm trying to make a sidescrolling game in Flash that will run on a low performance laptop.

While studying the subject from Tonypa I saw that he builds a Bitmap by making copys of the `BitmapData` of each tile from the Tile Sheet and placing it on the bigger Bitmat with the size of the screen.

But when I came to think on how to scroll my map I ran into some optimization doubts. I came up with two choices:

1. Create a MovieClip, place a Bitmap instance for each tile that is shown on the screen + 1 row in it, then move them all. Then when the tile ran off the screen I would move it to end of the MovieClip and replace their BitmapData for the next row in my map.
2. Use a Bitmap with copys of each tile in it (as shown in Tonypa's tutorial) but 1 extra row, move the whole Bitmap, and when it comes the time to replace rows, redraw the whole Bitmap and move it back to the origin position.

The first idea is how a co-worker of mine suggested, the second one is my own, but none of us has enough technical knowledge to be sure on a technique that would be optimal in performance, can anyone help?

# Answer
The second idea would be much, much faster. Rendering dozens of DisplayObjects every frame is going to be slower than occasionally re-blitting to a Bitmap.

Depending on the speed/memory tradeoff you want to make, you can make the background Bitmap wider to make your redraws less frequent. Keep in mind that there is a maximum size for Bitmaps, depending on which Flash player you're targeting, but that size is at least 2048 pixels in every direction.
> 5 votes

# Answer
The second is way better / efficient.

The 'old' way (when you really didn't have much processor speed and no GPU) was to use what was called a 'scroller', take your second example and instead of redrawing everything when you have moved one tile (say the game is a Mario clone moving to the right which means you move the bitmap to the left):

Just continue to move the big bitmap and instead of brawing All new tiles, you draw the new tiles to the Left of the bitmap and draw the bitmap a second time to the right of the first draw:

this is the map:

123456789

you see this:

\[1234\]

because the bitmap is like this:

12345

Now we move 1 whole tile to the right, which means the big bitmap moves to the left (well, you can move it pixel by pixel but here you have moved one whole tile):

1\[2345\]

(the brackets is the screen)

What you proposes, so that we can continue moving another tile) is to redraw the whole bitmap like this: 23456

but you just need to redraw one tile here (or one tile-column) so the new bitmap looks like this:

62345

draw it twice, first:

62\[345 \]

second:

\[3456\]2345

and there you are.

You can obviously use this when moving up / down and left too.
> 1 votes

---
Tags: flash, actionscript-3, tiles, side-scroller
---


# Question
Title: What are my tool options to prototype a 2D online multiplayer game?
I'm looking for the best tool to allow me to quickly put together a 2D game that relies largely on networking. It's extremely likely that this game will require a server side program to constantly run. I have little experience with these things and since it's a prototype i'd like the easiest options for achieving this.

I am looking to make this game for the web and mobile devices, although at present I only have access to ios hardware, (no android etc).

I just want to get the bare bones of this set up so I can test it from the earliest opportunity to see if it's fun.

EDIT - doesn't unity have some inbuilt networking stuff in it?

# Answer
If you want to give a shot at HTML5, you could try a combination of the HTML5 boilerplate and node.js. It would allow you to use the same language (Javascript) on server and client-side. This can help in doing quick and dirty prototyping, and it has the additional benefit that your client will run on any decent web browser on any machine. I've used HTML5 with node.js for a 48h Global Game Jam entry, and it went really well.
> 1 votes

# Answer
I am not sure if there are any tools available for doing prototyping an online multiplayer game but you can use some of the inbuilt features in the iOS sdk to test out your game before making it live. Though you have to create your game prototype first in any of the engines available for 2D game programming or you can write your own(which is really not that difficult). The game play might change a little depending on the server speed and network connection of user, but you will get the basic idea if you use game kit framework for testing out your game.

You can find the reference of the game kit framework here

http://developer.apple.com/library/ios/#DOCUMENTATION/NetworkingInternet/Conceptual/GameKit\_Guide/Introduction/Introduction.html

It also provides some sample codes for you to get started.

And here are some 2D game development engines available for developing game in iOS.

http://www.anscamobile.com/corona/

http://www.cocos2d-iphone.org/

http://code.google.com/p/oolongengine/

http://www.garagegames.com/products/torque-2d/iphone

http://gamua.com/sparrow/

http://code.google.com/p/galaxyengine/

http://flixel.org/

And best of luck with your game...
> 1 votes

---
Tags: 2d, ios, multiplayer, online, prototyping
---


# Question
Title: How can I design good continuous (seamless) tiles?
I have trouble designing tiles so that when assembled, they **don't** look like tiles, but look like a homogeneous thing. For example, see the image below:

Even though the main part of the grass is only one tile, you don't "see" the grid; you know where it is if you look a bit carefully, but it is not obvious. Whereas when I design tiles, you can only see "oh, jeez, 64 times the same tile," like in this image:

(I took this from another GDSE question, sorry; not be critical of the game, but it proves my point. And actually has better tile design that what I manage, anyway.)

I think the main problem is that I design them so they are independent, there is no junction between two tiles if put closed to each other. I think having the tiles more "continuous" would have a smoother effect, but can't manage to do it, it seems overly complex to me.

I think it is probably simpler than I think once you know how to do it, but couldn't find a tutorial on that specific point. Is there a known method to design continuous / homogeneous tiles? (My terminology might be totally wrong, don't hesitate to correct me.)

# Answer
> 20 votes
*Disclaimer: I'm not an artist so this is just programmer's art knowledge.*

You're having the grid effect in your example mostly because of that lighter patch of grass on the bottom edge of the tile:

Details like that that are easily recognizable instantly give it away that you're just repeating the same tile.

Check **this article** which has a lot of useful tips on the subject. In particular, using Photoshop:

* Use the Patch Tool to get rid of glaring details.
* Use the Doge or Burn tool to get uniform luminosity everywhere.
* Make the edges seamless by offseting the image and then using the Patch Tool to blend the edges together. I've also seen people duplicate and mirror the image four times before for this purpose.

Also in the image you linked there seems to be an implementation problem too because when zooming in on the image you can see some gaps between tiles:

# Answer
> 15 votes
I'm no expert, but appart from having more than one type of grass tile (not completely different so people realize, but different enough), one trick could be having "transition tiles" between 2 different types of tiles. Using the example image you showed, having a half-green, half-grey tile between the completely grey and the completely green tile can help smooth out the transition. Also, if you make those transitions rounded and more natural looking (one texture fading into the next one), it can help with the effect.

Notice in the image from Chrono Trigger, on the bottom center, how it has a half brown (dirt), half green (grass), with patches of darker grass. It also uses lighter grass and stones to add natural variation (a transparent tile with the stone or light grass on top of the grass tile, maybe?)

# Answer
> 12 votes
You have got to make transitions, for every possible composition of multiple types of tiles you will have to draw tiles that complete the shift. You might want to decide that a lot of the combinations ain't possible in your game as the number of transitions you would otherwise have to make would easily grow to a very large number.

Usually this means blending the qualities of the surface types in some manner, a simple grass to dirt transition for instance would typically have small patches of grass growing rarer the further you get into the dirt tile. But for a quick fix you may simply fade out one texture while fading in another, or make a dithering where you randomly pick pixels from one of two textures using weighted chance that shift from favouring one texture to the other.

Also, I'd recommend that you shift from looking at tiles to sub-tile patterns, consider this image of two tiles, if you rather than making full tiles make shapes corresponding to the red figure you will never need more than two different surfaces in the same tile, thus greatly limiting the number of transition tiles that you have to make, you may then proceed to generate square tiles from these diamond tiles for use in the game, or you may simple use the diamond tiles directly, computers ain't very picky about these things any more.

# Answer
> 6 votes
**Apply a high-pass filter to your tiles.**

See this excellent article by Skaven for detailed theory, examples, and instructions.

# Answer
> 6 votes
Start by making a regular tile. Then divide the tile horizontally and vertically, into 4 equal pieces, leaving you with 4 "tiles".

The tile will now look like this:

```
1 2
3 4

```

Put piece 2 on the left side of piece 1. Do the same with 3 and 4. The tile will now look like this:

```
2 1
4 3

```

Now move both of the lower pieces up above the top pieces. You're left with this:

```
4 3
2 1

```

Assuming your tile is 32x32, each piece will be 16x16. Now you delete the middle, let's say 22x22 pixels(it's up to you), leaving a frame of your tile. This frame will now tile perfectly with itself and you're left to fill in the gap in the middle with uniqueness like gravel, a stone, some higher grass or whatever.

You probably have to jiggle the pixels a little but when you have your frame, you will be able to churn out plenty of unique but perfectly tiling tiles.

# Answer
> 1 votes
The way i design my tiles is like this:

1. Make your draft tile
2. copy your tile into an image that is 3X larger in the X an Y directions
3. copy your tile so that there should be 9 copies of your tile in the image
4. you should be able to see where each tile starts and ends, what you need to do is take a blur tool(I use GIMP for this) and blur the edges so it looks like its one big tile.
5. Then copy the middle tile out of the image and then you have your final tile

The result should look pretty good when you put multiple tiles next to each other. You can always repeat this process to fine tune your tiles.

---
Tags: tiles, graphics-design
---


title: 2D Camera Acceleration/Lag

text:
# Question
Title: 2D Camera Acceleration/Lag
I have a nice camera set up for my 2D xna game. Im wondering how I should make the camera have 'acceleration' or 'lag' so it smoothly follows the player, instead of 'exactly' like mine does now. Im thinking somehow I need to Lerp the values when I set CameraPosition. Heres my code

```
private void ScrollCamera(Viewport viewport)
    {

        float ViewMargin = .35f;

        float marginWidth = viewport.Width * ViewMargin;
        float marginLeft = cameraPosition.X + marginWidth;
        float marginRight = cameraPosition.X + viewport.Width - marginWidth;

        float TopMargin = .3f;
        float BottomMargin = .1f;
        float marginTop = cameraPosition.Y + viewport.Height * TopMargin;
        float marginBottom = cameraPosition.Y + viewport.Height - viewport.Height * BottomMargin;

        Vector2 CameraMovement;
        Vector2 maxCameraPosition;

        CameraMovement.X = 0.0f;
        if (Player.Position.X < marginLeft)
            CameraMovement.X = Player.Position.X - marginLeft;
        else if (Player.Position.X > marginRight)
            CameraMovement.X = Player.Position.X - marginRight;

        maxCameraPosition.X = 16 * Width - viewport.Width;
        cameraPosition.X = MathHelper.Clamp(cameraPosition.X + CameraMovement.X, 0.0f, maxCameraPosition.X);

        CameraMovement.Y = 0.0f;
        if (Player.Position.Y < marginTop) //above the top margin
            CameraMovement.Y = Player.Position.Y - marginTop;
        else if (Player.Position.Y > marginBottom) //below the bottom margin
            CameraMovement.Y = Player.Position.Y - marginBottom;

        maxCameraPosition.Y = 16 * Height - viewport.Height;
        cameraPosition.Y = MathHelper.Clamp(cameraPosition.Y + CameraMovement.Y, 0.0f, maxCameraPosition.Y);

    }

```

# Answer
Yes you can do it with a simple lerp. You have your current camera position called `cameraPosition`, let's say you add a target position you're trying to reach called `targetPosition`. You set your `targetPosition` to follow 'exactly' your player, and you smooth your `cameraPosition` this way:

```
cameraPosition.X = MathHelper.Lerp(cameraPosition.X, targetPosition.X, 0.1f);
cameraPosition.Y = MathHelper.Lerp(cameraPosition.Y, targetPosition.Y, 0.1f);

```

That's quick and easy, just tweak the last factor to adjust the effect. To get an even more natural-looking movement, you can do this twice: make your camera position follow a target that follows the 'fixed' target.

Note that this works well with fixed delta times, if your framerate varies a lot you'll be in trouble.
> 5 votes

---
Tags: xna, c#, 2d, tiles, camera
---


title: How to load 3D models into Java?

text:
# Question
Title: How to load 3D models into Java?
Using LWJGL what is the easiest way to load a 3D model to be drawn on screen?

I know LWJGL doesn't have built in loading support so I am looking for a small library that would help to load specifically .blend files.

# Answer
> 9 votes
The best way in my opinion is to write your own parser for .obj exported with Blender or your preferred 3D modeling software. It will really only take you a maximum of one hour and you won't have to worry about distribution/licence issues. Here is a video about this question: http://youtu.be/izKAvSV3qk0.

# Answer
> 4 votes
The easiest way is to build you own loader that can for example load .OBJ files or maybe your own format thats custom made for your game. Blender files however I'm not sure.

# Answer
> 3 votes
You may find JAGaToo to be useful. It has loaders for MD2/3/5, OBJ, and some other model formats.

# Answer
> 0 votes
Have a look at jMonkeyEngine \- it has model loading capabilities for many different model files and is based on LWJGL so you may be able to adapt it to your needs.

---
Tags: 3d, java, 3d-meshes, blender, lwjgl
---


# Question
Title: Recent mainstream games written in pure C? not C++ what was/is the point?
Recent meaning the current decade. I had found this post https://gamedev.stackexchange.com/a/15403/6544 wasnt c++ adopted as the industry standard quite some time back. In what sort of situation does it make sense to go with games written in pure c on established consoles/pc/os

# Answer
C is almost as good as assembly language in putting you in touch with the computer. C++ add all kinds of tricky complications that many programmers love, but it moves you away from the CPU. If you want total control at the expense of OO features and neat gimmicks and assembly language is just a little bit too gritty, C is just the thing. I'm not recommending it, but it was a neat languange when it first arrived, being both a higher level language than FORTRAN *and* a lower level at the same time. All the advantages and none of the disadvantages.

It fills a certain niche better than anything else. Not too many people use that niche any more, but if they do, C's the language for them.
> -1 votes

---
Tags: software-engineering, c, game-industry
---


title: How do I draw thick lines in XNA 4.0?

text:
# Question
Title: How do I draw thick lines in XNA 4.0?
I can draw some curves using this:

```
GraphicsDevice.DrawUserPrimitives<VertexPositionColor>
           (PrimitiveType.LineStrip, Points, 0, count);

```

Now I try to set the `PointSize` to make the line thicker but I can only find a solution for XNA 3.0 using:

```
GraphicsDevice.RenderState.PointSize

```

How can I make my lines thicker in XNA 4.0?

# Answer
> 2 votes
XNA 4 does not support point sprites, which is (I believe) all that PointSize is for; for some rationale, see Shawn Hargreaves' blog post on the subject. The short version is that D3D10+ does not support them, and continuing to expose them in XNA restricts options for eventually moving XNA's underpinnings to a newer D3D version.

While it's not a decision that was met with universal praise, it's not the end of the world because you can simulate the effects yourself. It just requires more work. Fortunately, there are third-party solutions to do so that already exist -- something like the RoundLine library might serve your needs, or you can see this blog post about a similar technique (probably actually the same one RoundLine uses).

---
Tags: xna-4.0
---


# Question
Title: In OpenGl ES 2, should I allocate multiple transformation matrices?
In OpenGl ES 2, should I declare just one transformation matrix, and share it across all objects or should I declare a transformation matrix in each object that needs it?

for clarification... something like this:

```
public class someclass{
   public static float[16] transMatrix = new float[16];
   ...
   public static void translate(int x, int y){
      //do translation here
   }
}
public class someotherclass{
   ...
   void draw(GL10 unused){
      someclass.translate(10,10);
      //draw
   }
}

```

verses something like this:

```
public class obj1{
    public static float[16] transMatrix = new float[16];
   ...
   void draw(GL10 unused){
      //translate
      //draw
   }
}
public class obj2{
   public static float[16] transMatrix = new float[16];
   ...
   void draw(GL10 unused){
      //translate
      //draw
   }
}

```

# Answer
> 0 votes
I'm also interested in the general opinion of which one is better. Here's my take on it:

In my OpenGL ES2 engine I have global transformation matrices (one modelview and one projection, obviously). I guess I've done it that way because it resembles how the old pipeline worked. It also makes sense because the way you traverse the scene you can build a stack of matrices (again, similar to the traditional approach) and it's really easy to understand - you can just think of the matrix transformations as camera movement.

On the other hand having a modelview matrix per object may be a pretty good idea. Off the top of my head you get the benefit that you don't need to do matrix calculations in the rendering phase (since it can be set in the physics simulation phase). This means you only have to recalculate these matrices if the object actually moves. It probably has some memory penalty but that's unlikely to matter on today's hardware. It may also allow you to have one transformation matrix for both the graphical and physical representation of the object (this depends on the frameworks you use).

# Answer
> 0 votes
I have a global MVP matrix that my Camera class constructs each update. This gets passed to my rendering classes and then to my shaders. It seem like a lot of unnecessary overhead to have one or more matrices for each object when you can just use global matrices.

---
Tags: android, opengl-es2
---


# Question
Title: Cutting out smaller rectangles from a larger rectangle
The world is initially a rectangle. The player can move on the world border and then "cut" the world via orthogonal paths (not oblique). When the player reaches the border again I have a list of path segments they just made.

I'm trying to calculate and compare the two areas created by the path cut and select the smaller one to remove it from world.

After the first iteration, the world is no longer a rectangle and player must move on border of this new shape.

How can I do this? Is it possible to have a non rectangular path? How can I move the player character only on path?

*EDIT*

Here you see an example of what I'm trying to achieve:

1. Initial screen layout.
2. Character moves inside the world and than reaches the border again.
3. Segment of the border present in the smaller area is deleted and last path becomes part of the world border.
4. Character moves again inside the world.
5. Segments of border present in the smaller area are deleted etc.

# Answer
It's difficult to understand the context of your problem without an image. It sounds like the player is given the ability to divide a polygon along an arbitrary axis thereby producing two, possibly irregular, polygonal shapes. The process of actually splitting a specified Rectangle into these two shapes is rather simple.

If the axis must bisect the entire shape, it produces two sets of Vector2s that represent the vertices of two polygons. To determine the area of these two irregular polygons would require a simple triangulation of the polygons. There are existing implementations of well known triangulation algorithms like Delaunay triangulation, but for simple shapes you may be able to roll your own with little issue. If this is not the situation you're facing, please elaborate on the context of your question and I'll give it another shot.
> 2 votes

# Answer
So, I first assume you are trying to make a game with gameplay elements highly similar to that of Cacoma Knight in Bizyland You have the general idea down, but you are imagining too much that adding a new rectangle requires the game to "remove" the overlapping borders of the old rectangle. This is not the case at all. Simply maintain a list of rectangles, with the first item in the list being a rectangle occupying the entire gameplay screen. Whenever the player sucessfully traces a new rectangle, it is added to the list.

In your game loop's update function, check the rectangles in the list as the player moves, and do not permit them to cross a horizontal line of a rectangle while moving vertically or the vertical line of a rectangle while moving horizontally. In addition, the entire time, do not permit them to move to any coordinate that is not on the border of a rectangle, unless they are currently "cutting" from the world.

Special things to consider include logic to use the edges of already existing rectangles to create the new ones. The parameters of the already existing items in your list are sufficient to perform the necessary logic for this. Also, this is a more simple form of gameplay than the video I linked, in which you can create more complex shapes. If you want to do more complex shapes, you would use a list of lines instead of rectangles, which would either run purely vertical or purely horizontal. The same concept applies, in which the player can't cross horizontal lines vertically or vertical lines horizontally, but you need to add some complex logic for keeping track of the lines the player is cutting out, as well as to help define when a shape is complete.

I wish you the best of luck, and hopefully I have been of help.
> 0 votes

---
Tags: xna-4.0
---


title: XNA extending an existing Content type

text:
# Question
Title: XNA extending an existing Content type
We are doing a game in XNA that reacts to music. We need to do some offline processing of the music data and therefore we need a custom type containing the `Song` and some additional data:

```
// Project AudioGameLibrary
namespace AudioGameLibrary
{
    public class GameTrack
    {
        public Song Song;
        public string Extra;
    }
}

```

We've added a Content Pipeline extension:

```
// Project GameTrackProcessor
namespace GameTrackProcessor
{
    [ContentSerializerRuntimeType("AudioGameLibrary.GameTrack, AudioGameLibrary")]
    public class GameTrackContent
    {
        public SongContent SongContent;

        public string Extra;
    }

    [ContentProcessor(DisplayName = "GameTrack Processor")]
    public class GameTrackProcessor : ContentProcessor<AudioContent, GameTrackContent>
    {
        public GameTrackProcessor(){}

        public override GameTrackContent Process(AudioContent input, ContentProcessorContext context)
        {

            return new GameTrackContent()
            {
                SongContent = new SongProcessor().Process(input, context),
                Extra = "Some extra data" // Here we can do our processing on 'input'
            };
        }
    }
}

```

Both the Library and the Pipeline extension are added to the Game Solution and references are also added. When trying to use this extension to load "gametrack.mp3" we run into problems however:

```
// Project AudioGame
protected override void LoadContent()
{
    AudioGameLibrary.GameTrack gameTrack = Content.Load<AudioGameLibrary.GameTrack>("gametrack");

    MediaPlayer.Play(gameTrack.Song);
}

```

The error message:

> `Error loading "gametrack". File contains Microsoft.Xna.Framework.Media.Song but trying to load as AudioGameLibrary.GameTrack.`

`AudioGame` contains references to both `AudioGameLibrary` and `GameTrackProcessor`. Are we maybe missing other references?

EDIT

Selecting the correct content processor helped, it loads the audio file correctly. However, when I try to process some data, e.g:

```
public override GameTrackContent Process(AudioContent input, ContentProcessorContext context)
{
    int count = input.Data.Count; // With this commented out it works fine

    return new GameTrackContent()
    {
        SongContent = new SongProcessor().Process(input, context)
    };
}

```

It crashes with the following error:

```
Managed Debugging Assistant 'PInvokeStackImbalance' has detected a problem in 'C:\Users\Maarten\Documents\Visual Studio 2010\Projects\AudioGame\DebugPipeline\bin\Debug\DebugPipeline.exe'.
Additional Information: A call to PInvoke function 'Microsoft.Xna.Framework.Content.Pipeline!Microsoft.Xna.Framework.Content.Pipeline.UnsafeNativeMethods+AudioHelper::OpenAudioFile' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.

```

Information from logger right before crash:

```
  Using "BuildContent" task from assembly "Microsoft.Xna.Framework.Content.Pipel
ine, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553".
  Task "BuildContent"
    Building gametrack.mp3 -> bin\x86\Debug\Content\gametrack.xnb
    Rebuilding because asset is new
    Importing gametrack.mp3 with Microsoft.Xna.Framework.Content.Pipeline.Mp3Imp
orter

```

Im experiencing exactly this: http://forums.create.msdn.com/forums/t/75996.aspx

EDIT2

The second problem was fixed by using SoundEffect instead of Song inside the GameTrack struct and using an uncompressed audio format (WAV). It turns out that accessing AudioContent.Data is not supported for compressed formats.

# Answer
You have to change the "Content Processor" property of your gametrack.mp3 file to match the name of your custom Content Processor. This is done in the "Properties" window of Visual Studio.
> 2 votes

---
Tags: xna, xna-4.0, xna-content-pipeline
---


title: How to render realistic ice?

text:
# Question
Title: How to render realistic ice?
I am trying to write an ice shader in Unity that looks good and at least semi-realistic.

If the following shot (found on Google) was CG, what would its shader include? (the foreground cave). I might be wrong but it looks like it even has a different lighting model than the default diffuse.

# Answer
> 53 votes
Ice is translucent so I believe the single most important thing you have to simulate in your shader to get realistic results would be **subsurface scattering** or SSS for short. SSS basically describes how rays of light penetrate the surface of translucent objects and scatter underneath it, being reflected multiple times in an irregular fashion, before finally exiting through a different location.

Here's a picture that I think demonstrates the effect nicely:

From the picture in your question we can also see that ice is quite reflective, so you'll probably also want to combine it with some sort of **environment mapping** for reflections, and also tone up the **specularity** in order to reinforce the highlights.

You can also try other things such as adding a bit of **refraction**, overlaying some sort of **noise** texture to add a bit of variation, or even some sort of **bump mapping** or **displacement mapping** for very small and subtle details.

**Resources**

Some other resources that I found while writing the answer:

# Answer
> 14 votes
One of my students did this a few years ago (using renderman ) but lots of background in the thesis http://nccastaff.bournemouth.ac.uk/jmacey/MastersProjects/MSc09/Salas/index.html

---
Tags: graphics, unity, shaders, rendering, glsl
---


# Question
Title: Circle to Circle collision, checking each circle against all others
I'm currently coding a little circle to circle collision demo but I've got a little stuck. I think I currently have the code to detect collision but I'm not sure how to loop through my list of circles and check them off against one another.

Collision check code:

```
public static Vector2 GetIntersectionDepth(Circle a, Circle b)
    {
        float xValue = a.Center.X - b.Center.X;
        float yValue = a.Center.Y - b.Center.Y;

        Vector2 depth = Vector2.Zero;

        float distance = Vector2.Distance(a.Center, b.Center);

        if (a.Radius + b.Radius > distance)
        {
            float result = (a.Radius + b.Radius) - distance;
            depth.X = (float)Math.Cos(result);
            depth.Y = (float)Math.Sin(result);
        }

        return depth;
    }

```

Loop through code:

```
        Vector2 depth = Vector2.Zero;

        for (int i = 0; i < bounds.Count; i++)
            for (int j = i+1; j < bounds.Count; j++)
            {
                depth = CircleToCircleIntersection.GetIntersectionDepth(bounds[i], bounds[j]);
            }

```

Clearly I'm a complete newbie, wondering if anyone can give any suggestions or point out my errors, thanks in advance. :)

# Answer
> 2 votes
The functions look correct assuming bounds is a Circle. The loop through code is also seems correct, as you are avoiding checking the same 2 circles again which is good.

For the collision detection bit, from the source your provided, the function `GetIntersectionDepth(Circle a, Circle b)` will return a zero vector IF the two circles are not colliding, so all you have to do is change your code to this:

```
Vector2 depth = Vector2.Zero;

    for (int i = 0; i < bounds.Count; i++)
        for (int j = i+1; j < bounds.Count; j++)
        {
            depth = CircleToCircleIntersection.GetIntersectionDepth(bounds[i], bounds[j]);
            if(depth == Vector2.Zero){
                //this means that did not collide
            }else{
                //this means they collided
            }
        }

```

---
Tags: xna, c#, collision-detection
---