# Question
Title: Platform jumping problems with AABB collisions
See the diagram first:

When my AABB physics engine resolves an intersection, it does so by finding the axis where the penetration is smaller, then "push out" the entity on that axis.

Considering the "jumping moving left" example:

* If velocityX is bigger than velocityY, AABB pushes the entity out on the Y axis, effectively stopping the jump (result: the player stops in mid-air).
* If velocityX is smaller than velocitY (not shown in diagram), the program works as intended, because AABB pushes the entity out on the X axis.

How can I solve this problem?

## Source code:

```
public void Update()
{
    Position += Velocity;
    Velocity += World.Gravity;

    List<SSSPBody> toCheck = World.SpatialHash.GetNearbyItems(this);

    for (int i = 0; i < toCheck.Count; i++)
    {
        SSSPBody body = toCheck[i];
        body.Test.Color = Color.White;

        if (body != this && body.Static)
        {
            float left = (body.CornerMin.X - CornerMax.X);
            float right = (body.CornerMax.X - CornerMin.X);
            float top = (body.CornerMin.Y - CornerMax.Y);
            float bottom = (body.CornerMax.Y - CornerMin.Y);

            if (SSSPUtils.AABBIsOverlapping(this, body))
            {
                body.Test.Color = Color.Yellow;

                Vector2 overlapVector = SSSPUtils.AABBGetOverlapVector(left, right, top, bottom);

                Position += overlapVector;
            }

            if (SSSPUtils.AABBIsCollidingTop(this, body))
            {
                if ((Position.X >= body.CornerMin.X && Position.X <= body.CornerMax.X) &&
                    (Position.Y + Height/2f == body.Position.Y - body.Height/2f))
                {
                    body.Test.Color = Color.Red;
                    Velocity = new Vector2(Velocity.X, 0);

                }
            }
        }
    }
}

```

---

```
public static bool AABBIsOverlapping(SSSPBody mBody1, SSSPBody mBody2)
{
    if(mBody1.CornerMax.X <= mBody2.CornerMin.X || mBody1.CornerMin.X >= mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y <= mBody2.CornerMin.Y || mBody1.CornerMin.Y >= mBody2.CornerMax.Y)
        return false;

    return true;
}
public static bool AABBIsColliding(SSSPBody mBody1, SSSPBody mBody2)
{
    if (mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y)
        return false;

    return true;
}
public static bool AABBIsCollidingTop(SSSPBody mBody1, SSSPBody mBody2)
{
    if (mBody1.CornerMax.X < mBody2.CornerMin.X || mBody1.CornerMin.X > mBody2.CornerMax.X)
        return false;
    if (mBody1.CornerMax.Y < mBody2.CornerMin.Y || mBody1.CornerMin.Y > mBody2.CornerMax.Y)
        return false;

    if(mBody1.CornerMax.Y == mBody2.CornerMin.Y)
        return true;

    return false;
}
public static Vector2 AABBGetOverlapVector(float mLeft, float mRight, float mTop, float mBottom)
{
    Vector2 result = new Vector2(0, 0);

    if ((mLeft > 0 || mRight < 0) || (mTop > 0 || mBottom < 0))
        return result;

    if (Math.Abs(mLeft) < mRight)
        result.X = mLeft;
    else
        result.X = mRight;

    if (Math.Abs(mTop) < mBottom)
        result.Y = mTop;
    else
        result.Y = mBottom;

    if (Math.Abs(result.X) < Math.Abs(result.Y))
        result.Y = 0;
    else
        result.X = 0;

    return result;
}

```

# Answer
I just looked at the code I have not tried to prove where it is wrong.

I looked at the code and these 2 lines seemed strange:

```
if ((Position.X >= body.CornerMin.X && Position.X <= body.CornerMax.X) &&
(Position.Y + Height/2f == body.Position.Y - body.Height/2f))

```

You check for interval and then You check for euquality? I may be wrong, (there might be som rounding going on) but it seems it might cause a trouble.
> 2 votes

# Answer
It's hard to read code of other people, but I think this is one possible (purely brainstormed) workaround, although of course I'm not able to test it:

1. Before the collision detection happens, save the players velocity to some temporary variable.
2. After you've done your collision response, check if the players X or Y position has been corrected
3. If X position has been changed, manually reset (as a kind of "safety reset") the players Y velocity to the one that he had before the response.

By the way, what happens with your current code when your players hits the roof while jumping?
> 0 votes

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


title: XNA Quadtree with LOD

text:
# Question
Title: XNA Quadtree with LOD
I'm looking to create a fairly large environment, and as such would like to implement a quadtree and use LOD on it. I've looked through numerous examples and I get the basic idea of a quadtree. Start with a root node with 4 vertices covering the whole map and divide into 4 children nodes until I meet some criteria (max number of triangles)

I'm looking for some very very basic algorithm or explanation with respect to drawing the quadtree. What vertices need to be stored per iteration? When do I determine what vertices to draw? When to update indices and vertices? Hope to integrate the bounding frustum? Do I include parent and child vertices?

I'm looking for very simple instruction on what to do. I've scoured the internet for days now looking, but everyone adds extra code and a different spin without explanation.

I understand quadtrees, but not with respect to 3d rendering and lod. A link to an outside source will probably have been read by myself already and won't help.

Regards, Byron.

# Answer
> 2 votes
The "modern" way to render terrain is to use chunked LOD.

With the last few generations of hardware, say the last 5-10 years, fiddling with the geometry primitives on a per frame level (as is needed e.g. for ROAM) is counterproductive as it incurs a horrible performance hit. You are much better off building a whole array of immutable chunks and selecting the proper ones based on distance etc.

---
Tags: xna, c#, terrain-rendering
---


# Question
Title: Where to hire a scenario writer for a small interactive story game?
I need a scenario for a small dialog-based game / interactive story. The game would be used as an example to be shipped with a middleware tool we're developing.

I would like to buy an existing story (it should be dynamic of course — with branching dialogs etc.), or hire someone to write a new one.

Please advise, where to go to find such person / service? We're based in Russia, so getting a talented enough native English writer locally is a bit of a problem.

Update: To be extra clear: We must get all necessary rights to reuse the story and make a derived work (i.e. the game we're talking about) from it. This is a commercial product. Borrowing someone else's work at random and using it just not going to work.

***WARNING:*** **Please do not post "I can do it" answers here. *This is not a job board!* You will get downvoted and your answer will be deleted.** If you really want to contact me, look into my profile.

# Answer
> 4 votes
Mea culpa. Should have done more research before posting.

Alexander, you can check out the IGDA's Game Writing Special Interest Group -- there, you'll find information about freelance writers in the industry. You can also sign up for the mailing list, which will allow you to get in touch with game writers directly.

http://www.igda.org/writing

GameGuzzler is a good site for posting ads for contract writers. I believe someone else may have mentioned Gamasutra already, but I'll emphatically add a recommendation for that one as well.

http://www.gameguzzler.com

# Answer
> 3 votes
I've found this web of a game writer that has an article: how to find the best game writer for your game

**Edited:**

In this web there are scripts from movies or unproduced scripts uploaded by his authors. The web FAQs says that the scripts are links to other sites. You can see the unproduced scripts and contact the author if the script has copyright. Make sure that the script hasn't been post illegaly in the web. I'm not sure if the web ensures the legality of his content.

# Answer
> 1 votes
If all you're after is demo content, consider borrowing a plot from an existing source such as a "Choose Your Own Adventure" book, or a game that you like. If you're not selling the content, I doubt I will cause copyright problems (but i am not a lawyer).

**To clarify**: I'm *not* advocating stealing someone else's work. As someone who makes intangible things for a living, I don't advocating stealing intellectual property.

If I'm demoing, say, an audio channel separation tool to a client, I'm not going to pay a musician to compose and record custom music for the demo. Using one of my existing MP3s or CDs is just fine - I'm not reselling (or distributing) their content, and am in no way harming the copyright owner ( financially or otherwise).

Now, if I were putting the same demo on a website or distributing it in some other way, the circumstances are very different.

---
Tags: game-design
---


# Question
Title: Other games that employ mechanics like the game "Diplomacy"
I'm doing a little bit of research and I'm hoping you can help me track down any games, other than Diplomacy (online version here), that employ all or some of the mechanics in Diplomacy (rules, short form). Examples I'm looking for:

* Simultaneous orders given prior to execution of orders
    + In Diplomacy, players "write down" their moves and execute them "at the same time"
* Support, in terms of supporting an attacker or defender "take" a territory.
    + In Diplomacy, no one unit is stronger than another you need to combine the strength of multiple units to attack other territories.
* Rules for how move conflicts are resolved
    + Example, 2 units move into a space, but only one is allowed, what happens.

I may add to this list later, but these are the primary things I'm looking for. If you need clarification on anything just let me know.

> **Note**: I tried asking this on GamingSE, but it was shot down. So, I am unsure where else I could post this. Since I am researching this for game development purposes, I assume this post is on topic. Please let me know if this is not the case. Please also feel free to re-categorize this. Thanks!

# Answer
> 7 votes
Judging from the gameplay you've suggested Frozen Synapse might be one to watch.

# Answer
> 6 votes
First, Diplomacy is a board game. The question might have more chance getting great answers on http://boardgames.stackexchange.com

# Answer
> 4 votes
There's a neat little two-player board game called "2 De Mayo" which has some of these features.

* Simultaneous orders (both French and Spanish side write down orders and reveal at the same time)
* Simple rules for resolving conflicts.

It does not, however, have supporting actions. You can only move (attack an area) and not stay and support.

Apart from that, it's an asymmetrical game in that the French army (which is much stronger has only few troops) and needs to hunt down a highly mobile Spanish rebel mob comprised of many small units. Check it out.

# Answer
> 3 votes
Medieval Total War has all three of those. Unless multiplayer in this strategic portion is required.

# Answer
> 3 votes
Total war games all really good for this and you could also try the Civilization games I think Civ 5 was released recently.

# Answer
> 2 votes
This isn't a perfect match, but Dominions 3 is the first thing I thought of. It's got the simultaneous movement and heavy use of diplomacy in order to win games. There's no official way to "support" units, besides having them form larger armies, and there's no way two players can assist each other in combat. But from what little I played of Diplomacy, Dominions 3 has the same basic feel, only with, you know, hordes of monsters and worldshattering spells added.

In a more general sense you might want to look into the Play-By-Mail genre, now frequently referred to as Play-By-Email or PBEM. There are many, many examples of this genre, but besides Dominions 3 it may also be worth looking at the venerable VGA Planets and Stars! games.

# Answer
> 2 votes
Game review blog *Rock Paper Shotgun* reviewed a team-work board game somewhat unimaginatively named *Space Alert*. The review however is a great read and the game seems ridiculously fun.

The game takes the *Diplomacy* concept to the extreme in that the whole game is played to the end before everyone finds out if they won or lost.

---
Tags: game-design, game-mechanics
---


# Question
Title: Coordinate based travel through multi-line path over elapsed time
I have implemented A\* Path finding to decide the course of a sprite through multiple waypoints. I have done this for point A to point B locations but am having trouble with multiple waypoints, because on slower devices when the FPS slows and the sprite travels PAST a waypoint I am lost as to the math to switch directions at the proper place.

EDIT: To clarify my path finding code is separate in a game thread, this onUpdate method lives in a sprite like class which happens in the UI thread for sprite updating. To be even more clear the path is only updated when objects block the map, at any given point the current path could change but that should not affect the design of the algorithm if I am not mistaken. I do believe all components involved are well designed and accurate, aside from this piece :- )

