title: How to make a registration for my game?

text:
# Question
Title: How to make a registration for my game?
Me and my (new) company want to sell a very simple game, but we want it so that only the person that buys it can play it.

I want to know if it's possible to make a "registration" window pop up when the game either first starts or when it is being installed (still haven't decided whether or not to use an installer or not). It would require the person to input a registration key and it would then check that key against a database to 1. check to see if it's actually there and 2. to see if it has not been used already. If both are true, it lets you install or play the game an infinite number of times on that computer up until it is uninstalled.

Is this possible in the c#/xna code, or would i have to use some advanced form of executable programming?

# Answer
> 9 votes
Your method sounds like it could be detrimental to paying customers. Rule #1 about DRM: `Never screw paying customers`. Sure, you may lose more copies to the pirates, but your paying customers will thank you.

That said, I'd look at either getting your game accepted to a platform like Steam or XBox Live that already does this user checking. Failing that, I would recommend maintaining a database on your own web server and require that users create an account and have to log in to play. There are additional security concerns when you are storing customers' private information though, so do some research *before* you get rainbow hacked.

The above methods will require an internet connection, but any client-side serial key mechanism you may conjure up can be cracked open by nearly any kiddie scripter. I would just steer clear of client-side serials if you were trying to follow rule #1.

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


title: Creating online game for android

text:
# Question
Title: Creating online game for android
What protocol is used to develop real time update games over the internet? From my research here is what I understood:

1. You cant make one device (phone) as server to host room, you need real server not sure why.
2. UDP have better performance but the data packet may get lost on the way
3. TCP HTTP is the easiest way (what I am familiar with) my question here should I use REST and call the server each second from the clients(phones) to update game status or is there a way where the server can update the client?

# Answer
> 1 votes
I can suggest you to read this tutorial : http://gafferongames.com/networking-for-game-programmers/ It explains differences between TCP and UDP and provides an implementation of a UDP-like protocol used in games (in c++).

# Answer
> 1 votes
First, don't try to reinvent the wheel. Take the idea of TCP or UDP and toss them out of the window. You will likely want to use HTTP with Android's standard URL calls.

As noted before, phones are a bad server. There isn't likely a case where X people are sitting around a table with phones connected to each other. They are likely in various places, doing various things. Phone signal strength varies greatly depending on a number of factors, but it is very likely that a phone will go to sleep or lose connection at some point.

What is the point of these real time updates? Real time on a mobile device is almost always bad. Real time requires almost a constant connection, which usually means a constant flow of network data, which eats up both network bandwidth limits and also will drain the phones battery. I suggest either using push notifications or polling at a reasonable rate (even better if this rate can be set by the user).

Android does support push notifications. These are useful to tell the phone that you have new updates, and then pull the appropriate data. This is where your REST server comes into play. The REST server gives you a central repository so that your game's data won't be lost. I commonly use two different android devices. Applications that sync my data between those devices are far more useful than those that do not.

# Answer
> 0 votes
It's very difficult to get reliable peer-to-peer communication over the internet. It's much easier to use a central server as a relay among the clients. UDP accepts unreliable communications in exchange for better real-time behavior. It's possible to use two way pipes to exchange data freely, without polling, but also possible to use polled HTTP requests (or other methods) to periodically keep clients up to date. The best choice depends on what the required performance characteristics are, the number of clients, and the amount of data that has to move.

---
Tags: android, online
---


# Question
Title: Build / Destroy function design & security checks
I'm working on a browser based strategy game. For the moment I'm working on the build/destroy functions and I have a couple of questions about this. The main question is do you have advice on how I can pass the buildingId and townId to the page where I call the build function? Any advices about the checking I should have in the build / destroy function?

# Answer
Since this is PHP, you can pass your buildingId and townId as GET data in the URL, i.e.:

```
build.php?building=39&town=204832

```

You can then access this with `$_GET["building"]` and `$_GET["town"]`, which would equal 39 and 204832 respectively in this case.

Your other option is submitting this as POST data (form data) and accessing it using `$_POST["building"]`. I don't know of a way in PHP to send POST data other than to have form fields on your page and submit that form (`<input type="hidden">` would come in handy here). The only advantage here is that your variables aren't exposed in the URL, but it is does not make anything more secure.

I am not a security expert, but don't trust any information your client gives you. There are a lot of security checks you might want to do and only you (as the game's designer) would know which ones need to be asked. Some likely examples:

* Does the town exist and belong to the user, or do they have permission to build there?
* Does the building they want to build even exist? Can they build it? Can they build it *there*? If it is a one-of-a-kind building, have they already built it?
* Is there already something built there? Is there room for it?

---

My ultimate advice would also be that **you should not use PHP at all**, and instead should create this game in *anything else*: Python webservice, ASP.NET, JavaServer Pages, take your pick. PHP is an incredibly bad language in all the ways a language can be bad. This is not me having a language bias and hating on a language like how some people hate C++ or Java. This is different. *PHP is actually just bad.*
> 1 votes

---
Tags: php, sql
---


title: How can I avoid "bleeding bullets"?

text:
# Question
Title: How can I avoid "bleeding bullets"?
I'm making a top-down shoot-em-up in XNA, and I have placeholder blocks for my characters and bullets. Here's a picture:

I have all the Bullets stored in a `List<Bullet>`, such that a Bullet is deleted whenever it collides with the window bounds. So I have a `List<Bullet>` called `bullets`, and I call `bullets.RemoveAt(i)` to delete a Bullet object.

However, if I keep on holding down `Space` to shoot Bullets, my "Mango Warfare" application starts "bleeding bullets," or bleeding memory. The app starts to climb up the memory rankings in Windows Task Manager:

Here's my code for removing out-of-window-bounds bullets:

```
private void CheckBulletCollisions()
{
    foreach (Bullet bullet in bullets)
    {
        if (bullet.X > GraphicsDevice.Viewport.Width ||
            bullet.X < -5 ||
            bullet.Y > GraphicsDevice.Viewport.Height ||
            bullet.Y < -10)
        {
            bullet.Enabled = false;
            continue;
        }
    }
}

private void RemoveDisabledBullets()
{
    int num_bullets = bullets.Count;
    int count = 0;
    int i = 0;
    while (count < num_bullets)
    {
        if (!bullets[i].Enabled)
        {
            bullets.RemoveAt(i);
            ++count;
            continue;
        }
        ++count;
        ++i;
    }
}

```

Clearly, `RemoveAt()` is not working. Is there anything else I can do to free up memory for out-of-window-bounds bullets?

# Answer
Don't use the task manager to do memory profiling. It doesn't mean what you think it means, especially for C# or other managed applications. ANTS Memory Profiler is a wonderful managed memory profiler that I've used repeatedly. It is not free, but it does have a trial. As Jonathan Dickinson points out in the comments, the CLR itself also exposes several performance counters you can view in perfmon.exe, including several related to .NET memory and garbage collection.

There is a very good chance there's nothing actually rooting your bullet objects once they are removed from that list and that, upon a subsequent collection of the appropriate garbage generation, the memory consumed by the objects will be reclaimed. Without seeing more of your code I can't be sure, but I think it's a safe bet.

However, you are doing something that is, if nothing else, *inefficient* and you could improve it:

You're removing items from a list, which implies you are allocating them and putting them in the list in the first place -- in other words you are allowing allocation to occur during your game loop, and this means you'll eventually cause garbage collection (and more to the point, possibly cause more frequent collection of higher GC generations). Further, you're removing items from the middle of the list (most of the time), which means every time you remove something, the following elements of the list must be copied.

Consider instead partitioning your list into two halves, an "active" and a "disabled" half. You will need an additional integer variable somewhere to track the index of the first disabled bullet in the list.

When your game starts, you preallocate some reasonable number of bullets in the list and set the "first disabled" index to 0 (because all bullets in the list are currently disabled). Whenever you need to "create" a new bullet you just set the properties of `bullets[firstDisabled]` to whatever values the new bullet should have:

```
bullets[firstDisabled].X = desiredX;
bullets[firstDisabled].Y = desiredY;
bullets[firstDisabled].Speed = 100;

// The bullet is now active:
++firstDisabled;

```

In your main update loop, you only process bullets from 0 to `firstDisabled`:

```
for (var bulletIndex = 0; bulletIndex < firstDisabled; ++bulletIndex) {
  // Update the bullet here.
}

```

To handle the case where a bullet has left the screen during the update loop, you don't remove it from the list. Instead you *swap* that bullet's data with the last *enabled* bullet's data (which is at `firstDisabled - 1` and decrement `firstDisabled`.

Obviously this technique implies two things: you have a fixed upper limit of live bullets and that the order of bullets in the list doesn't matter. The latter should not be a problem, however the former might be. Fortunately you can deal with this if you have to by adding a new bullet at the end of the list (not in the middle) and swapping that bullet's properties with the bullet at index `firstDisabled`. Then you increment `firstDisabled` -- much like how you handle "removing" a disabled bullet, really.

The end result is that you have a system that allows bullets to be activated and deactivated in linear time (your original method was more intensive) *and* has a fixed memory budget which can't leak *or* induce garbage collection during gameplay and is easily cleaned up post-gameplay by simply clearing the entire list (if need be).
> 11 votes

# Answer
2 Things. First, it could be some kind of garbage collection issue. Just because you are removing the Bullet from the List doesn't mean it or some part of it still doesn't exist in memory. I don't know enough about the specifics or how Bullet is implemented, but it could be the Bullet object is creating something (A Texture2d?) and not properly destroying it?

2nd, For the loop in your second code, you have two variables (count and i) that grow exactly the same. Just pointing that out. See Hackerworth's method in the other answer.

Hope this is helpful! -Woody
> 4 votes

# Answer
First, you don't need 2 indices *i* and *count*, one will suffice.

For clarity, I would rewrite the method:

```
private void RemoveDisabledBullets()
{
    int i = bullets.Count - 1;
    while (i >= 0)
    {
        if (!bullets[i].Enabled)
        {
            bullets.RemoveAt(i);
        }
        --i;
    }
}

```

Second, I have no reason to believe that RemoveAt(i) somehow doesn't work, it's a very basic method. Maybe there's a bug in your while loop, it's certainly convoluted enough to allow for that possibility, no offense, but if you call RemoveAt(i) and your program does not throw an exception, then the element at *i* has indeed been removed from that list.