Here is the scenario:

```
public void onUpdate(float pSecondsElapsed)
{
    // this could be 4x speed, so on slow devices the travel moved between
    // frames could be very large. What happens with my original algorithm
    // is it will start actually doing circles around the next waypoint..
    pSecondsElapsed *= SomeSpeedModificationValue;

    final int spriteCurrentX = this.getX();
    final int spriteCurrentY = this.getY();

    // getCoords contains a large array of the coordinates to each waypoint.
    // A waypoint is a destination on the map, defined by tile column/row. The
    // path finder converts these waypoints to X,Y coords.
    //
    // I.E:
    // Given a set of waypoints of 0,0 to 12,23 to 23, 0 on a 23x23 tile map, each tile
    // being 32x32 pixels. This would translate in the path finder to this:
    //    -> 0,0 to 12,23
    //        Coord : x=16 y=16
    //        Coord : x=16 y=48
    //        Coord : x=16 y=80
    //          ...
    //        Coord : x=336 y=688
    //        Coord : x=336 y=720
    //        Coord : x=368 y=720
    //
    //    -> 12,23 to 23,0 -NOTE This direction change gives me trouble specifically
    //        Coord : x=400 y=752
    //        Coord : x=400 y=720
    //        Coord : x=400 y=688
    //          ...
    //        Coord : x=688 y=16
    //        Coord : x=688 y=0
    //        Coord : x=720 y=0
    //
    // The current update index, the index specifies the coordinate that you see above
    // I.E. final int[] coords = getCoords( 2 ); -> x=16 y=80
    final int[] coords = getCoords( ... );

    // now I have the coords, how do I detect where to set the position? The tricky part
    // for me is when a direction changes, how do I calculate based on the elapsed time
    // how far to go up the new direction... I just can't wrap my head around this.

    this.setPosition(newX, newY);
}

```

# Answer
> 1 votes
When using a variable time-step, the game becomes non deterministic, as you can see it can break the flow of gameplay on a slower device.

The easiest way to fix this error would be to implement a fixed timestep with interpolation. If implemented correctly the logic of the game will always update at the same rate, and becomes deterministic, meaning a simulation will always play out the same(if there are no random numbers, or if there are random numbers the random numbers are seeded the same way).

Here is an answer with resources on how to implement a fixed timestep.
Semi-fixed or Fully-fixed timestep?

Here is an answer that explains how to implement interpolation for movement and transformations.
How to Interpolate between two game states?

---
Tags: mathematics, algorithm, sprites, path-finding, coordinates
---


title: Experience embedding javascript

text:
# Question
Title: Experience embedding javascript
I'm looking into scripting languages to embed in my game.

I've always assumed Lua was the best choice, but I've read some recent news about embedding V8 as was considering using it instead.

My question is two fold:

Does anyone with experience embedding v8 (or another javascript engine) recommend it?

How does it compare with embedding Lua?

I like that v8 has a c++ embedding API. However Lua API has had lots of time to be refined (newer isn't always better and all that).

Note: At this point I'm not too concerned with which is better language or which library has better performance. I'm only asking about ease of embedding.

# Answer
I use JINT with my C# MUD. I have looked into V8, but found JINT to be much easier in my case. I'm not so sure what the best option for C++ would be. I simply enjoy Javascript as a language because I know it better than Lua. I'm sure Lua is much more refined and has been widely used for a long time now. My guess is if your looking for the easiest thing to embed, Lua would be the way to go just because I would think it be much better than documented than anything else. However if you are going to have a lot of scripters later on, javascript programmers are probably much more widespread at this point than Lua programmers.

In my case JINT was just as easy if not easier to embed than Lua. However the actual time embedding the script should be trivial compared to the time it will take to write said scripts. I would go with whatever you think your programmers or you are most comfortable programming with later on. Unfortunately I don't really know what the performance kicks are from either. I do know for sure that V8 is by far the fastest Javascript engine.
> 1 votes

# Answer
you should maybe look into nodeJS

Its a V8 wrapped with some excellent base modules. Its fast, has a huge community and tens of a universe of modules available via the NPM package manager.
> -3 votes

---
Tags: javascript, scripting, lua
---


# Question
Title: Java how to color text without using JNI?
I am working on a small text-based game in Java. I am trying to understand the concept of how to color the output without needing to use JNI. C++ has the ability to modify the console directly and also make system calls but as far as I can tell JAVA doesn't because of its ability to be system independent.

Is this possible or should I look at using a JFrame and the paint object?

# Answer
https://stackoverflow.com/questions/1448858/how-to-color-system-out-println-output is a answer to your question.
> 2 votes

---
Tags: java, text-based, color
---


title: Sanity checks vs file sizes

text:
# Question
Title: Sanity checks vs file sizes
In your game assets do you make room for explicit sanity checks, or do you have some generally expected bounds which you assert?

I've been thinking about how we compress data and thought that it's much better to have the former, and less of the latter. If your data can exceed your normal valid ranges, but if it does it's an error, then surely that implies you're not compressing the data well enough?

What do you do to find out if your data is compressed as far as it can be, and what do you use to ensure your data isn't corrupted and ensure it's an official release?

*EDIT*

I'm not interested in sanity checking the file size, but instead, how you manage your sanity checks and whether you arrange the excess size caused by the opportunity to do sanity checks by using explicit extra data, or through allowing the data enough file space (data member size) to be out of valid range and thus able to be checked merely by looking at the asset in memory after loading.

*EDIT*

QUOTE: "runtime performance is valued very highly while maximal compression is merely a nice thing to have"

yes, but we're still having issues with our media being slower than decompression algorithms, especially with situations where programmers and data desginers have not considered the footprint of their data layouts and are unnecessarily creating assets that have redundant storage capacity.

I must assume that there are very few people who consider the importance of bandwidth outside of those working on platforms that are strictly bound by their data throughput rate or storage capacity.

# Answer
I've done two things for release builds in the past, I've never added extra data.

First is all the data is described by a manifest that has a CRC or MD5 and at program startup the local files are checked against their expected hash. A patching system will do this for you, if you use one, so it's almost automatic.

Second is not to use asserts (which disappear in release modes) but simple range checks, for example does a bitmap have \>2048 width, which will catch malformed data.

Josh Petrie's remarks are right on. Since we're talking about Games here, runtime performance is valued very highly while maximal compression is merely a nice thing to have.

Preparing data offline to unpack directly into C structures on a target platform is very fast technique that's been used for decades. While I'm sure it could be perverted into an attack vector it's far more likely that the EXE itself is violated and not the data and so efforts to failsafe the data are wasted and better spent elsewhere.
> 1 votes

# Answer
I wouldn't bother sanity checking or asserting against the size of individual assets. I would have a report or something that could tell me the total size of my final asset bundle, and if that exceeded something I was comfortable with I might look into using a more aggressive compression routine or something, but that would be an entirely manual check unless I was working on a platform with very strict hardware limitations (and thus I had very strict memory budgets).

Regardless this would be something done at asset compile time, and would be optional, otherwise one might restrict the ability for end-users to mod one's game, which is usually a negative.

Remember that exceeding the predefined bounds of your asset volume may have just meant you mis-estimated your asset volume in your initial planning, not that anything has, per se, gone "wrong."

I also wouldn't worry too much about this because of most of the time compressing the data "well enough" or not is largely out of our hands -- sure, we can elect to use data formats that compress better under certain algorithms, but we shouldn't be doing that at the cost of quality of the in-game asset as a general rule, and unless we're writing our own compression there's only so far we can get things compressed. Unless I've misunderstood you, I sort of feel like this issue is overly hand-wringy.
> 1 votes

# Answer
It is telling that big games have not tried too hard to keep the file formats slim. Things like MD2 and MD5 would compress much much better and be much smaller if they weren't text formats, if they were triangle strips and fans and such, and other simple tricks. Its as if the team were deliberately not concerning themselves with data size.

On the other hand, compressing the textures and the cut scenes seems to be worth much more effort.

I would always favour robustness over size. It worries me when I see binary formats that are designed to fit a given C struct layout. That will really bite you later. And its where bugs can hide and, later, an attack vector. Best to go with nice formats that you read in and validate each and every load. Triply so if you start using user generated content or p2p.

I'm just a hobbyist who has looked at file sizes for the current spins on Glest and my own efforts. I see that Charles Bloom - someone who really made an impact on compression in the 1990s - then went to Oddworld. One wonders why compression wasn't a talked-up part of what he did there - you can draw the conclusion that if the top dog in the data compression field goes and does graphics engines for game company, rather than data compression, that data compression is not where its at. He probably cares more about load times in the gaming context? His blog is brilliant.

Compression is about data modeling. It is legal for all vertices to be in any random point in 3D space, but then your model would look like a porcupine. In real life, the actual position of a vertex - if you know those it is attached to - is fairly constrained and predictable. If you google "compress mesh" and such you find lots of academic papers, but I don't know anything mainstream.

I've played with making predictors. Its not so different from LOD makers really. It didn't seem to have much application - would people adopt a mesh format that was half as small again as existing ones LZMA2ed models?
> 0 votes

# Answer
Rule 1) Only handle what you are designing for.

If you are developing a game where assets are being made by someone Other than you, then generally you will want to validate them. If they are only being made by you then it might be overkill to do upfront.

Secondly.. If you are running some sort of compression on your assets prior to use (I prefer in-memory expansion of pre-loaded data chunks because its where ya get the nice few second load times from :D), then you can have whatever it is that is compression or otherwise compiling your assets do the checks as well.

Remember Rule #1 ;) Too often people (read, programmers) try to handle every situation under the sun, because that is what we are taught.. All your application ever needs to handle is what it will run into.

As for a way to validate an overall asset set to make sure people havent screwed with it. Generate a hash value (Sha1, MD5, both?) and store it internal to your application. Then if the has value of your assets does not match what is stored, they are not running what you gave them.
> 0 votes

---
Tags: assets, release, compression, validation
---


# Question
Title: Thread problem updating Windows Forms control in XNA C#
I'm development a network card game, and for now i've two players connected but there is a problem with one of them, this one can't do anything on the game. Looks that screen was blocked. I'm think that is because a code i used before.

That code is:

```
if (InvokeRequired)
            {
                this.Invoke(new MethodInvoker(delegate
                {

                   ...

            }));
                return;
            }

```

The code above is surrounding code to changing Button values, make connection with server and create game window. Without this code a warning is shown.

InvalidOperationException was unhandled

Cross-thread operation not valid: Control 'startGameButton' accessed from a thread other than the thread it was created on.

# Answer
> 1 votes
Win Forms only allows the UI thread to access and create UI Controls. There is an inbuilt way to run delegates on the UI thread for particular control: Control.BeginInvoke(): http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx.

So you would need something like:

```
 if (BeginInvokeRequired)
 {
     startGameButton.BeginInvoke(new InvokeDelegate(delegate()
       {
          startGameButton.Text = "blah blah";
       }));
 }
 else
 {
     ...
 }

```

(If your code is in the startGameButton as it seems to be just replace startGameButton with this).

Incidentally there are few bad things with your original code. Notice I have removed your early return in the if block and I wrap the rest of the method in the else - this is because I am using BeginInvoke() not Invoke() which will return immediately - your delegate will be placed on a queue and be run when UI thread can run it - using Invoke you would have to wait until the UI thread has run it which is unneccesary (it should be run straight away anyway as the UI should not have long running operations to perform).

You needn't use anonymous delegates by the way:

```
public void UpdateStartButton()
{
    startGameButton.BeginInvoke(new InvokeDelegate(UpdateStartButtonCallback));
}

private void UpdateStartButtonCallback()
{
    startGameButton.Text = "blah blah";
}

```

# Answer
> 0 votes
Looks like you're using WinForms for your windows. You're not allowed to run WinForms control delegates on a thread that does not own said control.

The old way of working around this is described here: http://msdn.microsoft.com/en-us/library/zyzhdc6b(v=vs.80).aspx

Though instead I would take the new school route and use BeginInvoke: http://msdn.microsoft.com/en-us/library/0b1bf3y3(v=vs.80).aspx

Which just lets you forget about any of that boilerplate code :)

---
Tags: c#, windows-forms
---


title: Drawing particles as a smooth blob

text:
# Question
Title: Drawing particles as a smooth blob
I'm new to game/graphics development and I'm playing around with particles (in 2D). I want to draw particles close to each other as a blob, just as liquid/water. I do not want to draw big circles overlapping as the blob won't be smooth (and too big). I don't really know physics but I assume what I want is something looking similar to surface tension.

I haven't been able to find anything on stackexchange or on Google (maybe I do not know the correct keywords?). So far I have found two possible solutions, but I am unable to find any concrete information about algorithms.

One of them is to calculate the concave hull of particles I consider being a blob. I can calculate the blob by creating an equivalence class (on the relation "close to each other"). Strangely enough I haven't been able to find *any* algorithm explaining how to calculate the concave hull. Many posts (and among stackexchange) links to libraries or commercial products that do this (I need libraries to work in C#), but never any algorithm. Also this solution might have a problem with a circle of particles, which would not detect the empty space in the middle.

While researching concave hull I stumbled upon something called alpha shapes. Which seems to be exactly what I want to do, however just as with concave hull I haven't found any source explaining how they actually work. I have found some presentation materials but not enough to go on. It's like a big secret everyone knows except me :-/

After calculating the concave hull or alpha shape I want to make it a Bézier curve to make it smooth and nice.

Although I do find my approach a bit too complex, maybe I am trying to solve this the wrong way? If you can either suggest any other solution to my problem, or explain the pieces I am missing I would be very happy and grateful :-)

Thanks.

# Answer
> 8 votes
The keyword you might need is "Metaballs," and ranges from the complex nVidia GPU Gems sample down to the demo scene driven versions designed only to look good and run fast.

# Answer
> 1 votes
To convert a group of particles to a mesh to can render, metaballs style, you can take a look at the Marching Cubes algorithm, which generates a polygonal mesh from voxel data. There is a demoscene demo that has a great example of this, with everything generated on the GPU: numb res.

# Answer
> 0 votes
As mentioned above, you are thinking of Metaballs.

This is a great article on the subject with some basic theory discussion and examples.

Exploring Metaballs and Isosurfaces in 2D

---
Tags: 2d, c#, algorithm, graphics-programming, particles
---


# Question
Title: How to implement line of sight restriction in actionscript?
I have a problem with a game i am programming. I am making some sort of security game and i would like to have some visual line of sight. The problem is that i can't restrict my line of sight so my cops can't see through the walls. Below you find the design, in which they can look through windows, but not walls. Further below you find an illustration of what my problem is exactly.

this is what it looks like now. As you can see, the cops can see through walls.

This is the map i would want to use to restrict the line of sight.

So the way i am programming the line of sight now is just by calculating some points and drawing the sight accordingly, as shown below. Note that i also check for a hittest using bitmapdata to check whether or not my player has been spotted by any of the cops.

```
private function setSight(e:Event=null):Boolean
{
    g = copCanvas.graphics;
    g.clear();

    for each(var cop:Cop in copCanvas.getChildren())
    {
        var _angle:Number = cop.angle;
        var _radians:Number = (_angle * Math.PI) / 180;
        var _radius:Number = 50;

        var _x1:Number = cop.x + (cop.width/2);
        var _y1:Number = cop.y + (cop.height/2);
        var _baseX:Number = _x1 + (Math.cos(_radians) * _radius);
        var _baseY:Number = _y1 - (Math.sin(_radians) * _radius);

        var _x2:Number = _baseX + (25 * Math.sin(_radians));
        var _y2:Number = _baseY + (25 * Math.cos(_radians));
        var _x3:Number = _baseX - (25 * Math.sin(_radians));
        var _y3:Number = _baseY - (25 * Math.cos(_radians));

        g.beginFill(0xff0000, 0.3);
        g.moveTo(_x1, _y1);
        g.lineTo(_x2, _y2);
        g.lineTo(_x3, _y3);
        g.endFill();
    }

    var _cops:BitmapData = new BitmapData(width, height, true, 0);
    _cops.draw(copCanvas);

    var _bmpd:BitmapData = new BitmapData(10, 10, true, 0);
    _bmpd.draw(me);

    if(_cops.hitTest(new Point(0, 0), 10, _bmpd, new Point(me.x, me.y), 255))
    {
        gameover.alpha = 1;
        setTimeout(function():void{ gameover.alpha = 0; }, 5000);
        stop();

        return true;
    }

    return false;
}

```

So now my question is: Is there someone who knows how to restrict the view so that the cops can't look through the walls? Thanks a lot in advance.

ps: i have already looked at this tutorial by emanuele feronato, but i can't use the code to restric the visual line of sight.

# Answer
Since you already check if the player is inside the viewing-area of a cop, you can follow this up by a line-of-sight check.

It seems like you use a bitmap-based approach for your entire world. Therefore I suggest you do the following:

* Check if player is inside a viewing-area of a cop
* If yes, use the Bresenham line algorithm to sample pixels of the *walls map* from the cops position to the players position. If you hit a black pixel, the view is obstructed by a wall.

While this is not really accurate (your player can hide behind a small object, if the line from cop to player goes through that object), it will be really fast and should be accurate enough for your game.

**Update:** To improve this a little bit, you could do two line-of-sight tests, from the cops position to the leftmost point of the player and to the rightmost point, as shown in the following image:

---

### Edit