If you are absolutely positive that the bullets are causing your memory leak, then the reason must be that your bullets are still being referenced somewhere else and are not getting garbage-collected.

Can you confirm that *bullets* is really the only active object that references bullets?

I haven't personally tried it, but have a look here to log whether or not the garbage collector has actually run.
> 2 votes

# Answer
Is continue even necessary? Not seeing how the program would get caught in that one line of the if statement.

I'm guessing RemoveDisabledBullet() is called in your Update method after the CheckBulletCollisions() method

maybe try a for loop. It's worked for me in the past.

```
for (int x = bullets.Count - 1; x >= 0; x--)
{
   if (!bullets[x].Enabled)
   {
      bullets.RemoveAt(x);
   }
}

```
> 1 votes

# Answer
I know this is like the third or so answer with this suggestion, but I would rewrite your for loop like this:

```
private void RemoveDisabledBullets()
{
    for (int i = 0; i < bullets.Count;)
    {
        if (!bullets[i].Enabled)
        {
            bullets.RemoveAt(i);
        }
        else
        {
            i++;
        }
    }
}

```

This makes sure that `count` gets evaluated for every step and that every bullet is actually checked to see if it is disabled. It's how I do it for my own bullets. :)
> 1 votes

# Answer
Is it possible that even tho removeAt() is removing the reference to the object that the operating system is not reporting it as free (and may not report it as free until it decides to claim it for another activity)?
> 0 votes

---
Tags: xna
---


# Question
Title: openGL managing images, VBOs and shaders
I'm working on a game where I use shaders with vertex attributes (so not immediate mode). I'm drawing lots of images and changing the width/height of the quads I use to draw them a lot. To optimize this it's probably a good idea to have one buffer but then one needs to update the complete buffer when one image changes (or only a part of the buffer using glBufferSubData...)

I was just wondering what kind of strategies you guys are using?

# Answer
One option may be to just use immediate mode with glVertexAttrib calls instead of the more traditional glTexCoord/glVertex/etc calls - you'll certainly avoid having to worry about how you manage VBOs here, and will still be able to get all the attribute goodness you need. Of course it is immediate mode, but if it works well enough then I say it works well enough.

Another way is to use a large VBO and glMapBufferRange \- ensure that you specify the GL\_MAP\_UNSYNCHRONIZED\_BIT option and append to the buffer each time you add a quad; when the buffer is full orphan it via GL\_INVALIDATE\_BUFFER\_BIT or glBufferData (... NULL ...). That's probably the most efficient way of handling this use case with a VBO.

See here for further info: http://www.opengl.org/wiki/Buffer\_Object\_Streaming

It's worth making a comparison with D3D here. The glMapBufferRange approach is an almost direct match for D3D's NO\_OVERWRITE/DISCARD pattern, which has been in use for well over a decade and is proven to work well for this kind of usage. That should assure you that it is going to be an optimized path and will be well supported.
> 1 votes

# Answer
> I'm drawing lots of images and changing the width/height of the quads I use to draw them a lot.

My suggestion would be to make a function for a single quad you want to render and batching the calls in a for loop.

I made a vertex attribute object for rendering sprites using the Sprite shader as a source for the attributes:

```
    // sprite batches

    m_SpriteBatchShader = ResourceManager::Get().GetShader("Sprite");
    m_SpriteBatchArray = m_SpriteBatchShader->CreateVertexArray();

    m_SpriteBatchPosition = m_SpriteBatchArray->GetAttribute("attrPosition")->GetArray<tb::Vec2>();
    m_SpriteBatchPosition->SetData(AccessMode::Host | AccessMode::Write, 4, NULL);

    m_SpriteBatchTexCoord = m_SpriteBatchArray->GetAttribute("attrTexCoord0")->GetArray<tb::Vec2>();
    m_SpriteBatchTexCoord->SetData(AccessMode::Host | AccessMode::Write, 4, NULL);
    tb::Vec2* dst_tex = m_SpriteBatchTexCoord->Lock(LockMode::Write);
    dst_tex[0] = tb::Vec2(0.f, 1.f);
    dst_tex[1] = tb::Vec2(1.f, 1.f);
    dst_tex[2] = tb::Vec2(1.f, 0.f);
    dst_tex[3] = tb::Vec2(0.f, 0.f);
    m_SpriteBatchTexCoord->Unlock();

```

I never have to change the texture coordinates for a sprite, because they're always going to be the same, filling the entire quad.

And now you can loop over the Sprites in a batch call:

```
m_SpriteBatchShader->Enable();
m_SpriteBatchShader->BindVertexAttributeArray(m_SpriteBatchArray);
m_SpriteBatchShader->SetMatrix(MatrixLocation::FullTransform, m_MatOrthographic);

for (size_t i = 0; i < a_SpriteBatch.size(); i++)
{
    Sprite* curr = a_SpriteBatch[i];

    const tb::Vec2& pivot = curr->GetPivot();
    const tb::Vec2& dim = curr->GetDimensions();

    tb::Vec2 pos_ul(-pivot.x,         -pivot.y        );
    tb::Vec2 pos_ur(-pivot.x + dim.x, -pivot.y        );
    tb::Vec2 pos_ll(-pivot.x        , -pivot.y + dim.y);
    tb::Vec2 pos_lr(-pivot.x + dim.x, -pivot.y + dim.y);

    // this Lock is a wrapper around glMapBuffer, which returns a pointer
    tb::Vec2* dst_pos = m_SpriteBatchPosition->Lock(LockMode::Write);

    dst_pos[0] = curr->GetTransform() * pos_ul;
    dst_pos[1] = curr->GetTransform() * pos_ur;
    dst_pos[2] = curr->GetTransform() * pos_lr;
    dst_pos[3] = curr->GetTransform() * pos_ll;

    // Unlock uploads data to the GPU
    m_SpriteBatchPosition->Unlock();

    // bind the sprite's texture to GL_TEXTURE0 and texDiffuse in the shader
    m_SpriteBatchShader->BindTexture(TextureLocation::Diffuse, 0, curr->GetTextureHandle());

    glDrawArrays(GL_QUADS, 0, 4);
}

m_SpriteBatchShader->Disable();

```

How can you optimize this further? Well, if your sprites don't need to be rotated, you can remove that transform. If they don't need a pivot, you can remove that as well. But if you *do* need those things, it may be beneficial to rotate the quad in the shader.
> -1 votes

---
Tags: opengl, shaders
---


title: OpenGL Blending GUI Textures

text:
# Question
Title: OpenGL Blending GUI Textures
I'm currently creating a menu for my project and I'm trying to get the textures to blend so I'm only left with the actual Image on the texture and not the background. The problem is the whole texture is somewhat transparent, it's not just removing the background.

My RGBA texture looks like

And the black background needs to be removed from the image.

I was using `GL_SRC_ALPHA`, `GL_ONE_MINUS_SRC`, `ALPHA` for my blend function but it wasn't blending anything. I changed to `GL_ONE`, `GL_ONE` and now I'm at where I am now.

You can see the text is there but its also transparent, but the background has been removed which is good.

This is how i'm drawing my button. The world behind it is drawn after (i've tried switching order didnt change anything) and it's drawn using VBO's whereas the Buttons are drawn in immediate mode.

```
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);[/left]
// get button pos
Point3<float> pos = button->getPos();
// get button dimensions
int width = button->getWidth();
int height = button->getHeight();
// bind button texture and draw quad
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, button->getState() ? button->getDownTex()-
>getTextureID() : button->getUpTex()->getTextureID());
glBegin(GL_QUADS);
glTexCoord2i(0, 1); glVertex3f(pos.x, pos.y, 0.0f);
glTexCoord2i(1, 1); glVertex3f(pos.x + width, pos.y, 0.0f);
glTexCoord2i(1, 0); glVertex3f(pos.x + width, pos.y + height, 0.0f);
glTexCoord2i(0, 0); glVertex3f(pos.x, pos.y + height, 0.0f);
glEnd();

```

I'm using sdl to load the texture

```
SDL_Surface* image = IMG_Load(textureName);
data.m_w = image->w;
data.m_h = image->h;
data.m_bitsPerPixel = image->format->BitsPerPixel;
data.m_alpha = image->format->alpha;
int colourMode = image->format->BytesPerPixel;
if (colourMode == 4)
   internalFormat = GL_RGBA;
if (colourMode == 3)
   internalFormat = GL_RGB;
if (colourMode == 1)
   internalFormat = GL_LUMINANCE;
if (SDL_BYTEORDER == SDL_LIL_ENDIAN)
{
if (colourMode == 4)
  format = GL_BGRA;
else
  format = GL_BGR;
}
else
{
if (colourMode == 4)
  format = GL_RGBA;
else
  format = GL_RGB;
}
GLuint texture = -1; // create texture handle
glGenTextures(1, &texture);    // gen texture
bindTexture(GL_TEXTURE_2D, texture);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexImage2D(GL_TEXTURE_2D, 0, internalFormat, image->w, image->h, 0, format,
GL_UNSIGNED_BYTE, image->pixels); // normal texture

```

# Answer
Take a look at this chart:

You're currently using `GL_ONE` with `GL_ONE`.

It looks like what you want is for the text to multiply with the background, so you get a blend where the green outline of the text modifies the color of the background. If you look at the chart, you can see that that is:

```
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

```