It seems like you want to dynamically paint the actual viewing-area of each cop instead of just a triangle. A way to do that would be to look into 2D shadowing. I once did a quick flash experiment with 2D shadows based on a bitmap image. I integrated your wall map into my code. Here's the interactive result, and here's the source-code which you're free to use as a starting point for your own implementation.

In the top left, you'll see the composed image, on the top right there's the original map image. Bottom left shows the calculated light pixels and on the bottom right you'll find the distance-map that was used. You can drag the light with the mouse and increase/decrease the light radius using the arrow keys (left/right). Instead of rendering a circle, you would only render your triangle as active "light".

To make the calculation of every single pixel inside the light radius reasonably fast, I use a distance map that is being used to look up how much distance can be traveled from any given pixel without hitting an obstacle. The distance map is calculated at initialization time, therefore the flash file takes a while to initialize (because calculation of the distance-map is quite CPU heavy). To avoid this, you could also pre-calculate your distance-maps and store them as individual files.

Please note that a distance-map won't work with moving obstacles though.
> 10 votes

---
Tags: flash, actionscript-3, line-of-sight
---


# Question
Title: Role of an entity state in a component based system?
Component-based entity systems are all the rage these days; everyone seems to agree they are the way to go, but no one really has a definitive implementation of such a system. I was wondering, what role do entity states (walking-left, standing, jumping, etc) have in a CBS? Do they act like controllers (i.e. they handle events and change the entity's attributes based on those events)?

What about cases where a state would, for example, require that the entity enters no-clip mode? Should, that state, when it enters, maybe set the CollisionComponent of the entity to a null pointer or something? (Then, on exit, the state should restore the entity's CollisionComponent to its previous state.)

Also, I guess it's the current state's job to change the entity's state to something else, right?

# Answer
I was under the impression that in a components based design the entities are essentially components containers (with possibly some message thrown in). Viewed from this perspective the each components would store a little of the state. For instance if the ghost-behavior-components decides it needs to enter the intangible mode it also sends a message to the physics component telling it to enable no-clip. It would probably also send a message to the ghost-model-components telling to kick up the alpha.
> 9 votes

# Answer
State machines and components are orthogonal techniques. You can have states in your components or not, just as you can have states in any class. You can have a component observe (see Observer Pattern) and change another component's state. State machines have many uses and the implementation will depend on your needs.

For character the character states you described (walking, standing, jumping), I have seen implementations where the various components all maintain their own state machines... physics, animation, controls, ai. The components should have a clear authority about which other components they react to, and which component states they can change.
> 2 votes

# Answer
Design Components as structures with data only, no logic more complex than getters and setters. Don't create dependencies between Components or you'll end losing most of the benefits of an Entity System.

See an example of this approach(close to t-machine vision) here: https://github.com/thelinuxlich/starwarrior\_CSharp

And the engine itself: https://github.com/thelinuxlich/artemis\_CSharp
> 2 votes

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


# Question
Title: Objective C and C++ for Game Development
I'm trying to figure out which language I should begin learning. I've only been programming for about 6 months, with languages like PHP, Java, and C#. I want to learn how to dev games, and while I know in most cases the answer to this would be through C++ (at least, I would think), though I'm still curious about what Objective C can offer in the sense of long term benefit.

It seems like there's a chance that Objective-C may actually become more popular than C++ in a few years, and for all I know, it may become the de facto standard development language for games. Still, despite all of this, I really don't know anything, and this is all speculation.

Both languages seem very interesting, and obviously can pull a lot of out of themselves.

What do you think?

Note: despite what some might say, I really don't want to end up using prebuilt engines, and would rather just learn how to make my own. I'm well aware that it takes a lot more time, but I'm quite ok with that.

# Answer
> 9 votes
> I want to learn how to dev games, and while I know in most cases the answer to this would be through C++ (at least, I would think),

Actually, while C++ is an important language for anyone aspiring to enter the field professional, it is *by no means* the language you have to learn to make games and, in fact, makes for a rather poor first language (primarily due to its complexity, the wealth of incorrect/poor information on the language out there, and most important its cultural penchant for assuming the programmer is right, which is bad for a neophyte).

> It seems like there's a chance that Objective-C may actually become more popular than C++ in a few years, and for all I know, it may become the de facto standard development language for games. Still, despite all of this, I really don't know anything, and this is all speculation.

Something will replace C++ eventually, as C++ has by and large supplanted C, which has by and large replaced machine-specific assembly. That said, it's very hard to gauge what will replace C++ and mostly a thought experiment -- for practical concerns, it doesn't matter what language we all eventually move on to.

It's fair to surmise that the popularity of the iOS platform might help usher in a new era for Objective C, one where it's not considered some unusual warty distant cousin of C++. But in practice one can write iOS games with a bare minimum of Objective C bootstrap code (doing the rest in C++), and Objective C itself doesn't offer enough modern advances to make it otherwise more attractive, so I doubt it will replace C++ ever.

> Note: despite what some might say, I really don't want to end up using prebuilt engines, and would rather just learn how to make my own. I'm well aware that it takes a lot more time, but I'm quite ok with that.

Do you realize that using pre-built technologies is (1) essentially inevitable (you'll be using a pre-built runtime on a pre-built OS for example) and (2) orthogonal to the issue of which language you use?

It's fine to build things yourself for learning purposes, but don't let "not invented here" syndrome get you in its claws. Once it has you, it's hard to get out, and it's very easy for a new programmer to get snatched up. Resist the temptation, you *will* be a better developer for it in the long run.

**So all that ancillary stuff being said, to answer your real question:**

It doesn't matter which language you pick. My personal recommendation for people who want to get into game development and don't already know any programming languages is C# or Python. If you already know a language, use that language (it sounds like this is where you fit; if you know some C# already, I'd say continue using that). If you really can't decide, flip a coin. Between C++ and Objective C I'd say go with C++, since I think the available tools are more mature (especially on the Windows platform -- Xcode is decent if you are on a Mac, but it's no Visual Studio).

A good programmer will know many languages and, similarly, the more languages a programmer knows the easier it is for her to pick up more. So you should never be focused on trying to predict the motion of the industry so as to study the "right" language. Instead, pick something, learn it, make some games, and move on to new languages as the time comes. You will never be wasting your time doing so.

# Answer
> 7 votes
From my perspective, Objective-C is mainly used to develop for OS X and iOS. And even there, a lot of people tend to use C++ because of portability. Looking at a language comparison over at Ohloh, I can't really see much of a trend that Objective-C will replace C++ in the near future.

Also have a look at this question (Objective-C or C++ for iOS?).

I personally like Objective-C, but C++ is far more widespread and very portable. You'll also find tons of resources and libraries about/for C++. If you want to develop specifically for iOS or Mac OS X, you could consider Objective-C, but for all other cases I strongly reccomend C++.

# Answer
> 3 votes
Here are a couple of other posts that are related to your question:

Is C++ "still" preferred in game development?

What are the most commonly used programming languages?

Am I hurting myself by not knowing C++ for game design?

Also, this isn't terribly relevant, but I thought it was interesting: Google's language performance comparison

# Answer
> 1 votes
Where raw performance is concerned, C++ as a language has an advantage over Objective-C as it favors compile-time over runtime (static dispatch, templates, C++ 0x `constexpr`). It is doubtful that Objective-C will ever replace C++ as the lingua france of cutting-edge game development.

However, more dynamic languages like Objective-C are generally superior where ease of implementation is concerned. But no one forces you to implement your game in a single language, and it's common to embed the runtime for an even higher-level language like Lua into C++ game engines.

This isn't to say that Objective-C is a bad language for game development - its rather unique combination of raw performance and dynamism definitely fits the problem domain, and thanks to Apple it has recently gained some popularity - but it's not a silver bullet: There are better choices for the highest and the low end of the performance spectrum.

---
Tags: c++, objective-c
---


title: Creating Entity as an aggregation

text:
# Question
Title: Creating Entity as an aggregation
I recently asked about how to separate entities from their behaviour and the main answer linked to this article: http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy/

The ultimate concept written about here is that of: OBJECT AS A PURE AGGREGATION.

I'm wondering how I might go about creating game entities as pure aggregation using C#. I've not quite grasped the concept of how this might work yet. (Perhaps the entity is an array of objects implementing a certain interface or base type?)

My current thinking still involves having a concrete class for each entity type that then implements the relevant interfaces (IMoveable, ICollectable, ISpeakable etc).

How can I go about creating an entity purely as an aggregation without having any concrete type for that entity?

# Answer
> 6 votes
The "pure aggregation" approach described by West in that linked article eschews an "entity" object altogether. There are components, floating around in memory, but they are tied together only by implicit relationships, if at all.

One way to do this is a so-called outboard approach. In such a system, components are held by systems that manage or otherwise control them (I use the term "manage" here, but you shouldn't take this to mean I'm suggesting that you have a bunch of \*Manager classes to hold component types). For example, your physics system may hold on to a bunch of things representing each rigid body in its simulation world, and may expose those things as PhysicsComponents. The components can be the actual objects handled by the subsystem in question, or they can be proxies for those objects, as needed.

In such a system there isn't necessarily a need for an "Entity" class to hold a collection of references to the components that comprise it; instead a notification is raised concerning the creation or destruction of an "entity" and each subsystem that handles components looks at the description of the created/destroyed entity (which is typically loaded from some data) and determines if a component is necessary for it.

One of the advantages to this approach is that you get really good locality of reference for each component. Unfortunately it's a bit weird, overall, and not the most friendly flavor of component-based entities I've encountered. Sometimes it is really convenient to have a real object that represents an entity, even if that object does little more then aggregate weak references to components that are still held by other subsystems (if nothing else it provides a easy way to route messages between components).

There are several good ways to implement component oriented game object systems; it really, really, *really* helps if you have a solid idea of the requirements you want out of your system -- you can look at what popular frameworks like Unity do for examples. Without setting strict requirements for yourself, you may run into the problem of endlessly "designing" the system without ever really building it, trying in vain to hit upon the perfect implementation. For whatever reason I've seen this a lot with component systems.

# Answer
> 3 votes
The way Unity does it is that all scripts (in your case, game code that's specific to a type of game object) derive from a base class, `MonoBehaviour`, which itself derives from the more relevant-to-your-case `Component` class. You never edit (and don't have access to the code of) the GameObject class.

The game object is in charge of containing all those `Component`s. It's also ostensibly in charge of calling the relevant functions on them (i.e. `Update`). Unity uses reflection to determine what functions to call (look at the "Overridable Functions" section on this page), but you'd probably want to make them virtual.

So one of the mechanisms that you use in Unity is getting components on your current game object (or its children) by type. There are some helper properties that wrap some of the common stuff. For example, if you want to access the game object's `Transform` component (to control the game object's position/rotation/scale), you would normally have to do something like `this.GetComponent<Transform>().position`, but they wrap that into a helper `this.transform.position` call. Another common pattern is accessing the current game object's `Renderer` component. So if you want to do something like change the current game object's material, from another script you might do something like `this.renderer.material = someOtherMaterial`, and your game object updates appropriately.

One of the ways this works in Unity is that their editor is set up such that you can create game objects in your scene that have components already hooked up. In Unity's case, all game objects have a `Transform` component, but it can also contain built-in types like `AudioListener` or `Renderer`, which do what you would expect. Or you can add your own components that do whatever it is you want them to do. The editor also exposes public/serializable fields on your components so you don't have to make different scripts if you want to use the same basic code but change a few magic numbers around.

All in all it's pretty slick, and I'd suggest downloading the free version of Unity and playing around with how their scripting system is set up as a pretty decent proof of concept of what you want to achieve.

# Answer
> 0 votes
I like a approach more close to Adam's vision from the t-machine blog. Components should be only data, and systems do all the job with them.

See an example of ES implementation in C#: https://github.com/thelinuxlich/artemis\_CSharp

And an example game using it(XNA 4): https://github.com/thelinuxlich/starwarrior\_CSharp

---
Tags: c#, architecture, design-patterns, component-based, entity-system
---


# Question
Title: Sources (other than tutorials) on Game Mechanics
But, I'm not quite sure where I should start from here. I know I have to go and grab an engine to use with some prebuilt libraries, and then from there learn how to actually code a game, etc. All I have right now is some "program Tetris" tutorial for C++ open right now, but I'm not even sure if that will really help me with what I want to accomplish.

I'm curious if there are is any good C++ documentation related to game development which provides information on building a game in more of a component model (by this I'm referring to the documentation, not the actual object-oriented design of the game itself), rather than an entire tutorial designed to do something specific. This could include information based on various design methodologies, or how to link hardware with OpenGL interfaces, or just simply even learning how to render 2D images on a canvas.

I suppose this place is definitely a good source :P, but what I'm looking for is quite a bit of information - and I think posting a new question every ten minutes would just flood the site...

# Answer
> 0 votes
i started to place a comment bt it went to long so changed it to an answer :

first of all you have specify your target platform, and it would also help if you tell which genre are you going to create a game. the brad answer is to download and install dx SDK if you are going to develop for microsoft group or opengl sdk if you are going to develop for others. there are many sample codes with enough documentation inside each sdk.

or you can just pick a game engine again based on the genre and platform you are going to create your game and start reading that engine's specific manual. studying a engine help you create your games easier but will take you a lot more time until you reach the point that you can start your games from the scrach( and blieve me starting to develop a gameengine is almost always a bad idea). for stat I suggest essenthel engine. it comes out with a lot of samples and an active community and it's very easy to use almost the easiest engine i've ever seen in c++ and it's also free unless you want to publish a game with it. but it needs a lot of c++ knowledge to begin with and one might consider it as a moderate engine compared to UDK or similar gigantic engines.

--edit--

esenthel engine has only target platform of pc and mac and if you are a license developer you can also create games for ipad/iphone. for an opensource game development i recommend taking a look on ogre3D, it's an opensource engine and even there is chapter in "deitel & deitel: c++ how to program" about it. but as far as I know (I didn't try that engine myself) it's almost somevery basic framework which force you to add many conecpts of your game yourself. And I think givving a bigger challange you can learn a lot more if you really get into it.