Coincidentally, this is the most common use for `glBlendFunc` (that I've seen).
> 7 votes

---
Tags: opengl
---


# Question
Title: Can the solar system be accurately represented in 3d space using doubles (or longs)?
I would like know to how to best manage coordinates in a 3D game whose aim is to realistically model the entire solar system, yet be able to handle the smallest movements in a "ship" (ie: perhaps we can consider 1cm to be the smallest acceptable movement for a frame). Do 64-bit doubles (or 64-bit longs) support this, or do we run into overflow problems? If not, then should longs or doubles be used, or if so, then which alternative approach do you think is the most sensible for modelling positions in the solar system in a 3D game? (ie: only holding a bit of the system in the display at a time based on distance to ship, or having the system somehow represented in a different co-ordinate space etc)

# Answer
There's already a good answer about integers, but I feel like floating-points shouldn't be eliminated. In his answer, Byte56 took the option to go for the maximum orbit of Pluto, probably taken from this excel sheet, so I'll stick to that.

That places the solar system boundaries at:

7,376,000,000 km = 7.376x10^9 km = 7.376x10^14 cm ≈ **7.4x10^14 cm**

The Double-Precision floating-point format offers a maximum precision of 15 significant decimals. So you're lucky: if your origin is at the Sun's center and you use a position around Pluto, you can represent *all* centimeters, e.g. in C++:

```
printf("%.0Lf\n", 7.4e14);
printf("%.0Lf\n", 7.4e14 + 1.0);
printf("%.0Lf\n", 7.4e14 + 2.0);

Output:
-------
740000000000000
740000000000001
740000000000002

```

**So if you can limit your game to the orbit of Pluto, then congratulations! You've got just enough precision with doubles to represent it.**

Beware though, that's enough to represent it in a *simulation*, but don't expect to *render* this painlessly. You'll have to convert to 32-bit floats, maybe change your origin so you get enough precision on the close objects, and you'll probably have to rely on some Z-buffer and camera frustum trickery to get all this to render properly.

**Now, if you want your astronauts to visit some far away comets in the Oort cloud, which is way bigger, then it's over.** Around 10^16 cm, you start loosing accuracy:

```
printf("%.0Lf\n", 1.0e16);
printf("%.0Lf\n", 1.0e16 + 1.0);
printf("%.0Lf\n", 1.0e16 + 2.0);

Output:
-------
10000000000000000
10000000000000000 <-- oops
10000000000000002

```

And it gets worse further on, of course.

So if you're in this case, you might want to try some more advanced solutions. I suggest you take a look at Peter Freeze's article in Game Programming Gems 4: "2.3 Solving Accuracy Problems in Large World Coordinates". IIRC, he suggest a system that might suit your needs, it's indeed some kind of multiple different co-ordinate spaces.

That's just some hints, you'll probably have to use some recipe of you own to get this running. Somebody that already implemented that kind of stuff might help you more. Why not firing an email to the guys behind Kerbal Space Program for instance?

Good luck with your game!
> 11 votes

# Answer
Assuming Pluto for the "edge" of the solar system (though some say it's as far as 3 light years out). Pluto, at it's maximum orbit is about 7,376,000,000 kilometers from the sun. That's 7.37600 × 10^14 centimeters. Double that to get the diameter and you'll get **1,475,200,000,000,000** centimeters. That's well within the maximum size of a 64 bit long. Since the height of the solar system is negligible compared to its diameter, we can ignore that.

So yes, you could use a long to represent your position in the solar system. In fact, you could have positions out as far as 9.75 light years with an signed long (double for unsigned).

Note that this is not the case for finding distances. The maximum distance you can find is the square root of the maximum distance you can travel to. This can be overcome by using a level of detail system for finding distances. You can do some simple checks to guess how far away the distances are (compare their x values and y values), then use 1,000,000 kilometer increments for large distances down to centimeter increments for small distances.

Of course there's the question of, do you really want to? 99.999% of the solar system is totally uninteresting empty space. If you're accurately representing the solar system, I sure hope you're not accurately representing the physics. It takes a long time to get around the solar system. Way too long for most people to stay interested.

And why even have such fine accuracy unless you're also going to model the objects in the solar system with that accuracy? That's where you'll get into trouble. The volume of the sun is 1.40900 × 10^18 cubic kilometers. On the cubic centimeter scale, using a single bit to represent that that space is "occupied" takes up 1.4 × 10^33 bits or 1.6 × 10^23 gigabytes. I think you don't have that much RAM.
> 17 votes

# Answer
You can use `BigInteger`, whatever your programming language calls it. It's an unlimited-sized integer; it scales well -- generally using `log(n)` storage for an integer of size `n`.

Java and C# have it; I'm sure other languages do. If not, you can decompile and reimplement it without too much hardship.
> 2 votes

---
Tags: 3d
---


title: Game Logic - Tree Based Game Design

text:
# Question
Title: Game Logic - Tree Based Game Design
I'm trying to write an easy to use and extremely modifiable game engine in C++. I was thinking about using a tree to store game data. All objects would inherit a from the Node class and would have parents and children. For example to access an object you could make a request the tree for `game.workspace.player` or `game.devices.controller`. I've seen this done in other games and it seems to work well.

Is this worth implementing? Would it affect the performance of my engine? -- I'm just looking for the best way to organize game data. Any critique or insight is greatly welcomed!

# Answer
> 6 votes
Build a game and not an engine. You're getting caught up in what you inevitably get caught up in when you're making an engine: you have no specific requirements and you have no idea what will be most useful or pleasant, or how it will impact using your engine or your game's performance. You also have no way to know.

Build a game, and the game will tell you what matters, it will tell you what your game engine requires and you will be able to see the performance impacts of what you're doing.

You'll actually have a game to play for it, too.

# Answer
> 3 votes
IF using C++ I would start with an existing solution that is feature full and fast. Such as openscenegraph

In general though I think most people would agree that a tree structured hierarchy is a good way to implement the things you refer to. Except for instancing. For this (Geometry, materials, etc) you would change the Tree into a DAG or Graph of nodes. This efficiency change will unfortunately mean rewriting a lot of your tree traversal code. So once again I would say start with a well supported and debugged intial framework.

---
Tags: architecture, data-structure, logic, methodology
---


# Question
Title: Algorithm for constructing the corners of a regular, n-sided polygon
I've googled this using a lot of keyword combinations, but to my great surprise I could not find an algorithm for constructing a regular, n-sided polygon into a given circle, i.e., finding the coordinates for the *n* corner points. All I could find were instructions how to do it by physical compass and straightedge, or interactive browser plug-ins without source.

So where could I find such an algorithm?

# Answer
> 16 votes
To build the list of the vertices of a regular, n-sided polygon inscribed into a given circle, pointy on the right sided. Where (xOffset,yOffset) is the center of the circle.

With `i` going from `0 to n-1` inclusive:

```
pointX[i] = ( cos( i / n * 2 * PI ) * radius ) + xOffset;
pointY[i] = ( sin( i / n * 2 * PI ) * radius ) + yOffset;

```

Edit: As Lars Viklund mentioned in the comments, this is only safe in languages like javascript in which integer division returns a floating point number rather than a integer. In other languages you should first cast `i` to a float.

---
Tags: algorithm, geometry
---


title: Design patterns in Game Physics

text:
# Question
Title: Design patterns in Game Physics
In the frames of a number crunching compatible programming language (say.. C++), what would be an elegant solution for adding self collision, external collision and integration step (Euler, etc.) updates to an object? (say the already abused mass spring system).

Say the object class is this one:

```
class DeformableObject
{
    public:
    DeformableObject();
    virtual ~DeformableObject();
    protected:
    vector <vec3<Real> > pos;
    vec3<real> fEval(int idx); // - the internal force due to ellasticity at the idx-th node
    friend class Integrator;
}

```

For example, in case of the integration method, I was thinking of having an abstract Integrator class and derive from it to add specific methods (Euler, Verlet, Midpoint, you name it).:

```
class Integrator
{
    public:
    Integrator();
    virtual ~Integrator();
    vec3<Real> Step(Real DTime, DeformableObject * dObject, int idx);
}

```

Now, since I'd like to switch or perhaps let different instances of the same deformable object use integration method A and the other use integration method B (for "benchmarking" purposes), is it safe to "think inside the box" and refer to either the **Bridge** or **Strategy** pattern? Which is more suitable and less ambiguous, especially performance-wise?

What about a self collision controller approach? Should I just add a self collision method to the `DeformableObject` class or "befriend" it with a Collider class? And what about external collisions, with different objects - how should that aspect be approached, at least at the conceptual level: considering the naive, brute pair-to-pair collision queries, if two objects collide, their points must be updated in the sense that velocities and forces are added to the points' own dynamic quantities (e.g. restitution forces, penalty forces, friction forces, reflected velocities, impulse conservation velocity changes, etc.). I know this is a broad topic, but I don't know which book does tackle these natural problems for a novice programmer. Thanks for your patience in reading this question!

# Answer
If you are looking for speed and elegance, consider a moving away from object-oriented design to a more data-oriented solution. There are several major performance problems with your design. The first Is the usage of a virtual destructor, (which is good for most object oriented design and C++ best practice, but an absolute performance killer on small objects). The second biggy is the use of an std:vector, (ie. dynamic memory allocator), in your deformable object. This kills cache coherency.

I would consider the following sources good jumping off points:

http://gamesfromwithin.com/data-oriented-design

http://solid-angle.blogspot.com.au/2010/02/musings-on-data-oriented-design.html

http://macton.smugmug.com/gallery/8936708\_T6zQX#593426709\_ZX4pZ (This ones a little more related to physics).

Anyway, if you come up with a nice Object-oriented design you are happy with, by all means use it. But remember that a data-oriented design will almost definetly beat it in performance.
> 3 votes

---
Tags: c++, software-engineering, design-patterns, physics-engine, numerical-methods
---


title: How to mix textures in DirectX?

text:
# Question
Title: How to mix textures in DirectX?
I am new to DirectX development and I am wondering if I am taking the wrong route to achieve the following:

I would like to mix three textures which contain transparent areas and some solid areas (Red, Blue, Green). The three textures should blend like shown in this example:

How can I achieve that in DirectX (preferably in directx9)?

A link or example code would be nice.

**Update:**

My rendering method looks like this and I still think I am doing it wrong, because the sprite only shows the last texture (nothing is rendered transparent or blended):

```
void D3DTester::render()
{
d3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0);
d3ddevice->BeginScene();

d3ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

LPD3DXSPRITE sprite=NULL;
HRESULT hres = D3DXCreateSprite(d3ddevice, &sprite);
if(hres != S_OK)
{
    throw std::exception();
}

sprite->Begin(D3DXSPRITE_ALPHABLEND);

std::vector<LPDIRECT3DTEXTURE9>::iterator it;
for ( it=textures.begin() ; it < textures.end(); it++ )
{
    sprite->Draw(*it, NULL, NULL, NULL, 0xFFFFFFFF);
}

sprite->End();

d3ddevice->EndScene();
d3ddevice->Present(NULL, NULL, NULL, NULL);
}

```

The resulting image looks like this:

But I need it to look like this instead:

**Update2:** I figured out that I have to `SetRenderState` after I use `sprite->Begin(D3DXSPRITE_ALPHABLEND);` thanks to the hint by Josh Petrie. However, by using this:

```
    sprite->Begin(D3DXSPRITE_ALPHABLEND);

d3ddevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

std::vector<LPDIRECT3DTEXTURE9>::iterator it;
for ( it=textures.begin() ; it < textures.end(); it++ )
{
    sprite->Draw(*it, NULL, NULL, NULL, 0xFFFFFFFF);
}
sprite->End();

```

The sprites colors are becoming transparent towards the background scene e.g.: if I use `d3ddevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,100,21), 1.0f, 0);` the result looks like:

Is there any way to avoid that? I would like the sprites be transparent to each other but to be still solid to the background.

**Update3:** After having sombody explained to me, how to do what @LaurentCouvidou and @JoshPetrie suggested, I have a working solution and therfore accept the answer:

```
d3ddevice->BeginScene();

D3DCOLOR white = D3DCOLOR_RGBA((UINT)255, (UINT)255, (UINT)255, 255);
D3DCOLOR black = D3DCOLOR_RGBA((UINT)0, (UINT)0, (UINT)0, 255);

sprite->Begin(D3DXSPRITE_ALPHABLEND);
sprite->Draw(pTextureRed, NULL, NULL, NULL, black);
sprite->Draw(pTextureGreen, NULL, NULL, NULL, black);
sprite->Draw(pTextureBlue, NULL, NULL, NULL, black);
sprite->End();

sprite->Begin(D3DXSPRITE_ALPHABLEND);
d3ddevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
d3ddevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
d3ddevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
d3ddevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
sprite->Draw(pTextureRed, NULL, NULL, NULL, white);
sprite->Draw(pTextureGreen, NULL, NULL, NULL, white);
sprite->Draw(pTextureBlue, NULL, NULL, NULL, white);
sprite->End();

d3ddevice->EndScene();
d3ddevice->Present(NULL, NULL, NULL, NULL);

```

*Update: since this question is rather popular, I'd like to point out a website where you can experiment with opengl blendmodes:*

# Answer
> 1 votes
The ID3DXSprite interface will modify the render states of the device when you call the `Begin` method. The specifics of the state modifications that will be performed are detailed in the method's documentation. In particular, note that the source and destination blend modes are set to 'source alpha' and 'inverse source alpha,' respectively. This enables the typical blending behavior wherein the alpha component of the color is used to control how transparent a pixel is.

Since this isn't what you want, you should pass the `D3DXSPRITE_DONOTMODIFY_RENDERSTATE` flag to `Begin` and ensure, as the documentation notes, that

> The device is assumed to be in a valid state to draw vertices containing `UsageIndex = 0` in the `D3DDECLUSAGE_POSITION`, `D3DDECLUSAGE_TEXCOORD`, and `D3DDECLUSAGE_COLOR` data.

By doing this, the render states you set up to blend the way you want will be preserved. You may note that doing this changes some other aspect of your render behavior, and that is probably due to your not setting other render states to the values described in the documentation for `Begin`.

As an aside, you shouldn't test `HRESULT` values against specific constants (like `S_OK`) if all you want to know is success or failure -- as is the case in your code. There are multiple success or failure codes. Prefer the SUCCEEDED or FAILED macro as appropriate.

# Answer
> 1 votes
This is known as *Additive Blending*.

In DirectX9, you use a few render states to set that up:

```
pDirect3DDevice9->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
pDirect3DDevice9->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE);
pDirect3DDevice9->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);

```

---
Tags: directx, textures
---


title: Cross Platform 2D Graphics Engines

text:
# Question
Title: Cross Platform 2D Graphics Engines
I'm looking for a 2D graphics engine that would allow me to release to Windows, Mac and the iPhone, much the way Unity does for 3D.

Is there a good engine that does this and is specific to 2D?

# Answer
There's always the old standby, SDL. It's fairly low level, but that simplicity is what allows it to be ported to bajillions of platforms (including windows, linux, mac, nintendo DS, wii, etc etc). There is an iPhone port, which I haven't used, but seems mature enough.
> 37 votes

# Answer
There really isn't any reason you can't use Unity3D to create "2D" games. You can use textured quads and an orthographic camera, and you have yourself a 2D game. There are even some unique solutions like using a skeletal animation system and putting sprites on top of different joints, or using a really tight perspective camera to get cheap parallaxing.

There are even middleware providers for Unity to provide better sprite management solutions. Like sprite manager 2.
> 22 votes

# Answer
SFML is a nice modern, Object-Oriented, cross platform graphics engine. It is hardware accelerated (based on OpenGL), and has bindings for

* C++
* C
* .Net (C#, VB.Net, C++/CLI, ...)
* Python
* D
* Ruby
* Ocaml
> 20 votes

# Answer
SDL, Allegro, OpenGL
SDL and Allegro are not only graphic libs, but whole game development libs.
One down side of SDL is that it takes over your main() and redefines it, making it hard to combine it with other libraries. (QT in my experience)
Another bad thing is that SDL only allows one window (this is stable version 1.2, the development version 1.3 does, but it's not fully supported or documented yet)
I can name SDL's weak points because I know it best and worked with it, but despite that, it's very powerful, many emulators, including a port of Mame and ScummVM, as well as games use it.
OpenGL, despite its popular 3D use, is a graphical library, and as such, also allows 2D graphics through surfaces pixel-level manipulation, and makes extensive use of hardware acceleration both in 3D and 2D.
> 12 votes

# Answer
You can look at Troll2D

Box2D is used for many platforms. Including the iPhone. But you'd have to find a way to display those objects. Since Box2D handles only 2D physics simulation.
> 6 votes

# Answer
LÖVE is a 2D engine that allows easy and fast development of games in the Lua language.

It runs on Mac (PPC and Intel), Windows and Linux (32 and 64bit) and games are easily distributed as one-file-runs-on-all-platforms ".love" files.

They are basically a zipped version of your game with the *zip* extension renamed to *love*.

Unfortunately, there is no iPhone port (so far).
> 5 votes

# Answer
Cocos2D originated under Mac/Windows in Python and is available in an Objective-C flavor under the iPhone. It's popular in 2D iPhone game development. Ray Wenderlich has some great Cocos2D tutorials for the iPhone.

Because they moved from Python to Objective-C, I suspect you're not going to be able to cross-compile between all platforms anymore from the same code base.
> 5 votes

# Answer
If you're not worried about iPhone there's always Flash packaged as AIR - you lose iPhone but you gain Linux and web deployment. You can then choose game/physics/rendering engines that suit your project, eg. FlashPunk, Flixel, Box2d.
> 4 votes

# Answer
You could try the Angel Engine. It's based on C++, OpenGL, Box2D, and it uses Python for scripting. It's mostly for prototyping, but the recent versions seem to focus on making full games.
> 4 votes

# Answer
torque2D supports PC and mac out of the box. The iTorque2D supports deployment to the iphone. Its also possible to get console deployment.
> 3 votes

# Answer
Moai SDK is a framework that can run\* on these platforms. It is open source so check out their github repo.

Moai can also be published to Google Chrome and Android.

\*I don't think publishing is to mac or windows (i.e. to a .app or .exe) is available at the moment but can be added.
> 2 votes

# Answer
PlayN supports HTML5, Android, iOS, Flash and desktop Java.

You write your code in Java and it handles converting your Java code to JavaScript (via GWT) for HTML, to ARM assembly (via IKVM to go from Java bytecode to CLR bytecode, then MonoTouch to compile CLR bytecode to a native iOS app), to ActionScript via a custom GWT backend that generates ActionScript instead of JavaScript, and to Android and desktop Java with no conversions.
> 2 votes

# Answer
Haxe + NME supports HTML5, Flash, Android, iOS, Blackberry, Windows, Mac, Linux, WebOS. It supports 2D graphics (bitmap sprites, vector drawing, plus effects like drop shadow and blur).
> 1 votes

# Answer
I've been hearing a lot about MonoTouch lately for people doing iPhone and iPod touch development. The Framework is on top of Mono, which is already cross platform compatible.
> 0 votes

# Answer
Unity3d is best 2d game development tools and engine. alternatively monogame. html5 and flash is not appropriate for this topic. already flash is dead.
> -1 votes

---
Tags: 2d, iphone, windows, cross-platform
---


# Question
Title: Create the right pom.xml for LWJGL and Slick Project (Maven)
Can somebody tell me whats wrong with my pom.xml file?

At this point I get this error if I start my \*.jar file:

```
C:\Users\Michael\git\freezing-robot\target>java -jar freezing-robot-0.0.1-SNAPSHOT.jar
java.lang.NoClassDefFoundError: org/newdawn/slick/BasicGame
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.newdawn.slick.BasicGame
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 13 more
Exception in thread "main"

```

And my pom file looks like this:

```
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>de.devnetik.freezing-robot</groupId>
    <artifactId>freezing-robot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>freezing-robot</name>
    <url>http://maven.apache.org</url>

    <properties>
        <package.name>de.devnetik.freezing_robot</package.name>
        <main.class>${package.name}.App</main.class>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <natives.version>0.0.6</natives.version>
        <lwjgl.version>2.8.2</lwjgl.version>
        <slick.version>274</slick.version>
    </properties>
    <repositories>
        <repository>
            <id>mavenNatives</id>
            <name>Maven Natives Repository</name>
            <url>http://mavennatives.googlecode.com/svn/repo</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>slick</id>
            <name>slick</name>
            <url>http://slick.cokeandcode.com/mavenrepo</url>
        </repository>
    </repositories>
    <build>
        <plugins>
            <plugin>
                <groupId>com.googlecode.mavennatives</groupId>
                <artifactId>maven-nativedependencies-plugin</artifactId>
                <version>${natives.version}</version>
                <executions>
                    <execution>
                        <id>unpacknatives</id>
                        <goals>
                            <goal>copy</goal>

                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>${main.class}</mainClass>
                            <packageName>${package.name}</packageName>
                            <addClasspath>true</addClasspath>
                            <classpathPrefix>lib/</classpathPrefix>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.lwjgl.lwjgl</groupId>
            <artifactId>lwjgl</artifactId>
            <version>${lwjgl.version}</version>
        </dependency>
        <dependency>
            <groupId>slick</groupId>
            <artifactId>slick</artifactId>
            <version>${slick.version}</version>
        </dependency>
    </dependencies>
</project>

```

If I try to start the application from eclipse through "play" ill get this error:

```
Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at org.lwjgl.Sys$1.run(Sys.java:73)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.lwjgl.Sys.doLoadLibrary(Sys.java:66)
    at org.lwjgl.Sys.loadLibrary(Sys.java:95)
    at org.lwjgl.Sys.<clinit>(Sys.java:112)
    at org.lwjgl.opengl.Display.<clinit>(Display.java:135)
    at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.newdawn.slick.AppGameContainer.<clinit>(AppGameContainer.java:36)
    at de.devnetik.freezing_robot.App.main(App.java:30)

```

And at least this is my project folder structure:

# Answer
> 3 votes
As the error says, there's no LWJGL in your java library path. See this answer for that.

For setting that up in Eclipse you want to add the `-Djava.library.path="your_path"` part into the VM arguments field found in the debug/build section in the project settings in eclipse. The `"your_path"` part should point to the native libraries for LWJGL (native to whatever system you're working on be it Windows, Mac or Linux).

---
Tags: java, lwjgl, slick
---


title: How to develop XBox 360 games?

text:
# Question
Title: How to develop XBox 360 games?
I understand that I can learn XNA as a hobbyist, but for top games like Fifa for example how are they witten?

# Answer
> 3 votes
in order to develop a game via physical media for a console (XBox360, PS3, Wii) you would need to contact the respective company (Xbox360-\>Microsoft, PS3-\>Sony, Wii-\>nintendo), and request/purchase a dev-kit (this is not a small request/purchase, and some of these companies may request that you formally pitch your game)

this dev-kit is in many cases a system that has some of the features either removed, modified, or added (in the case of addition this is for the ability to debug, and to easily get information from the system), and can also give rights to the user that are not given to a user of the actual system. in other cases the dev-kit is a software-library/emulator for testing the executable on.

few if any console developer(s) give these dev-kits to anyone who asks, and it requires a non-disclosure agreement (for anyone to work on the project).

if your more asking about language, and dev-environment that can be different from system to system, but is a fair question when you contact to request a dev-kit. as a side note: these dev-kits are usually per title, and need to be re-requested/re-purchased for each title.

# Answer
> 2 votes
This big companys just buy the Xbox 360 SDK from Microsoft. I think its a huge Library written in C++.

---
Tags: xna-4.0, xbox
---


# Question
Title: Managing lists of different types of entities  - is there a better way?
I am developing a 2D space game for mobile devices, but it gets realy complex and my solution is realy confusing and produces lots of repeated code segments.

I hava a world class in which i have multible lists of different object like:

```
List<Enemy> enemys;
List<Projectile> projectiles;
List<Collectable> collectables;
List<Asteroid> asteroids;
List<Effect> effects;
..

```

Each list gets updated by the world class. but thats not all.. Each enemy has a list of engines, and list of weaponlunchers which gets updated by the enemy. Now each engine adds some fire effects to the world list 'effects', and each weaponluncher adds projectiles to the world list 'projectiles'. All these classes have different parameter, so i need an extra update AND extra render function for each class.

At least they are all childs of 'GameObject' which provides them basic things like position, velocity and acceleration vectors, bounding Polygons and functions like applyForce and a finite state machine

Is there a better or more common way to do this? like one catch-all class which contains all possible parameters and methods for all different objects. (i think this would produce even more confusing code)

# Answer
> Is there a better or more common way to do this? like one catch-all class which contains all possible parameters and methods for all different objects.

Yes, it's called a architecture. Have a look here for details.

This would let just one list of entities in your world class:

```
List<Entity>

```

It's one example of Composition over inheritance.
> 5 votes

# Answer
Within the bounds of your original question one option would be to break out the lists into Actions instead of Types like what you have. For example, you'd have the `List<HasAI>` and one for `List<Collidable>` and when you create a new object it adds itself to whatever action list it needs, when the object is destroyed then it removes itself from those lists. An object can be on multiple lists.

Step two of that option is to refactor your classes from a hierarchy into one that uses Interfaces, so your HasAI type is a class that implements the IBrains interface as an example. Matching that the `List<HasAI>` only requires objects to have the IBrains interface.

That should help clean up some of the complexity.
> 3 votes

# Answer
I think what you need to do is abstract the rendering in to its own classes, I think one for player and one for enemy (or maybe just one for player, and then create an instance of it for player and enemy - not 100% sure of your game design.)

You could use a visitor pattern to let the renderer loop around the various objects and decide what to draw, that might be less complex.
> 2 votes

# Answer
Using a base class and relying on polymorphism is a very good idea. But there are some alternate approaches. There are two articles by Noel Llopis that are worth reading. I've been looking at Data Oriented Design lately and think it has some merit.

The articles are here and here. It may simplify your code a little bit more then polymorphism. But like anything YMMV, take a look and see if it fits in with what you are trying to achieve. Polymorphism uses inheritance and DOD uses aggregation both have pros and cons so choose your poison.
> 2 votes

# Answer
You can by utilizing OOP and especially polymorphism.

Basically, you have to create a base class, which all game entities inherit from. This base class, is as abstract as possible, it will contain things such as a Creation, Update and Perhaps a Destroy function.

Then you derive all your other game objects from this class. You will probably also need to add some sort of reflection into your code if your language does not support it, to do some more advanced things, but it's avoidable if you know how to structure your inheritance correctly.
> 1 votes

---
Tags: architecture
---


# Question
Title: 2d game with png sequences slowing on Unity3d
We are building a tower defence game,In which enemy movement is done through sprite sheets as well the tower rotation is also done through sprites...every tower and every enemy has its own script attached to it which controle its animation...but when enemies and towers are in greater ammount the games slows down..and become laggy on iphone and unity ..can anyone tell what is the problem with it...

# Answer
In a personal project of mine having a script working on every object in the game would slow the game down drastically. Thus creating a main object that controls multiple things should give a performance increase
> 1 votes

---
Tags: 2d, unity, spritesheet
---


# Question
Title: What is the best way to handle MouseEvents in AS3?
What is the best way to handle MouseEvents?

Should I add an event on each MovieClip I want to work with, or a general Event at a holder MovieClip (or even at the stage) with internal control from the function?

I generaly see people here at work using one Event for each MovieClip, but all linked to the same funcion that handles them in general, is that a good thing? "target" and "currentTarget" seem a bit weird to me at first, but I think I'm starting to get it.

# Answer
I recommend adding events to the MovieClips of interest and not a general handler on the stage that you then sort into different objects. The massive switch statement or whatever that you'd be writing would be annoying to maintain and not really gain you anything.

Indeed, I sometimes put in extra invisible Sprites solely for the purpose of managing which objects have event listeners applied. The reason is because sometimes mouse handlers get confused and behave oddly when you apply a mouse event listener to the child of another object with a mouse event listener; it's cleaner to deal with when all objects with event listeners are on completely separate branches of the display hierarchy.

For example, if I have a button attached to a MovieClip and I want both the button and MovieClip to receive separate mouse events, what I'll do is make an extra sprite and attack both the button and the MovieClip to that.

---

I want to add the caveat here that it's more efficient for processing if there is only one listener for each event on an object. This is kinda premature optimizations so I wouldn't stress over it too much, but if you have multiple functions that you want to happen in response to an event then it's better to have a single event listener that calls the multiple functions.

This is a slightly different situation than what you asked (a single listener on each of multiple objects vs. multiple listeners on one object) but it's related.
> 2 votes

# Answer
There's an official document from Adobe Optimizing Performance for the Flash Platform - Help - Adobe that says on page 37 that you should call addEventListener() only once:

> The code is simplified and much more optimized, with only one call to the addEventListener() method on the parent container. Listeners are no longer registered to the Apple instances, so there is no need to remove them when an apple is clicked

See pages 36 and 37 for a very good example.
> 2 votes

---
Tags: flash, actionscript-3, input, mouse
---


# Question
Title: Paddle will not *continue* to move, pong game, XNA
I'm making a pong game, and my paddles no longer continue to move after holding down the left thumbstick or dpad down. It simply moves once with each press. I think it is because I'm not checking for a LastKeyPressed anymore now that I've begun to use a new input class, which uses arrays to check for which controller is being uses, and that's not what I was using before.

**I've got to store the previous state, but I'm not sure of how to o that with these arrays.**

```
// From my input class:

  public Input()
    {
        // Get input state
        CurrentKeyboardState = new KeyboardState[MaxInputs];
        CurrentGamePadState = new GamePadState[MaxInputs];

        // Preserving last states to check for isKeyUp events
        LastKeyboardState = new KeyboardState[MaxInputs];
        LastGamePadState = new GamePadState[MaxInputs];
}

    /// <summary>
    /// Helper for checking if a button was newly pressed during this update.
    /// The controllingPlayer parameter specifies which player to read input for.
    /// If this is null, it will accept input from any player. When a button press
    /// is detected, the output playerIndex reports which player pressed it.
    /// </summary>
    public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex)
    {
        if (controllingPlayer.HasValue)
        {
            // Read input from the specified player.
            playerIndex = controllingPlayer.Value;

            var i = (int)playerIndex;

            return CurrentGamePadState[i].IsButtonDown(button) && LastGamePadState[i].IsButtonUp(button);
        }
        else
        {
            // Accept input from any player.
            return IsNewButtonPress(button, PlayerIndex.One, out playerIndex)
                    || IsNewButtonPress(button, PlayerIndex.Two, out playerIndex)
                    || IsNewButtonPress(button, PlayerIndex.Three, out playerIndex)
                    || IsNewButtonPress(button, PlayerIndex.Four, out playerIndex);
        }
    }

    // Tells the left paddle to move down
    public bool LeftDown(PlayerIndex? controllingPlayer)
    {
        PlayerIndex playerIndex;

        return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
    }

    // Tells the left paddle to move up
    public bool LeftUp(PlayerIndex? controllingPlayer)
    {
        PlayerIndex playerIndex;

        return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex)
               || IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex);
    }

// And now from my Gameplay class:

public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
........
input.Update();
            // Controls movement of the bats
            if (rightBat.GetType() != typeof(AIBat))
            {
                if (input.LeftDown(ControllingPlayer))
                {
                    leftBat.MoveDown();
                }
                else if (input.LeftUp(ControllingPlayer))
                {
                    leftBat.MoveUp();
                }

                if (input.RightDown(ControllingPlayer))
                {
                    rightBat.MoveDown();
                }
                else if (input.RightUp(ControllingPlayer))
                {
                    rightBat.MoveUp();
                }

// From my bat class, so that you see what the MoveUp and MoveDown functions do:

    public Vector2 GetPosition()
    {
        return position;
    }

    public void MoveUp()
    {
        SetPosition(position + new Vector2(0, -moveSpeed));
    }

    public void MoveDown()
    {
        SetPosition(position + new Vector2(0, moveSpeed));
    }

```

# Answer
> 2 votes
First I see a naming issue: You're using a method named LeftDown to check if the down arrow key is currently pressed. You might want to rename it to IsLeftPlayerGoingDown or something less ambiguous like that. At first glance, I thought "LeftDown" meant it checked whether the left arrow key was down.

Now, your LeftDown / IsLeftPlayerGoingDown method checks if there was a new key or button press (during the last frame). You should just check whether it's *currently* down, not if it has just been pressed. So your code would be something like:

```
public bool LeftDown(PlayerIndex? controllingPlayer)
{
    PlayerIndex playerIndex;

    return IsKeyPressed(Keys.Down, controllingPlayer, out playerIndex)
           || IsButtonPressed(Buttons.DPadDown, controllingPlayer, out playerIndex)
           || IsButtonPressed(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex);
}

```

And you'll have to define IsKeyPressed and IsButtonPressed to check against your Current{something}State (something being Keyboard or GamePad), ignoring the Last{something}State.

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


title: JointDef Modify at Runtime

text:
# Question
Title: JointDef Modify at Runtime
In my game, I want run time modification in object body so I want to modify the joint def according to situation. So provide comment for how to modify jointdef run time.

# Answer
There is no reason to do that unless you plan to reuse it. JointDef doesn't really do anything, as the name suggests, it is only a definition and even though you can change the fields, the Joint that was created using the JointDef will not change, as you probably discovered.

What you want to do is store a reference to the Joint that is created using the JointDef and then manipulate the Joint itself.

What exactly are you trying to accomplish? Specifying the problem better will help us provide you with a better answer.
> 1 votes

---
Tags: box2d, andengine
---


title: Reading the memory of a N64

text:
# Question
Title: Reading the memory of a N64
I'm looking for a way to read the memory of a N64, while the game is running, in real time.

I have a c# program which hooks into the memory of a running emulator and tracks SSB64 stats. I want to do the same thing with the physical N64. Currently it is possible to read the memory with a gameshark pro, however it's extremely slow, buggy, and not practical for what I am trying to accomplish.

Would it be possible to tap into the gameshark, or the N64 directly, to access the memory in real time?

Thanks!

# Answer
> 2 votes
Yes you could but you would need to actively sniff the data and address bus on the cartridge with some dedicated hardware and have it spit it somewhere.. I know the arduino mega has a fair amount of digital I/O but i don't think the software serial would be fast enough especially if you wanted it to chuck data both ways.

Another way would be to piggyback the memory (literally). I fiddled with something a couple of years back with the memory expansion pack with a similar target in mind but gave up due to time.

Good luck Your gonna need it

---
Tags: nintendo
---


# Question
Title: How do I create a wide-angle / fisheye lens with HLSL?
What are the concepts that need to be implemented in order to achieve the effect of a wide angle lens of varying extremities?

Pseudocode and specific explanation referring to the various stages of the content pipeline, as well as what information needs to be passed in from the source code to HLSL would be very useful.

Also, what are the differences between implementing a wide-angle lens, and a fisheye?

# Answer
A wide-angle lens should not behave differently than other regular lens models. They just have a larger FOV (in the `D3DXMatrixPerspectiveFovLH` sense -- I'm assuming you use DirectX), or larger left/right and bottom/top values (in the OpenGL `glFrustum` sense).

I believe the really interesting part lies in modeling the fisheye lens. There's Fisheye Quake that you can study, it comes with source.

## The true fisheye projection

The projection of a fisheye lens, however, is highly non-linear. In the more common (to my knowledge, which is limited to surveillance cameras) kind of lens, a point `M` in space is projected onto the surface of a unit hemisphere, then that surface undergoes a parallel projection onto the unit disc:

```
           M
             x                 M: world position
              \                M': projection of M on the unit hemisphere
               \  ______       M": projection of M' on the unit disc (= the screen)
             M'_x'      `-.
             ,' |\         `.
            /   | \          \
           /    |  \          \
          |     |   \          |
__________|_____|____\_________|_________
                M"    O        1

```

There are other fisheye mappings that may give more interesting effects. It's up to you.

I can see two ways to implement the fisheye effect in HLSL.

## Method 1: perform the projection on the vertex shader

**Advantage**: almost nothing needs to be changed in the code. The fragment shader is extremely simple. Rather than:

```
...
float4 screenPoint = mul(worldPoint, worldViewProjMatrix);
...

```

You do something like this (can probably be simplified a lot):

```
...
// This is optional, but it computes the z coordinate we will
// need later for Z sorting.
float4 out_Point = mul(in_Point, worldViewProjMatrix);

// This retrieves the world position so that we can project on
// the hemisphere. Normalise this vector and you get M'
float4 tmpPoint = mul(in_Point, worldViewMatrix);

// This computes the xy coordinates of M", which happen to
// be the same as M'.
out_Point.xy = tmpPoint.xy / length(tmpPoint.xyz);
...

```

**Drawbacks**: since the whole rendering pipeline was thought for linear transformations, the resulting projection is exact for vertices, but all the varyings will be wrong, as well as texture coordinates, and triangles will still appear as triangles even though they should appear distorted.

**Workarounds**: it could be acceptable to get a better approximation by sending a refined geometry to the GPU, with more triangle subdivisions. This might also be performed in a geometry shader, but since this step happens after the vertex shader, the geometry shader would be quite complex because it would have to perform its own additional projections.

## Method 2: perform the projection on the fragment shader

Another method would be to render the scene using a wide angle projection, then distort the image to achieve a fisheye effect using a fullscreen fragment shader.

If point `M` has coordinates `(x,y)` in the fisheye screen, it means it had coordinates `(x,y,z)` on the hemisphere surface, with `z = sqrt(1-x*x-y*y)`. Which means it had coordinates `(ax,ay)` in our scene rendered with a FOV of `theta` such that `a = 1/(z*tan(theta/2))`. (Not 100% sure about my maths here, I will check again tonight).

The fragment shader would therefore be something like this:

```
void main(in float4 in_Point : POSITION,
          uniform float u_Theta,
          uniform sampler2D u_RenderBuffer,
          out float4 out_FragColor : COLOR)
{
    z = sqrt(1.0 - in_Point.x * in_Point.x - in_Point.y * in_Point.y);
    float a = 1.0 / (z * tan(u_Theta * 0.5));
    out_FragColor = tex2D(u_RenderBuffer, (in_Point.xy - 0.5) * 2.0 * a);
}

```

**Advantage**: you get a perfect projection with no distortions apart from those due to the pixel accuracy.

**Drawback**: you cannot physically view the whole scene, since the FOV cannot reach 180 degrees. Also, the larger the FOV, the worse the precision in the center of the image... which is precisely where you want maximum precision.

**Workarounds**: the loss of precision can be improved by performing several rendering passes, for instance 5, and do the projection in the manner of a cube map. Another very simple workaround is to simply crop the final image to the desired FOV -- even if the lens itself has a 180-degree FOV, you may wish to render only a part of it. This is called "full-frame" fisheye (which is kinda ironic, since it gives the impression that you get the "full" something while it actually crops the image).

(Note: if you found this useful but not clear enough, please tell me, I feel like writing a more detailed article about this).
> 38 votes

# Answer
It should be `z = sqrt(1.0 - in_Point.x * in_Point.x - in_Point.y * in_Point.y)`, right?

My GLSL implementation is:

```
#ifdef GL_ES
precision mediump float;
#endif

varying vec2 v_texCoord;
uniform sampler2D u_texture;
uniform float fovTheta; // FOV's theta

// fisheye
void main (void)
{
    vec2 uv = v_texCoord - 0.5;
    float z = sqrt(1.0 - uv.x * uv.x - uv.y * uv.y);
    float a = 1.0 / (z * tan(fovTheta * 0.5));
//  float a = (z * tan(fovTheta * 0.5)) / 1.0; // reverse lens
    gl_FragColor = texture2D(u_texture, (uv* a) + 0.5);
}

```
> 3 votes

---
Tags: graphics-programming, hlsl
---


title: XNA server client model

text:
# Question
Title: XNA server client model
Hi what is the best model for creating client server application in one solution in xna, client as xna application, server as console and model as reference added to client and server? or maybe one xna application with global variable isHost passed from separate client/ server application running this xna application, or mayby different?

# Answer
> 1 votes
Add multiple projects to your solution in Visual Studio. One will be the XNA game, and one will be a console application or class library that will be referenced by the XNA game project.

Also, here is a sample of how to make a client/server architecture.

---
Tags: xna, client-server
---


title: Minesweeper: Mouse listener problem

text:
# Question
Title: Minesweeper: Mouse listener problem
I have wrote a code for game **Minesweeper** and there is no problem with the graphics,but there is some problems with **MouseListener**. Here is my code

---

```
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mines_v3.pkg0;

import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
/**
 *
 * @author Gevorg Hindoyan
 * @version 3.0
 * @since 2012
 */
public class Mines_v30 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                MineFrame frame = new MineFrame();
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }
}

class MineFrame extends JFrame {
    private int xq = 10;
    private int yq = 10;
    private int minq = 10;
    public MineFrame() {

        setSize((xq+1)*22-1, (yq+2)*22+44);
        setTitle("Mines v.3.0");

        Image ic = Toolkit.getDefaultToolkit().getImage("images/icon.png");

        setIconImage(ic);

        mainFields mf = new mainFields(xq,yq,minq);

        add(mf);
    }
}

class mainFields extends JComponent implements MouseListener{
    private int xq;
    private int yq;
    private int minq;
    private boolean loose;
    private int width;
    private int height;
    private boolean win() {
        int smq = 0;
        for(int i=1;i<=xq;i++) {
            for(int j=1;j<=yq;j++) {
                if(a[i][j]==-5 && b[i][j]==2) smq++;
            }
        }
        if(smq==minq) return true;
        return false;
    }
    private int a[][] = new int[100][100];
    private int b[][] = new int[100][100];
    private void init() {

        loose=false;
        // making all fields "0"
        for(int i=1;i<=xq;i++) {
            for(int j=1;j<=yq;j++) {
                a[i][j]=0;
                b[i][j]=0;
            }
        }

        //filing borders with -3
        for(int i=0;i<=xq+1;i++) {
            a[0][i]=-3;
            a[yq+1][i]=-3;
        }
        for(int i=0;i<=yq+1;i++) {
            a[i][0]=-3;
            a[i][yq+1]=-3;
        }

        //adding mines
        Random rand = new Random();
        int nx=0,ny=0;
        for(int i=0;i<minq;i++) {
            int
            x = rand.nextInt()%xq+1,
            y = rand.nextInt()%yq+1;
            if(x==0 || y==0) {
                i--;
                continue;
            }
            if(x<0) x*=-1;
            if(y<0) y*=-1;

            if(i==0) {
                nx = x;
                ny = y;
            } else if(nx==x && ny==y) {
                i--;
                continue;
            }

            a[x][y]=-5;

        }

        //filling with numbers
        for(int i=1;i<=xq;i++) {
            for(int j=1;j<=yq;j++) {
                if(a[i][j]==-5) {
                    if(a[i-1][j]>=0) a[i-1][j]++;
                    if(a[i+1][j]>=0) a[i+1][j]++;
                    if(a[i][j+1]>=0) a[i][j+1]++;
                    if(a[i][j-1]>=0) a[i][j-1]++;
                    if(a[i+1][j+1]>=0) a[i+1][j+1]++;
                    if(a[i+1][j-1]>=0) a[i+1][j-1]++;
                    if(a[i-1][j+1]>=0) a[i-1][j+1]++;
                    if(a[i-1][j-1]>=0) a[i-1][j-1]++;
                }
            }
        }

        /*DEBUG: printing matrix*/
        for(int i=0;i<=xq+1;i++) {
            for(int j=0;j<=yq+1;j++) {
                if(a[i][j]<0)
                    System.out.print(a[i][j]+" ");
                else
                    System.out.print(" "+a[i][j]+" ");
            }
            System.out.println();
        }
        /* DEBUG */
    }
    public mainFields(int xq1,int yq1,int mq1) {

        xq=xq1;
        yq=yq1;
        minq=mq1;
        width = (xq+1)*22-1;
        height = (yq+2)*22+44;
        init();

    }

    @Override
    public void paintComponent(Graphics g) {

        //status bar & all fields
        Image smile = null;
        String smile_name = "images/smile";
        if(loose) smile_name+="2";
        else if(win()) smile_name+="3";
        else smile_name+="1";
        smile_name+=".png";
        try {
            smile = ImageIO.read(new File(smile_name));
        } catch(IOException e ) {
            e.printStackTrace();
        }
        g.drawImage(smile, width/2-21,
                    0,
                    smile.getWidth(null),
                    smile.getHeight(null),
                    null);
        for(int i=1;i<=xq;i++) {
            for(int j=1;j<=yq;j++) {
                Image field = null;
                String fname = null;
                if(b[i][j]==0) {
                    fname = "datark";
                }
                else if(b[i][j]==2 && !loose) {
                    fname = "drosh";
                }
                else if(b[i][j]==2 && loose && a[i][j]!=-5) {
                    fname = "sxal_drosh";
                }
                else if(b[i][j]==1) {
                    if(a[i][j]==0) {
                        fname = "sxmats";
                    }
                    if(a[i][j]==1) {
                        fname = "mek";
                    }
                    if(a[i][j]==2) {
                        fname = "erku";
                    }
                    if(a[i][j]==3) {
                        fname = "ereq";
                    }
                    if(a[i][j]==4) {
                        fname = "chors";
                    }
                    if(a[i][j]==5) {
                        fname = "hing";
                    }
                    if(a[i][j]==6) {
                        fname = "vec";
                    }
                    if(a[i][j]==7) {
                        fname = "yot";
                    }
                    if(a[i][j]==8) {
                        fname = "ut";
                    }
                }
                fname+=".png";
                try {
                    field = ImageIO.read(new File("images/"+fname));
                } catch(IOException e) {
                    System.err.println("Error 1: can't find images");
                }
                g.drawImage(field,
                            (i-1)*22,
                            (j-1)*22+42,
                            null);
            }
        }
    }

    @Override
    public void mousePressed(MouseEvent me) {

    }

    @Override
    public void mouseReleased(MouseEvent me) {

    }

    @Override
    public void mouseEntered(MouseEvent me) {

    }

    @Override
    public void mouseExited(MouseEvent me) {

    }

    private void click(int i, int j) {

        b[i][j]=1;
        System.out.println("click() was called");
        repaint();

    }

    @Override
    public void mouseClicked(MouseEvent me) {
        int x = me.getX(),
            y = me.getY();

        int xrd = (int)x/22+1,
            yrd = (int)(y-42)/22+1;

        int but = me.getButton();

        System.out.println("Mouse clicked");

        if(but == MouseEvent.BUTTON1) {

            if(b[xrd][yrd]==1 || b[xrd][yrd]==2) {
                return;
            }
            click(xrd,yrd);
            repaint();
            this.repaint();

        }

        if(but == MouseEvent.BUTTON3) {

            if(b[xrd][yrd]==2) {
                b[xrd][yrd]=0;
            } else if(b[xrd][yrd]==0) {
                b[xrd][yrd]=2;
            }
            repaint();

        }
    }

}

```

---

# EDIT

My function `click()` is not finished
And matrix `b[][]` is showing is that field is clicked matrix `a[][]` is showing is that filed mine(-5) or number(0,1,2,3,4,5,6,7,8)

The issue, as mentioned in chat, is that a click handler wasn't getting fired.

# Answer
You are probably forgetting to hook up your listener.
> 5 votes

# Answer
You forgot to put addMouseListener(this); to your frame/panel
> 4 votes

---
Tags: java, graphics, mouse, minesweeper
---


# Question
Title: in box2d how to decrease joint's reaction force?
I'm trying to make a game like **cut the rope** and meet some problems.
when I create a float bubble and connect with a rope(a sets of bodies connected with revoluteJoint), the rope will become longer and when I destroy the bubble,rope gives a a big reaction force to candy, so how to decrease this reaction force?
to simulate bubble's floating, I did this

```
class Bubble extends PhyObject
{
     override function draw():void{
         if(this.combined){
            this.getBody().SetLinearVelocity(velocity);//velocity=new b2Vec2(0,-3.5);
         }
     }
     //other code
}
class Main{
    public function loop(){
        getAllPhyObject().forEach(function(phyObj){
              phyobj.draw();
        });
    }

}

```

so if bubble was combined with candy ,It "float".
I think maybe I can do this
pseudo code:

```
if(bubble is connected with rope)
{
    //dynamic adjust bubble's linear velocity with rope's reaction force
}

```

but I just cannot figure out how to dynamic adjust bubble's linear velocity.and is there a simpler way to solve this problem?
thanks!
**update** finally I solved my problem,so I write it down and hope it help to you. below code is grab from b2BuoyancyController and it works in my case.

```
    //buoyancy
    private function float():void {
        if (bodies.length < 1)
            return;
        var body:b2Body = bodies[0];
        if(body.IsAwake() == false){
            //Buoyancy force is just a function of position,
            //so unlike most forces, it is safe to ignore sleeping bodes
            return;
        }
        var normal:b2Vec2 = new b2Vec2(0, -1);
        var offset:Number = 20;
        var density:Number = 2;
        var velocity:b2Vec2 = new b2Vec2(0, 0);
        var linearDrag:Number = 2;
        var angularDrag:Number = 1;
        var gravity:b2Vec2 = toolkit.world.GetGravity().Copy();
        var areac:b2Vec2 = new b2Vec2();
        var massc:b2Vec2 = new b2Vec2();
        var area:Number = 0.0;
        var mass:Number = 0.0;
        for(var fixture:b2Fixture=body.GetFixtureList();fixture;fixture=fixture.GetNext()){
            var sc:b2Vec2 = new b2Vec2();
            var sarea:Number = fixture.GetShape().ComputeSubmergedArea(normal, offset, body.GetTransform(), sc);
            area += sarea;
            areac.x += sarea * sc.x;
            areac.y += sarea * sc.y;
            var shapeDensity:Number = 1;
            mass += sarea*shapeDensity;
            massc.x += sarea * sc.x * shapeDensity;
            massc.y += sarea * sc.y * shapeDensity;
        }
        areac.x/=area;
        areac.y/=area;
        massc.x/=mass;
        massc.y/=mass;
        if(area<Number.MIN_VALUE)
            return;
        //Buoyancy
        var buoyancyForce:b2Vec2 = gravity.GetNegative();
        buoyancyForce.Multiply(density*area)
        body.ApplyForce(buoyancyForce,massc);
        //Linear drag
        var dragForce:b2Vec2 = body.GetLinearVelocityFromWorldPoint(areac);
        dragForce.Subtract(velocity);
        dragForce.Multiply(-linearDrag*area);
        body.ApplyForce(dragForce, areac);

        //tmpForce
        if(candy.bodies.length>0){ //TODO 你妹!!!!!
            var tmpForce:b2Vec2 = candy.bodies[0].GetLinearVelocity();
            body.SetLinearVelocity(tmpForce);
            //tmpForce.x = 0;
            //tmpForce.Subtract(velocity);
            //tmpForce.Multiply(-linearDrag*area);
            body.ApplyForce(tmpForce, areac);
        }
        //Angular drag
        //TODO: Something that makes more physical sense?
        body.ApplyTorque(-body.GetInertia()/body.GetMass()*area*body.GetAngularVelocity()*angularDrag)
    }

```

tips:use force instated of impulse and changing linear velocity.

# Answer
> 0 votes
There is a limit in box2D configuration file, but the main problem is with how you implemented bubble. The rope length should always be a less than a value, meaning it shouldn't become longer to give that big reaction in the first place.

---
Tags: box2d
---


title: Platforms collide-able on one side only

text:
# Question
Title: Platforms collide-able on one side only
I have frequently tried to make some sort of a platformer, but when I actually code it, I run into a bit of a snag. How would I be able to make platforms in the air stop objects if they hit the sides or bottom, but allow them to sit on top of them?

I have tried many different methods, and some work slightly, but have many bugs, or some don't even work at all. Like this one I tried made it so that if you hit the side of the platform at the right angle, it forced you up on top of it.

# Answer
Without knowing much about how your code works it's hard to give an exact answer, but something like this should work:

```
if (collision(platform) && pos.y - height - vel.y < platform.y && vel.y > 0) {
    // Player collides, was over the platform the last update and is falling
    vel.y = 0;                      // Stop player
    pos.y = platform.y - height;    // Position player on platform
    onGround = true;
}

```

If the registration point of the player is centered you would use height/2 instead of height, and you might have to take the platforms height into account as well if it's registration point isn't at the top.
> 2 votes

---
Tags: xna, c#, platformer
---


# Question
Title: Issue with removing sprites on collision
I'm trying to make a very simple collision detection procedure just for test purposes.
The problem is with the send/receive information between functions

I have these lines on the `update` method (could be later implemented for checking what kind of subclass `node` is)

```
CCSprite *sprite = [background spriteCollisionWithRect:player.boundingBox];
if (sprite!=nil) {
    [sprite removeFromParentAndCleanup:YES];
}

```

and this is the `spriteCollisionWithRect` method

```
-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
    for (CCSprite *sprite in _spritesArray) {
        if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
            return sprite;
        }
    }
    return nil;
}

```

Now, this way not all the sprites are removed. It only works occasionally. But if I **remove** the node inside the collision method instead of **returning** it, it works nicely.

```
-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
    for (CCSprite *sprite in _spritesArray) {
        if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
            [sprite removeFromParentAndCleanup:YES];
        }
    }
    return nil;
}

```

Why is this?

# Answer
> 0 votes
using an array to store the sprites to check for collision, means that if i remove some sprite, i certainly should update that array!! now i'm checking for collision always on the same sprite, even if it's removed from it's parent..

so the easiest way to fix the problem is as follows

```
-(CCSprite*)spriteCollisionWithRect:(CGRect)bounds
{
    for (CCSprite *sprite in _spritesArray) {
        if (CGRectIntersectsRect(sprite.boundingBox, bounds)) {
            [_spritesArray removeObject:sprite];
            return sprite;
        }
    }
    return nil;
}

```

# Answer
> 0 votes
Beyond the collection-management issue you identified, it's because your first function exits, returning a sprite, as soon as one colliding sprite is found, so no further sprites are examined on that iteration.

The version that performs the removal internally checks collision on all the sprites.

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


# Question
Title: How do I sync entity ids with the server and client?
I'm continuing my experimentation with entity component design by making a multiplayer space/trading/combat game with python and panda3d. My component system is a simple version of java's artimis. The entity id is stored in a simple list with it's position as its id. Components are stored in a second list of dictionaries with the position as the entity id. Components are then mapped in a {Class: instance} dictionary.

The client will only know about entities near it's local space. Entities to be networked will have a ClientComponent which tracks what clients that object is broadcasting to. The server and client sends updates with the entity id of the object being acted on, then the action type, followed by the relevant data and yes, the server will check if it is a valid action by the client. The client needs to have a local copy of the relevant entities and components but I am running into issues on how to set this up.

1. My initial reaction is to just use the entity id's from the server on a client. The client will probably need its own entities for elements like the UI which can interfere with a future entity from a server. I could reserve the first 64-128ish entities for client local use only, but that seems very awkward
2. Next though was to have the client generate the entity ids locally and have a map of client vs server entity ids. The problem here is that some components will have an id of what entity owns it, which can make the mapping system fall apart and hard to debug.

Here are my two questions. Is there a better way to set up the network protocol where I wont run into this issue. If not, what is a decent solution for the client to know the server's entity ids.

# Answer
This is a rough description of how an MMO that I worked on chose how to generate IDs:

For any object that will exist on both the client and server, allow the server to generate the ID, these are `global` IDs. Any time that a client needs to know about that object it should be serialized down to them along with any other data about that object.

For objects that will not need to be networked, there are two categories of IDs: `Local`, and `Static`. Some objects that are not networked are still known by both the client and server, for example, a tree in the world that was placed in a level editor, these objects can have `Static` IDs, generated however you wish, maybe based on the order they are placed in the map. And then there are objects that are created on the fly for server-only or client-only use, and are not networked, these can have unique `Local` IDs.

So you have:

* Global - Networked objects
* Static - Non-networked objects that are known by both client and server.
* Local - Non-networked objects that are known only by client or server, but not both.

It's probably a good idea to generate each type of ID in a different and unique way so that just by looking at an ID you can determine which type it is. For example, if all of your IDs are unsigned 32-bits, that gives you a range from 0 to 4,294,967,295. You could allow a few million or so values for local IDs, as you're not likely to generate a that many objects locally before restarting your client or server. Then split the remaining 4 billion or so between global and static IDs. If you have distinct ranges for your IDs you will know what is global, static, or local just by the value.
> 6 votes

# Answer
I've always just had IDs created by the server, and sent to the client, but that works because the client doesn't have any numbered entities specific to itself in my case.

If I did want to have some client-only entities, I would probably consider storing them in a separate structure to the server-managed ones, so that ID clashes wouldn't matter.

But, if you are trying to have just one set of entities, where each one knows nothing about whether it is controlled by the server or the client, then simply partition the identifier space. You can just reserve a small set of numbers, as you say, but the easiest and probably safest way is to move from using a single number as an ID to having a small class containing 2 values - one is the machine identifier (local or server) and one is the unique identifier generated by that machine. Each machine has a counter and just allocates new entity IDs sequentially from that counter.

You can't safely use a position in a list as an ID anyway. Removing items from that list will change the position, and there will come a time when you want to remove items. You're using Python, so you should use a dict for this, mapping unique values to each item, letting you remove items without affecting the positions of others.
> 4 votes

---
Tags: python, component-based, entity-system, panda3d
---


title: Sprite collisions in android andengine

text:
# Question
Title: Sprite collisions in android andengine
I'm developing a simple game by andengine. I have 10 balls which are moving randomly on screen.i'm importing the balls as picture in sprites.if they move at the same coordinate , they pass though their own insides.but i want: if they move at the same coodirnates ,they should change their directions.so they cannot pass through their insides.how can i do that?

```
 private Runnable mStartCircle = new Runnable() {
  public void run() {
    int i = circleNumber++;
    Scene scene = Level1Activity.this.mEngine.getScene();
    float startY = -64.0f;
    float startX = randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
    float a= randomNumber.nextFloat()*(CAMERA_WIDTH-70.0f);
    circles[i] = new Sprite(startX, startY, textRegCircle[i]);
    circles[i].registerEntityModifier(
            (IEntityModifier) new SequenceEntityModifier (
                        new MoveModifier(10.0f, circles[i].getX(),  a,
                                circles[i].getY(),CAMERA_HEIGHT+64.0f)));
    }
    scene.getLastChild().attachChild(circles[i]);
    if (circleNumber < 10){
        mHandler.postDelayed(mStartCircle,1000);
    }
}