# Answer
> -1 votes
Its questions like these, is why I wrote this (check link) and guess what it got closed and voted down. Anyway I hope it is of some use to you.

https://gamedev.stackexchange.com/questions/12892/education-paths-to-game-programming-dev-on-windows-linux-june-2011

The most important part of that link is that I recommend you "Game Coding Complete", its near the bottom of the link I gave.

---
Tags: game-mechanics, documentation
---


title: Does md2 support skeletal meshes?

text:
# Question
Title: Does md2 support skeletal meshes?
I'm creating an FPS game. I'm writing my own game engine. So far all the backend stuff is going great. I'd like to support md2 as the native file format for 3D Objects, but I also want to use skeletal meshes. Does anyone know if the md2 file format supports skeletal meshes?

In-case you need to know, I'm going to use blender as my Mesh creation tool and C++ as my programming language...

Thanks

For got to mention, the engine is based on OpenGL...

Alright, for anyone who is reading this, I just found the Doom 3 md5 specifications (http://tfc.duke.free.fr/coding/md5-specs-en.html). It gives you some help on writing a parser (see bottom of link), but the example doesn't support lighting and texture mapping (the second set of example code allows for animation). Thanks @Neverender for answering my question...

# Answer
> 3 votes
No, nor did the MD3 format used in Quake 3. As far as I know, skeletal animation was introduced as recently as id Tech 4 and the MD5 model format.

---
Tags: c++, 3d-meshes, skeletal-animation
---


# Question
Title: LWJGL Determining whether or not a polygon is on-screen
Not sure whether this is an LWJGL or math question. I want to check whether a shape is on-screen, so that I don't have to render it if it isn't. First of all, is there any simple way to do this that I am overlooking? Like some method or something that I haven't found? I'm going to assume there isn't.

I tried using my trigonometry skills, but it is hard to do this because of how glRotate also distorts the image a little for perspective and realism. Or, is there any way to easily determine if a ray starting from the camera, and going outward in a straight line intersects a shape? (I can probably do it with my math skillz, but is there an easier way?)

By the way, I can easily determine the angle at which the camera is facing around the x and y axis.

EDIT: Or, possibly, I could get the angles of a vector from the camera to the object, and compare those angles to my camera angles. But I have a feeling that the distorts from glRotate and glTranslate would be an issue. I'll try it though.

# Answer
> 1 votes
You could research frustum culling. Ideally done as coarsely as possible (say on a whole object - with maybe a bounding sphere), from this you know if it's completely inside (and all visible), part-in, or completely outside and therefore no rendering needed. Depending on what you're trying to achieve, it's possibly faster for the GPU to render some of these primitives than to try and determine their visibility first. The GPU is very good at discarding triangles that are completely outside the screen. So it might be good enough to just throw away objects that are definitely not visible and render the rest. You could cull individual polygons against the frustum too, but I'd profile this to see if it's actually faster or slowing you down.

# Answer
> 1 votes
You can use Occlusion Query for this very efficiently. It is simple thing saying how many fragments were rasterized. So first you draw all the renders to set z-buffer and than you ran occlusion query to know how big portion of the object is visible. If you need exact portion you first run query before rendering (you get number for fully visible object) and one after rendering (you get visible portion). Then divide the first value with second one(this is useful when size of object on screen changes every frame)

As this thread says, occlusion queries are supported by lwjgl.

And GPU Gems article for more details

---
Tags: opengl, lwjgl, visibility-determination
---


# Question
Title: Is dynamic casting Entities A good design?
For my game,

Everything inherits from Entity, then other things like Player, PhysicsObject, etc, inherit from Entity. The physics engine sends collision callbacks which has an Entity\* to the B that A collided on. Then, lets say A is a Bullet, A tries to cast the entity as a player, if it succeeds, it reduces the player's health.

Is this a good design?

The problem I have with a message system is that I'd need messages for everything, like: entity.sendMessage(SET\_PLAYER\_HEALTH,16);

So that's why I think casting is cleaner.

# Answer
Virtual function calls **are** your messages:

```
void Player::onCollision(const Entity& collisionEntity)
{
    Player::setHealth(Player::getHealth() - collisionEntity.damageValue());
}

```

Provide them with (empty) default implementations so an Entity will only handle the events it wants to.

When your Entity class inevitably starts to become bloated, it's either time to push some methods down the hierarchy, or begin moving to a component-based design.
> 9 votes

# Answer
Bullet collide with an object ( whichever ) and sends a message to the object. bullet.sendMessage( other\_object, BULLET\_IMPACT,16); the bullet doesn't need to know the details of the destiny object.

If the object is a player.

```
void Player::handleMessage( Message* msg )
{
   if ( msg->type() == BULLET_IMPACT )
       doDamage( msg->data() );
}

```

The destiny decides the action.

Avoid cast wherever you can.
> 3 votes

# Answer
Dynamic casting is really not something you want to design your code around.

Instead, virtual functions on your Entity/Player/PhysicsObject/etc classes are your best friends.
> 2 votes

# Answer
Handling collision is a common problem in games. The tricky part is that the way a collision is handled depends on *both* of the things that are colliding. You want to be able to select an appropriate method based on a pair of classes, not just one. Unfortunately, most OOP languages like C++ only support *single* dynamic dispatch (which is what virtual methods and overriding are).

What you want is *double dispatch*. You can imagine four functions like this:

```
void playerToPlayerCollision(Player* a, Player* b) { /* ... */ }
void playerToBulletCollision(Player* a, Bullet* b) { /* ... */ }
void bulletToPlayerCollision(Bullet* a, Player* b) { /* ... */ }
void bulletToBulletCollision(Bullet* a, Bullet* b) { /* ... */ }

```

And somehow the language would magically pick the right one based on the two `Entity*` objects that collided. You can make that magic work using a combination of overriding (for the first dispatch) and the visitor pattern (for the second). It looks like this:

```
class Entity {
  // Physics engine calls this:
  virtual void collide(Entity* other) = 0;

  virtual void collideWithPlayer(Player* player) = 0;
  virtual void collideWithBullet(Bullet* bullet) = 0;
}

class Player : public Entity {
  // Double dispatch:
  virtual void collide(Entity* other) {
    other->collideWithPlayer(this);
  }

  // Actual collision-handling functions:
  virtual void collideWithPlayer(Player* player) {
    // Player -> Player collision.
  }

  virtual void collideWithBullet(Bullet* bullet) {
    // Player -> Bullet collision.
  }
}

class Bullet : public Entity {
  // Double dispatch:
  virtual void collide(Entity* other) {
    other->collideWithBullet(this);
  }

  // Actual collision-handling functions:
  virtual void collideWithPlayer(Player* player) {
    // Bullet -> Player collision.
  }

  virtual void collideWithBullet(Bullet* bullet) {
    // Bullet -> Bullet collision.
  }
}

```

When the physics engine calls `collide`, that gets overridden by `Player` and `Bullet`. Those overrides dispatch on the first of the colliding objects. They immediately call another virtual method on the *other* colliding object. That method does the second dynamic dispatch and you ultimately select one of four methods based on the types of both arguments. No casting required.

This pattern only has two real limitations:

1. It's complex and obscure. Unless you recognize the pattern, the code here is kind of strange looking and hard to grasp.
2. You're constrained to a fixed set of subclasses. You'll note that `Entity` now is aware of the `Bullet` and `Player` subclasses. It will need to be aware of *all* subclasses that you dispatch on, which defeats the open-ended subclasses you usually get in C++.

If you can live with those, this pattern works pretty well.
> 2 votes

# Answer
There's nothing wrong with a good `dynamic_cast`. It is not the best design in many situations, but in some, it simply is the best, and in this kind of code, `dynamic_cast` is the right way to go. You don't want to make your derived classes aware of each other, and you don't want to put things in the interface that don't make sense. For example, what if a player collides with a wall? Unless you think that should do damage, it doesn't make sense to give Entity a DamageValue- because not all Entities have damage or do damage to the player upon collision.
> 1 votes

# Answer
Aside from using virtual functions as others already mentioned, you should also store an enum in the "base" class that specifies the type. Something like:

```
enum eEntType{
ENT_PLAYER,
ENT_PHYS,
ENT_ETC
};
eEntType m_eType;

```

Have the base class constructor take in an `eEntType` which sets it at the get-go. Then make read-only accessors to them. This is a quicker way of differentiating these objects, and it's good on the go/any time.

All the deriving subclasses should use the member initializer list passing a 'hardcoded' value of its type to the base ctor.
> 0 votes

---
Tags: c++, architecture
---


# Question
Title: Accept keyboard input when game is not in focus?
I want to be able to control the game via keyboard while the game does not have focus... How can I do this in XNA?

EDIT: I bought a tablet. I want to write a separate app to overly the screen with controls that will send keyboard input to the game. Although, it's not sending the input DIRECT to the game, it's using the method discussed in this SO question:

https://stackoverflow.com/questions/6446085/emulate-held-down-key-on-keyboard

To my understanding, my test app is working the way it should be but the game is not responding to this input. I originally thought that Keyboard.GetState() would get the state regardless that the game is not in focus, but that doesn't appear to be the case.

# Answer
Probably the safest way of doing that would be a little IPC (inter-process communication) that your game starts and listens to and your overlay tries to find and sends messages to.

The exact API to create that channel is going to be operating system specific. Wikipedia gets into some elaborate software, but something as simple as a shared memory area (with thread safe locks controlling access) and a shared data structure to pass the information along would work great.
> 1 votes

# Answer
If your game does not have focus, it should not be reading input - that is a giant programming taboo.

However, it is possible. Use P/Invoke to call SetWindowsHookEx with the parameter `WH_KEYBOARD` (and dwThreadId set to null). This will call your hook event on every keypress, no matter what window has focus at the time.

Again, though, I am not recommending this. It is quite likely this will even trigger some virus scanners.
> 0 votes

---
Tags: xna, c#, keyboard
---


# Question
Title: Unity, changing gravity game & stopping character when he hit a wall
I am currently working on a 2d puzzle game in the unity engine. One of the aspect of this game is the possibility to rotate the level of 90°. It also rotate the gravity.

The main character is not directly controlled by the player, but instead falls when the level is rotated.

When the main character hits a wall, he should stop to moving. If I do not stop it, it kind of blinks and shakes against the wall.

To stop it I detect collision and depending on the current rotation state, the player will stop at "vertical" or "horizontal" tags when a OnCollisonEnter occurs. I must do that because when the player falls on his relative ground, he must not stop like if he had touched a wall.

My problem is the 'side' of platform, or the 'top' of wall, they use the same tag and thus do not give the correct tag to my character. I tried to put a very small invisible box on top/side of elements but the collision occurs nevertheless. It seems when the player falls and hit something he go through a bit before being replaced at correct position by unity.

Is there a way :

1 ) to not stop my character but to make it appear immobile on screen

2 ) To detect a "I cannot move anymore" collision other than by using collision?

# Answer
> 1 votes
Perhaps your "walls" should be made of 4 planes, each of which has the appropriate horizontal or vertical tags.

# Answer
> 1 votes
I must admit, I don't see anything that should pose problem here in unity.

You can just have your walls as static colliders that you place manually, and use a *capsule collider* for your player. The Unity Platform tutorial is good even if it is in JS for the most part, and may help you with collisions.

The problem of the character "blinking" seems to me that it is just a physics problem (maybe the character is too small or too large). You should **NEVER** manually set the x / y position of something when using a physics engine, you need to let it do it's job.

*Although to try and answer your questions :*
In Unity you can create different Tags, which you can check on a collision. This means you can tag colliders that have special properties, and in your collision code check gameObject.transform.tag == "*YourTag*". You should be able to differentiate the vertical and horizontal walls this way.

*In response to 2) :*
If you do not want to use Physics, but still use collision detection, your objects have to be static, and you need to set the colliders as ***Triggers***. This also means in your code you have to use *OnTriggerEnter()* / Exit, etc.

```
"It seems when the player falls and hit something he go through a bit before being replaced at correct position by unity."

```

To counter this problem, you could reduce your physics time-step in the Physics properties of the game, or make the number of iterations higher.

# Answer
> 0 votes
1) i'm not sure but if you change you object from dynamic to static should do the trick, since static objects can't move even if they have some speed

2) not knowing a way to tell flag "i cannot move anymore" but you can always check wheather the speed or at least average speed of 1 past second is less than somthing that would happen only if you spot the character or it stuck somewhere in walls.

---
Tags: collision-detection, unity
---


# Question
Title: How to store character moves (sprite animations)?
So I'm thinking about making a small rpg, mainly to test out different design patterns I've been learning about. But the one question that I'm not too sure on how to approach is how to store an array of character moves in the best way possible.

So let's say I have arrays of different sprites.

This is how I'm thinking about implementing it:

```
array attack = new array (10);
array attack2 = new array(5);

(loop)
//blit some image
attack.push(imageInstance);
(end loop)

```

Now every time I want the animation I call on attack or attack2; is there a better structure? The problem with this is let's say there are 100 different attacks, and a player can have up to 10 attacks equipped. So how do I tell which attack the user has; should I use a hash map?

# Answer
There are many ways to implement animations, generally you would use a sprite sheet. This can get compilcated, but an easy way is to predefine character size, for example 128\*64, and pre-calculate the number of lines and columns to get the total number of frames. I assume you are familiar with this however.

You could end up with something like this (C# esque assuming tightly packed sprite sheet) :

```
class Animation {
    Texture2D spriteSheet;
    ushort rows, columns;

    Animation(ushort spriteWidth, ushort spriteHeight)
    {
        rows = spriteSheet.Height / spriteHeight;
        columns = spriteSheet.Width / spriteWidth;
    }

    Rectangle GetFrame(ushort frameNumber);
};

```

If you have hundreds of animations, this will mean hundreds of sprite sheets and lots of memory. If you look at some older games, you could have the same animation for each melee attack, but the weapon's animation was put on top of that. This means a big save in sprite sheets, and could be useful.

To check what attack a player currently has, I would simply have an array of animations (pre-loaded or not) which will be referenced by the player depending on the attacks he chooses. If you choose to decouple parts of the animation, an `AttackAnimation` could contain multiple animations for the top half of the body, the bottom hals, the weapon, etc.

That could be something like this :

```
class AttackingAnimation {
    List<Animations> animationList;
    // Draw and update all animations...
}

class Player {
    AttackingAnimation attackingAnimations[10];
    DoAttack(int attackIndex);
};

```
> 2 votes

# Answer
You're gonna want to think at a higher level. Playing and switching among a sequence of frames to create an animations should be encapsulated on the lowest level. It should know nothing about how many, or what attacks the player has.
> 1 votes

---
Tags: architecture, flash, animation, sprites, rpg
---


# Question
Title: Writing the correct value in the depth buffer when using ray-casting
I am doing a ray-casting in a 3d texture until I hit a correct value. I am doing the ray-casting in a cube and the cube corners are already in world coordinates so I don't have to multiply the vertices with the `modelviewmatrix` to get the correct position.

**Vertex shader**

```
world_coordinate_ = gl_Vertex;

```

**Fragment shader**

```
vec3 direction = (world_coordinate_.xyz - cameraPosition_);
direction = normalize(direction);

for (float k = 0.0; k < steps; k += 1.0) {
....
pos += direction*delta_step;
float thisLum = texture3D(texture3_, pos).r;
if(thisLum > surface_)
...
}

```

Everything works as expected, what I now want is to sample the correct value to the depth buffer. The value that is now written to the depth buffer is the cube coordinate. But I want the value of `pos` in the 3d texture to be written.

So lets say the cube is placed `10` away from origin in `-z` and the size is `10*10*10`. My solution that does not work correctly is this:

```
pos *= 10;
pos.z += 10;
pos.z *= -1;

vec4 depth_vec = gl_ProjectionMatrix * vec4(pos.xyz, 1.0);
float depth = ((depth_vec.z / depth_vec.w) + 1.0) * 0.5;
gl_FragDepth = depth;

```

# Answer
> 3 votes
volumetric raycasting. I know something about that :).