```

};

# Answer
Sounds like you need collision detection.

If you have sprites then its most likely you balls are on a tile of width X height dimensions. You probably want to create a 2D circle struct/class which is orientated at the origin of your sprite and moves about with the sprites when you update their position. Then you can do a simple square distance check between all your balls, if the distance is less than the sum of the radii then you've got a collision. Then, you could make them bounce by inverting their trajectory.
> 1 votes

# Answer
You use a sphere with sphere collision response.

The first requirement is that you separate velocity from position. What this means is that your balls will have a position they are at currently and they have a velocity (direction they want to travel in times speed). In the `Update` function of your `GameObject`, you only change velocity and don't touch position.

I will be using C++ throughout, because I am not familiar enough with Android's Java. The math can be easily ported though, once you understand the concepts behind them.

```
void Ball::Update(float a_DT)
{
    m_Velocity = m_Direction * m_Speed;
    m_Collision->SetPosition(m_Position);
    m_Collision->SetVelocity(m_Velocity);
}

```

Your collision handle consists of a class with the following members:

* `m_Position` \- 2D position
* `m_Velocity` \- Direction in which it is traveling times speed
* `m_Radius` \- Radius (half width) of the bounding sphere
* `m_Weight` \- Weight determines how unmovable an object is

You can determine whether two spheres collide by checking if the distance between their center points is smaller than their combined radii. In code:

```
bool CollisionSphere::CheckCollision(CollisionSphere* a_Other)
{
    if (m_Position.GetDistanceBetween(a_Other->m_Position) < m_Radius + a_Other->m_Radius) { return true; }

    return false;
}

```

So, how do you move the balls apart? Well, for my own game, I looked at this implementation:

http://gamasutra.com/view/feature/131424/pool\_hall\_lessons\_fast\_accurate\_.php?page=3

And here's how I wrote it:

```
void CollisionSphere::CollisionResponse(CollisionSphere* a_Other)
{
    tb::Vec2 delta = m_Position - a_Other->m_Position;
    float d = delta.GetLength();
    tb::Vec2 mtd = delta * (((m_Radius + a_Other->m_Radius) - d) / d);

    float m1 = m_Weight;
    float m2 = a_Other->m_Weight;

    float im1 = 1.f / m_Weight;
    float im2 = 1.f / a_Other->m_Weight;

    // fix position

    m_Position += mtd * (im1 / (im1 + im2));
    a_Other->m_Position -= mtd * (im2 / (im1 + im2));

    tb::Vec2 v1 = m_Velocity;
    tb::Vec2 v2 = a_Other->m_Velocity;
    tb::Vec2 v = v1 - v2;
    float vn = v.GetDotProduct(mtd.GetNormalized());

    // check if moving apart
    if (vn > 0.f)
    {
        return;
    }

    // calculate the impulse for a new velocity vector

    tb::Vec2 impulse = m_Position.GetDirectionTo(a_Other->m_Position);

    float a1 = impulse.GetDotProduct(v1);
    float a2 = impulse.GetDotProduct(v2);

    float optimizedP = (2.f * (a1 - a2)) / (m1 + m2);

    // fix velocity

    m_Velocity = v1 - (impulse * optimizedP * m2);
    a_Other->m_Velocity = v2 + (impulse * optimizedP * m1);
}

```

Then, finally, you have a `PostUpdate` function for your objects:

```
void Ball::PostUpdate(float a_DT)
{
    if (m_Collision)
    {
        m_Position = m_Collision->GetPosition();
        m_Velocity = m_Collision->GetVelocity();
    }

    m_Position += m_Velocity * a_DT;
}

```

And this will fix balls colliding with each other.
> 1 votes

---
Tags: android, collision-detection, sprites, andengine
---