But to you question: When you have sample in world space (your `pos`) you have to multiply it with View\*Projection matrix to have correct output of depth. View matrix contains linear basis of the camera and converts the world position to the camera space and then you do projection.

---

Using this depth with regular rendering pipeline is easy (if you are not able to write the depth into the depth buffer and use HW acceleration). Store world position in Vertex shader (using varying in gl i think). Than in PS perform viewProjection multiplication on this `worldPos`. Normalize (`pos /= pos.w`). And compare `pos.z` with the value in a depth texture. Thats it ;)

---
Tags: opengl, shaders, depth-buffer
---


# Question
Title: What are pros and cons of Voronoi shatter?
I have seen some Voronoi shatter videos on Youtube.

What is your experience with it?

What are the pros and cons in time complexity, resource complexity, implementation difficulty...?

Does it emulate how a real material would react?

# Answer
> 3 votes
As to the last question: It doesn't emulate most of real-world materials aside from very few exceptions, and these only for some specific choices of the Voronoi cell seeds. For example, toughened glass shatters like this, since the material is "pre-broken" into a loosely-held Voronoi-like structure in the process of manufacturing it.

On the other hand, state of the art particle systems don't usually emulate explosion dynamics, fluid flow in a waterfall or fog dispersion either ...

---
Tags: algorithm
---


# Question
Title: Normal vector of a face loaded from an FBX model during collision?
I'm loading a simple 6 sided cube from a UV-mapped FBX model and I'm using a BoundingBox to test for collisions. Once I determine there's a collision, I want to use the normal vector of the collided surface to correct the movement of whatever collided with the cube. I suppose this is a two-part question:

1) How can I determine which face of the cube was collided with during a collision?

2) How can I get the normal vector of that surface?

# Answer
The Xna.Framework.BoundingBox isn't designed to help provide that information, it simply is able to check for a collision of the cube as a unit.

Determining which side collided sounds simple but it can actually be complex. You might want to look into SAT (Separating axis therory/Test). The result of which axis and whether it is + or - the center of the cubeBox will help you deduce in which face the collision happened.

Another quick & dirty would be to create 6 boxes around your main box, then when a collision is registered with the main box, see which 'outsideBox' is also involved and calculate a normal based on that. This would have challenges though if penetration is deep. A version of this idea would be to make each face its own thin box so you always know which box (face) the collision is on. Again, deep penetration may challenge that.

Another idea would be to create a class which holds the bounding box and also creates Plane objects that coincide with the faces of the cube. Then you could use the built in Plane intersection tests to see which side the collision was coming from and use that plane's normal.
> 1 votes

---
Tags: xna, collision-detection
---


# Question
Title: How to find 2D grid cells swept by a moving circle?
I'm making a game based on a 2D grid, with some cells passable and some not. Dynamic objects can move continuously, independent of the grid, but need to collide with impassable cells.

I wrote an algorithm to trace a ray against the grid, that gives me all cells that ray intersects. However, actual object are not point-sized; I'm currently representing them as circles. But I can't figure out an effective algorithm to trace a moving circle. Here's a picture of what I need:

The numbers show in what order the circle collides with grid cells. Does anybody know the algorithm to find these collisions? Preferably in C#.

**Update** The circle *can* be bigger than a single grid cell.

# Answer
> 6 votes
I think your drawing is a little misleading because you choose to draw strokes from the point on the circle tangent to your moving direction. I can see that the collisions to your grid edges happends when the TOP and LEFT points of your circle touch an edge.

Let **C** be your center and *r* the radius so **P'** = **C** \+ (*r*,0) and **P"** = **C** \+ (0,r).

If **D** is your direction vector (the versor) you have two lines :

R' = **D** · *t* \+ **P'**,

R" = **D** · *t* \+ **P"**

You simple have to find the intersection of those lines with the lines of equation:

y = *i* and y = *i* that are the edges of your grid!

The solution are easy because you have to simply consider the x or the y component of R' and R". You will find the *t*s value for each insersection, and the points for thoose *t*s, simply sort those point by *t* and you are done.

I believe you can easily say what cell is hit if you know the intersection point.

This works if *r* \< 1 (the cell width and height).

It works also for the other cases simply doing some consideration about **P'** and **P"**. We choose TOP and LEFT because of direction, BOTTOM and RIGHT should be considered for opposite direction, you understand why.

Now look at this image:

The circle is bigger then a single cell and we suppose it is going the same direction as your drawing. P1 is the first point that will touch, P2 is the second, P3 is useless because is in the bottom half. What you need to do is to cast rays from P1 and P2 as we seen before and do the same for the vertical lines.

In general you will have other starting points along with the TOP and the LEFT ones from where shoot your rays, bigger your circle is, the more rays to cast.

To be honest some you can avoid to shoot all that rays doing some geometrical consideration, but that can make the things harder to understand.

# Answer
> 1 votes
If you want to use your ray-collision algorithm, you can choose eight points on each circle (at 45-degree increments, aligned with your square grid), and use the ray-collision between corresponding points (i.e., from the top of one circle to the top of the other). The union of all these ray-collisions is the entire set of cells intersected.

You could probably improve on this a little--for example by using the line segment from the center of one circle to the center of the other, but extended on either side by the radius of the circle, as well as the parallel line segments on either side at the extremities of the circles.

# Answer
> 1 votes
I'm not saying this is a perfect analogy, but you might think about Bresenham's line algorithm. A modification of this algorithm or one of its extensions might be helpful, especially if you couple it with some of the other posts and comments. Typically, this algorithm isn't concerned with ordering, but I would think that you'd be able to add that fairly trivially.

---
Tags: c#, collision-detection, algorithm, grid
---


title: Should I use procedural animation?

text:
# Question
Title: Should I use procedural animation?
I have started to make a fantasy 3d fps swordplay game and I want to add animations. I don't want to animate everything by hand because it would take a lot of time, so I decided to use procedural animation.

* I would certainly use IK (starting with simple reaching an object with hand ...).
* I also assume procedural generation of animations will make less animations to do by hand (I can blend animations ...).
* I want also to have a planner for animation which would simplify complex animations; those which can be split to a sequence - run and then jump, jump and then roll - or which are separable - legs running and torso swinging with sword -.

I want for example a character to chop a head of a big troll. If troll crouches character would just chop his head off, if it is standing he would climb on a troll. I know that I would have to describe the state ("troll is low", "troll is high", "chop troll head" ..) which would imply what regions animation will be in (if there is a gap between them character would jump), which would imply what places character can have some of legs and hands or would choose an predefined animation.

My main goal is simplicity of coding, but I want my game to be looking cool also. Is it worthy to use procedural animation or does it make more troubles that it solves? (there can be lot of twiddling ...)

I am using Blender Game Engine (therefore Python for scripting, and Bullet Physics).

# Answer
> 10 votes
In my opinion, using completely procedural animation, besides the math and physical complexity, is not a good idea. The problem with procedural generation is that it lacks an artistic intent.

For texture or terrain generation, this is not so much a problem because you can use custom rendering to stylize your data. But animation is a much more complex thing to process.

Now to answer your question, some people are using semi-automatic animation, mostly for all physical-related constraints. In the animation engine "Euphoria" ( http://www.naturalmotion.com/euphoria ), they use a ragdoll character, wich tries to stand, and react to any physical impulse it's given.

Then to make your character hit another one, or swing a sword or an axe, you could use a predefined animation made by an artist, and blend / modify it programatically to aim at this or that.

---
Tags: animation, random, bullet-physics, procedural, blender-game-engine
---


# Question
Title: What open-source 3d engine should I use to make a tiny 3d game (by myself)?
It can be non-open-source but must be free.

I've heard panda3d is good, what do you guys think?

# Answer
**In general**

eBusiness said that You don't have much experience with making games. Games are quite complex problems to solve and if You want to program them then You really need to know a lot; but if You will use some simple programs for making games like game builders (I recommend You more advanced builder, Blender Game Engine, in which You basically click things to get them done). You should really ask about some 3d game builder too or possibly ask for specific game builder like 3d rpg game builders.

Problem is that there are lot of concepts You may have not heard and You should know like :

* Finite State Machines
* Event Driven Programmming
* Boolean logic
* Analytical Geometry
* Matrices and vectors ...

I started to make things in BGE and it looks great. I used to do it in Quake engine but let it be because I wanted to have destroyable clothes. I can not tell You much about cons of BGE but what I heard it is very easy to use and from my little experience it is easy to make games in it.

**If You don't know much about programmming then perhaps Blender Game Engine**

Pros:

Cons:

* You have to set up Your game (In Quake You already have playable game and Quake's game logic)

To get started in BGE:

How You usually work in it:

1. You make 3d models with 3d scene
2. You specify their physic properties
3. You specify game logic (key up moves character 0.3 points in X axis, ...)
4. You press 'p' for simulation, You press ESC to go back to Blender
5. If You are not happy with it You go back and change things

Basically, follow some tutorial on Youtube and You will have a game soon. :) And after following simple tutorials You might want to learn how BGE works (how BGE's game loop works).

**If You know mathematics and some programming then perhaps Quake 1 engine**

It is very easy to set up, You can , but Quake can be hard if You want something advanced done like clothes and similar...

Pros:

Cons:

* If you want to get things done in Quake C You will have to in the end resort to analytical geometry, goniometry, reo

How You make game in it:

1. You set it up like here and get documentation from here
2. for levels, monsters ...

* in Your level editor (I reccomend simple Qoole) You make geometry
    * in level editor You also make entities (ladders, switches ...)
3. for game logic

* You modify .qc files. Classes of objects which are on a map correspond to functions You have in map, these functions are starting points of each entity.
    * You can modify behaviour of already made entities
    * You compile .qc files (You execute one program to do it all for You)
4. You run Quake to test it

**Alternatives**

* Unreal Development Kit
* Unity3D
* something like DarkBasic, they have lot of tutorials and You might get it somehow
> 3 votes

# Answer
There is plenty of free 3D engines, and Panda3D is a good one to my mind, but as you ask for informations about other 3D engines, I would suggest the following competitors on top of Panda3D:

The choice depends mostly of your feeling. You should try some tutorials for each one and read some threads on their community forums.
> 2 votes

# Answer
I think maybe you shouldn't write a 3D game at all.

I can only guess at how experienced a game developer you are, but everything I can learn about you make me believe that you are very green.

Setting up a 3D rendering environment in something like Blitz3D is very easy. (It's not free, but it's absolutely the easiest tool that I know.) Making something that looks good and works for a game is however a relatively big job.

So, stick to 2D for now.
> 1 votes

---
Tags: panda3d
---


title: How to store 2D tile-map

text:
# Question
Title: How to store 2D tile-map
I want to create a 2D map composed of small tiles, that should look like voxels (eg. this just from side).

I think I can make a structure like Voxel2D, that have int X, Y and some Color, and every Voxel2D is going to be 5x5 pixels (so multiply X and Y by 5 when drawing).

But now how should I store the whole map? In a 2D array like classic Tile-map, or is there any faster way?

# Answer
You wouldn't call it voxels when it's 2D, it's just tile based. Array storage should be what you are looking for.

Edit: I can't help wondering if there is more to your question than I read, and I don't really get why you choose a 3D game for explaining your idea. Do you just want to be sure that you are working in the right direction or is there something that you don't know how to implement?
> 3 votes

# Answer
You can also employ 2 arrays rather then one, with one as a map array containing "tiles" and one is a tile array containing predefined pixols(5x5 or less),when needed you can still modify this pixols but you have to make a new tile array rather then a predefined one.

The good thing about this is that the non modified ones can be predefined as image tiles until they are broken up.

Note however that worst case scenario is the same as having just one array full of pixols.
> 0 votes

---
Tags: 2d, java, maps, voxels
---


title: Level Creating Help

text:
# Question
Title: Level Creating Help
I am making a little 2d overhead RPG type game just for fun. I have almost all the basic stuff set up, but I just need a little help on level creation. I can already make a level and place each tile how I want it, but having to place each tile gets annoying after a while.

I noticed that in a lot of games, even extremely simple ones, they have LOTS of levels with LOTS of tiles in each. Creating all that in this fashion would take forever. So I guess my question is, as a game developer, am I supposed to do all that, or maybe make a little level editor so I can see things as I create it? What do game developers do? I'm using Java.

EDIT: Okay, say if I had an image for a map, that I made in MS paint or photoshop, and each pixel represent a tile value, could I somehow in Java detect what color an individual pixel is? If so, that would be perfect. If so, how?

# Answer
You want to use a map editor, such as Tiled.

EDIT: You can save it as an image if you really want, but that means you must have a rectangular map. What if you want an irregular one?

Also, you are then making it much harder to have an editor spit out the level code for you. I would advise against it, personally. Especially if your image is going to be many milions of pixels.
> 3 votes

# Answer
try tiled. it's a opensource level editor. and working with it is really simple. it's also opensource so you can easily implement your own file format for it. although many 2d game engines use tmx file format (it's an xml based format) and tiled have all tmx export options.
> 1 votes

---
Tags: 2d, java, tiles, rpg, levels
---


# Question
Title: Building dynamic bounding box hierachies
I've been reading about collision detection and I saw that the first part was a coarse detection which generates possible contacts using bounding box hierarchies.

I understand the concept of splitting up your objects in groups, to speed up the detection phase, but I'm a little confused on how do you actually build the hierachy, more so on what criteria is used to group them together.

Do I iterate through all the objects in the scene, and check the distance between them to see where they should be inserted in the tree?

Do you know some resources that may shed some light on this topic for me?

# Answer
With 50 independent cubes manuvering all around your 3d world, I might consider a 3 level oct tree. that splits your world up into 64 nodes (Axis Aligned Bounding boxes). Each frame you determine which of the 64 boxes each cube is in, then foreach cube, if there are more than one cube in that node, check each against the others in that node, else move onto next cube or frame.

How you build it? Create a bounding box that encompasses the entire world, determine the corner positions, determine points hallfway between each corner, build 8 smaller bounding boxes based on those 'halfway points'. then foreach of the 8 bounding boxes you just built, repeat: determine their corner positions, then determine points halfway between, then build 8 boxes within each box.

this would take approx 150 to 175 AABB to AABB checks each frame instead of the 1200 a brute force check would take.
> 3 votes

# Answer
A basic method is to use Binary Space Partitioning.
> 3 votes

# Answer
I think that the hierarchy that you want to know about is the called "scene graph".

The scene graph hierarchy has a lot of benefits, the majority of game engines use one. One of these benefits is the optimization of calculations. For example, collision detection ( the topic that you are asking ) and graphic culling to avoid send much information to the graphics card that is not visible.

The better form to know more about scene graphs is use one and see the features that have. For example, OpenSceneGraph or Ogre3D.

An overview:

A scene graph use basically the composition design pattern. A node can have more nodes, and the childs can have more nodes, ...

A node example:

```
class Node
{
   public:
        void addChild( Node* child );
        void removeFromParent();
        AABB calculateBoundingBox(); // Axis-aligned bounding box

   private:
       std::list< Node* >       m_children;
       vector3                  m_positionRelativeToParentNode;
       matrix4                  m_transformation;
};

```

Then, the construction that you're asking is composed when the scene is being created. I'm going to create a soccer player.

```
Node* player = new Node();
Node* torso = new Node();
Node* head = new Node();
Node* larm = new Node();
...

player->addChild( torso );
torso->addChild( head );
torso->addChild( larm );

...

```

Ok. The player is composed. With the transformation of each node, and the position relative to the parent node, the bounding box can be calculated.

If we calculate the AABB of the player, and we do a collision test with other player, then is when we descend to the children and the collision test is done with more precision. If the test is not passed at player level, the children tests are not necessary ( we are optimizing ).

How to calculate the bounding box? Think that each node has his own coordinate system. The relative position to the coordinate system of the parent is the member Node::m\_positionRelativeToParentNode, and the member Node::m\_transformation is the own transformation in his coordinate system. With this information, we can calculate the bounding box of a node. Remind that if we know test two nodes, they must "live" in the same coordinate system. Then we need compose the transformations and go up to a common parent and do the test in the common parent coordinate system.

Edited:

There is a really good book about collision detection called: "Real Time Collision Detection".
> 2 votes

---
Tags: collision-detection, bounding-boxes
---


# Question
Title: Implementing top view physics using box2D
How can top view physics games be done in box2D? One idea I have is to set the linear velocity of an object manually or to alter the linear and angular damping as my object moves over different surfaces. For example if my object is over a wet surface it'll have less linear damping and if it is over rough surface it'll have more damping. And to see if my object has fallen over an edge I'll try to use an `AABB` and check if its still inside or manually see if `object.x > boundary.x` etc. Is there any better way?

# Answer
> 5 votes
Look into b2FrictionJoint to simulate top-down "rough surfaces". Motion damping doesn't end up looking that realistic.

You can basically attach your objects to anything using a friction joint to get it to work. (I attach them all to a floor object, but it doesn't matter how big or where it is.)

# Answer
> 3 votes
If you simply set gravity to zero then the physics simulation works well for a top-down game.

# Answer
> 1 votes
Box2D is designed to work with two-dimensional space. On a 2D platformer game we could describe our objects with a basis XY:

```
--------- X
|
|
|
Y

```

In this game there is no depth, ok? If we want see this same game with a top view, our space need a third new dimension Z, to describe depth. What happens? Now we have three dimensions but Box2D is designed in two dimensions.

The game can be visually two-dimensional, but the logic is three-dimensional in this case. ( top-view ).

I think that will be better use another 3D physics library, or implement one yourself.

I never have seen a top view game using Box2D and I would be very grateful if someone knows one.

# Answer
> 0 votes
As jhocking said, its the same using Box2D for a side or top view.

Just disable gravity and play with depths using the colision filtering in the box2D manual.

because there will be no gravity force, the objects will be "lighter" than normal, when pushing them. Play with the masses and the forces to achieve equivalent results.

What you refered to as damping, should be the common friction in Box2D, i think. and as for checking limits of your levels, there are sensors. shapes that will tell you when something passes over :)

---
Tags: flash, box2d
---