# Question
Title: Objects won't render when Texture Compression + Mipmapping is Enabled
\[EDIT: FIXED - Calling setting texture max level fixed that\]

I'm optimizing my game and I've just implemented compressed (DXTn) texture loading in OpenGL. I've worked my way removing bugs but I can't figure out this one: objects w/ DXTn + mipmapped textures are not being rendered. It's not like they are appearing with a flat color, they just don't appear at all. DXTn textured objs render and mipmapped non-compressed textures render just fine.

The texture in question is 256x256 I generate the mips all the way down 4x4, i.e 1 block. I've checked on gDebugger and it display all the levels (7) just fine. I'm using GL\_LINEAR\_MIPMAP\_NEAREST for min filter and GL\_LINEAR for mag one.

The texture is being compressed and mipmaps being created offline with Paint.NET tool using super sampling method. (I also tried bilinear just in case)

Source follow:

\[SNIPPET 1: Loading DDS into sys memory + Initializing Object\]

```
    // Read header
    DDSHeader header;
    file.read(reinterpret_cast<char*>(&header), sizeof(DDSHeader));
    uint pos = static_cast<uint>(file.tellg());
    file.seekg(0, std::ios_base::end);
    uint dataSizeInBytes = static_cast<uint>(file.tellg()) - pos;
    file.seekg(pos, std::ios_base::beg);

    // Read file data
    mData = new unsigned char[dataSizeInBytes];
    file.read(reinterpret_cast<char*>(mData), dataSizeInBytes);

    file.close();

    mMipmapCount = header.mipmapcount;
    mHeight = header.height;
    mWidth = header.width;
    mCompressionType = header.pf.fourCC;

    // Only support files divisible by 4 (for compression blocks algorithms)
    massert(mWidth % 4 == 0 && mHeight % 4 == 0);

    massert(mCompressionType == NO_COMPRESSION || mCompressionType == COMPRESSION_DXT1 || mCompressionType == COMPRESSION_DXT3 ||
            mCompressionType == COMPRESSION_DXT5);

    // Allow textures up to 65536x65536
    massert(header.mipmapcount <= MAX_MIPMAP_LEVELS);

    mTextureFilter = TextureFilter::LINEAR;
    if (mMipmapCount > 0)
    {
        mMipmapFilter = MipmapFilter::NEAREST;
    }
    else
    {
        mMipmapFilter = MipmapFilter::NO_MIPMAP;
    }

    mBitsPerPixel = header.pf.bitcount;
    if (mCompressionType == NO_COMPRESSION)
    {
        if (header.pf.flags & DDPF_ALPHAPIXELS)
        {
            // The only format supported w/ alpha is A8R8G8B8
            massert(header.pf.amask == 0xFF000000 && header.pf.rmask == 0xFF0000 &&
                header.pf.gmask == 0xFF00 && header.pf.bmask == 0xFF);

            mInternalFormat = GL_RGBA8;
            mFormat = GL_BGRA;
            mDataType = GL_UNSIGNED_BYTE;
        }
        else
        {
            massert(header.pf.rmask == 0xFF0000 && header.pf.gmask == 0xFF00 && header.pf.bmask == 0xFF);

            mInternalFormat = GL_RGB8;
            mFormat = GL_BGR;
            mDataType = GL_UNSIGNED_BYTE;
        }
    }
    else
    {
        uint blockSizeInBytes = 16;
        switch (mCompressionType)
        {
            case COMPRESSION_DXT1:
                blockSizeInBytes = 8;
                if (header.pf.flags & DDPF_ALPHAPIXELS)
                {
                    mInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
                }
                else
                {
                    mInternalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
                }
                break;

            case COMPRESSION_DXT3:
                mInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
                break;

            case COMPRESSION_DXT5:
                mInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
                break;

            default:
                // Not Supported (DXT2, DXT4 or any compression format)
                massert(false);
        }
    }

```

\[SNIPPET 2: Uploading into video memory\]

```
    massert(mData != NULL);
    glGenTextures(1, &mHandle);
    massert(mHandle!=0);
    glBindTexture(GL_TEXTURE_2D, mHandle);
    commitFiltering();

    uint offset = 0;
    Renderer* renderer = Renderer::getInstance();

    switch (mInternalFormat)
    {
        case GL_RGB:
        case GL_RGBA:
        case GL_RGB8:
        case GL_RGBA8:
            for (uint i = 0; i < mMipmapCount + 1; ++i)
            {
                uint width = std::max(1U, mWidth >> i);
                uint height = std::max(1U, mHeight >> i);
                glTexImage2D(GL_TEXTURE_2D, i, mInternalFormat, width, height, mHasBorder, mFormat, mDataType, &mData[offset]);
                offset += width * height * (mBitsPerPixel / 8);
            }
            break;

        case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
        case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
        case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT:
        case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT:
        {
            uint blockSize = 16;
            if (mInternalFormat == GL_COMPRESSED_RGB_S3TC_DXT1_EXT || mInternalFormat == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT)
            {
                blockSize = 8;
            }

            uint width = mWidth;
            uint height = mHeight;
            for (uint i = 0; i < mMipmapCount + 1; ++i)
            {
                uint nBlocks = ((width + 3) / 4) * ((height + 3) / 4);

                // Only POT textures allowed for mipmapping
                massert(width % 4 == 0 && height % 4 == 0);
                glCompressedTexImage2D(GL_TEXTURE_2D, i, mInternalFormat, width, height, mHasBorder, nBlocks * blockSize, &mData[offset]);
                offset += nBlocks * blockSize;

                if (width <= 4 && height <= 4)
                {
                    break;
                }

                width = std::max(4U, width / 2);
                height = std::max(4U, height / 2);
            }
            break;
        }
        default:
            // Not Supported
            massert(false);
    }

```

Also I don't understand the "+3" in the block size computation but looking for a solution for my problema I've encountered people defining it as that. I guess it won't make a differente for POT textures but I put just in case.

Thanks.

# Answer
> 1 votes
You're missing the texture parameters, or you have omitted that part.

```
massert(mData != NULL);
glGenTextures(1, &mHandle);
massert(mHandle!=0);
glBindTexture(GL_TEXTURE_2D, mHandle);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, (ddsd.mipMapLevels == 0) ? 0 : ddsd.mipMapLevels - 1);

```

The rest of your code looks similar to my own DDS texture loader for OpenGL, which loads textures correctly.

---
Tags: opengl, textures, graphics-programming, compression
---


# Question
Title: 2d game view camera zoom, rotation & offset using 'Filter' / 'Shader' processing?
I wish to add the ability to zoom-in, zoom-out, rotate and move the view in a top-down view over a collection of points and lines in a large 2d map. I split the map into a grid so I only need to render the points that are 'near' the camera. My question is, how do I render a point A(Xp,Yp) assuming the following details:

Offset of the camera pov from the origin of the map is:

```
Xc, Yc

```

Meaning the camera center is positioned on top of that point. If there's a point in Xc, Yc it is positioned in the center of the screen.

The rotation angle is:

`alpha`

The scale is:

`S`

Read my answer first. I am thinking there is more optimized solution, thanks.

My question is how to include the following improvement:

I read in the AS3 Bible book that: In regards to ShaderInput, You can use these methods to coerce Pixel Bender to crunch huge sets of data masquerading as images, without doing too much work on the ActionScript side to make them look like images.

Meaning if I am performing the same linear function on a lot of items, I can do it all at once if I use Shaders correctly and save processing time.

Does anyone know how that is accomplished?

Here is a sample of what I mean:

http://wonderfl.net/c/eFp0/

# Answer
> 0 votes
The best answer I found so far as seen on the: How to use Pixel Bender (pbj) in ActionScript3 on large Vectors to make fast calculations? question is:

Use pixel bender to do the movement, rotation and scaling:

```
<languageVersion : 1.0;>

kernel linear
<   namespace : "il.co.elbowroom";
    vendor : "ArthurWulfWhite";
    version : 1;
    description : "Y = ax + b";
>
{
    parameter float4 xyrs <defaultValue: float4(0.0, 0.0, 0.0, 1.0);>;
    parameter float2 halfStage <defaultValue: float2(0.0, 0.0);>;
        // offsetX, offSetY, rotate, scale

    input image4 src;
    output pixel4 dst;

    void
    evaluatePixel()
    {
        float2 vals = sampleNearest(src, outCoord()).xy;
        float2 ovals = sampleNearest(src, outCoord()).zw;
        vals -= xyrs.xy;
        float len = length(vals) * xyrs.w;
        float ang = atan(vals.y / vals.x) + xyrs.z;
        if(sign(vals.x) == -1.0) ang += 3.14159265358979 / 2.0;
        vals = float2(len * cos(ang), len * sin(ang)) + halfStage;
        dst = float4(vals.x, vals.y, 0.0, 0.0);
    }
}

```

How to use pixel bender is covered in the question I mentioned in the beginning.

Explaining the math:

Assuming the screen is `Width` wide and `Height` tall and the position of the camera is `Xc` and `Yc`, we'll render a point A(Xp,Yp) like this:

The screen center will be:

`center = new Point(width/2, height/2);`

Deduct the camera position:

```
offsetPos = A.subtract(camera); // offsetPos = (Xp - Xc, Yp - Yc);

```

To include scale we'll multiply:

```
offsetPos = A.subtract(camera); // offsetPos = (S * (Xp - Xc), S * (Yp - Yc));

```

Now rotate :

```
distance = offsetPoint.length;
angle = Math.atan2(offsetPos.y, offsetPos.x);

renderPos = Point.(distance, angle + alpha).add(Center);

```

---
Tags: shaders, actionscript-3, camera
---


title: Turn based game - HTTP or WebSocket?

text:
# Question
Title: Turn based game - HTTP or WebSocket?
My game will be a turn based game which will need a **server gateway** in order to send requests. What would be better for the server: using REST HTTP GET for making the requests? Or using WebSocket which enables you to have an active connection?

# Answer
> 6 votes
If you need an active connection and literally real-time gameplay, then go with WebSockets, or a similar technique like Comet. Note that WebSockets requires a recent browser, while Comet is probably good enough for most purposes with better support for older browsers. For example, Facebook and Google use Comet for their technologies (Facebook Chat, Google Docs, Gmail, etc.).

If you don't need this, then you can choose plain HTTP. It's probably easier to develop, but you lose the real-time nature of a constant connection.

In this case, "turn based game" is not enough information. A turn based game like Draw Something is only going to have a few turns per day in an average game, so you could probably do just fine with plain HTTP, polling occasionally. A turn based game like chess, you'd probably want to have a little less latency, so I'd probably choose Comet. For some sort of action turn-based game, you might want the real-time nature of WebSockets.

# Answer
> 2 votes
Websockets are definitely the way to go. There are indeed solutions out there that allow you work with websockets smoothly and very fast. A couple were already addressed here and I work for Realtime.co. One of our priorities was precisely providing developers with a way for them to start working with this new technology (with fallbacks, of course) in a very easy way. You can actually start developing in less than 10 minutes. You should worry about your game logic, not your communication layer.

I wouldn't go with comet either right now. Websockets provides you with so many advantages with much less latency and it doesn't force you to hammer your server with constant connections, queries, etc..

There's no reason for developers not to start looking at the websocket-based frameworks out there very seriously.

As to why we should use websockets when Facebook and Google are not. Well... I'm sure they are working hard to change this as it offers them the ability to provide a much better service with a much, much lower maintenance cost.

# Answer
> 1 votes
I would not use Comet for any new development projects. There are websocket providers out there that provide websocket emulation or fallback for older browsers. Kaazing is one and full disclosure I work there, but there are others that will automatically do the fallback for you. And those (like Kaazing) that do it properly, will still provide speed benefits much closer websockets.

# Answer
> 0 votes
You should go for a Real-Time Web solution that completely abstracts from the underlying transport (WebSockets, Comet, etc.), giving you the guarantee that it will work on every possible browser and on the top of any possible network connection (mobile, unreliable, with unpredictable bandwidth, etc.). As the CTO of Lightstreamer, I suggest you to take a look at our solution, which has been around for 12 years, incorporating new standards and techniques. Originated in the financial services field, it has now been adopting by the gaming industry for many new projects. http://www.lightstreamer.com

---
Tags: turn-based, websocket
---


# Question
Title: Do Apple and Google ask for a share if custom payment is done in a free app?
I have a multiplatform game (web/iOS/Android) in the making. In the free version the core game is still fully playable but people who choose to pay will get more social features (and no ads, of course).

I was thinking that rather than having a free and a paid version for all the platforms I may release the apps just for free and if the users want more, they have to register and pay a one-time fee (through a payment gateway or PayPal). The extra content would then be available in all the clients they have access to. Theoretically, this means a better value for the players and less maintenance and headache for me (obviously I have to handle all the payment troubles myself).

Does it fit into the business model of Apple/Google? Or will they still claim their share of the registration fee?

# Answer
Google recently made their policy clearer so both Apple and Google are taking the 30 cut of any transaction made as in-app purchase. They don't allow any other form of payment inside the app and will simply remove your app from the marketplace if you hassle with it.

The only exceptions both of them allow are:

* Selling of virtual goods in the game - they do allow the app to charge using paypal or other payment gateway.
* Unlocking elements purchased elsewhere - If you set up a website where you sell your virtual goods you can unlock them in the app for those users - note that the app is not allowed to link to the website.
> 5 votes

# Answer
Unlocking extra content for paying users is not a problem for either Apple or Google (I assume you mean the Google Play app-store, there are different Android app-stores with different requirements).

However, your app will be rejected by Apple since they require you to use their In-App-Purchase service. It costs 30% for each transaction, but it is a payment flow that users are used to, so why not go with it?

For Google Play it is a bit unclear if it will be allowed in the future to use any other payment service than Google's IAP, so I think you would want to offer that as an alternative at least. Google can't take a share of the payment if it is not done through their IAP service.
> 4 votes

# Answer
As johlo said Apple only allow the use of their own API. I think Google do too.

However, if your game is HTML5 and you host it yourself, you're free to charge anyway you want. You can also instruct your players on how to save the game as an app and take advantage of caching to make the game act as close to any other app as possible (if you want offline playing).

This has it's downsides though, since it's so much harder to build a player base if you choose this solution, (but with all the games on the appstore and google play the chances of not being noticed is rather high anyway).

You will have to figure out a good marketing campaign.
> 4 votes

# Answer
With regards to the unlocking functionality (probably more relevant to your scenario) you will be required to set all goods as 'consumable' in Apple and 'unmanaged' in Google. This means that you need to set up a server to manage the entitlement of all goods on your side. Practically, every client will authenticate the user with the server and will inquire about the balance of different goods.
> 0 votes

---
Tags: android, ios, free-to-play, payment
---


# Question
Title: Camera wont stay behind model after pitch, then rotation
I have a camera position behind a model. Currently, if I push the left thumbstick making my model move forward, backward, or strafe, the camera stays with the model. If I push the right thumbstick left or right, the model rotates in those directions fine along with the camera rotating while maintaining its position relatively behind the model.

But when I pitch the model up or down, then rotate the model afterwards, the camera moves slightly rotates in a clock-like fashion behind the model. If I do a few rotations of the model and try to pitch the camera, the camera will eventually be looking at the side, then eventually the front of the model while also rotating in a clock-like fashion.

My question is, how do I keep the camera to pitch up and down behind the model no matter how much the model has rotated? Here is what I got:

```
// Rotates model and pitches camera on its own axis
    public void modelRotMovement(GamePadState pController)
    {
        // Rotates Camera with model
        Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(angularSpeed);
        AddRotation = Quaternion.CreateFromYawPitchRoll(Yaw, 0, 0);
        ModelLoad.MRotation *= AddRotation;
        MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation);

        // Pitches Camera around model
        Pitch = pController.ThumbSticks.Right.Y * MathHelper.ToRadians(angularSpeed);
    }

    // Orbit (yaw) Camera around with model (only seeing back of model)
    public void cameraYaw(Vector3 axisYaw, float yaw)
    {
        ModelLoad.CameraPos = Vector3.Transform(ModelLoad.CameraPos - ModelLoad.camTarget,
            Matrix.CreateFromAxisAngle(axisYaw, yaw)) + ModelLoad.camTarget;
    }
    // Raise camera above or below model's shoulders
    public void cameraPitch(Vector3 axisPitch, float pitch)
    {
        ModelLoad.CameraPos = Vector3.Transform(ModelLoad.CameraPos - ModelLoad.camTarget,
            Matrix.CreateFromAxisAngle(axisPitch, pitch)) + ModelLoad.camTarget;
    }

    // Call in update method
    public void updateCamera()
    {
        cameraYaw(Vector3.Up, Yaw);
        cameraPitch(Vector3.Right, Pitch);
    }

```

**NOTE: I tried to use** `addPitch` **just like** `addRotation` **but it didn't work...**

**UPDATE** I understand the problem Im having fully. While Im facing world-North or world-South, the camera pitches around the model like normal. But lets say I'm facing world-East. The camera will still point to the model regardless of the rotation, but when I pitch the camera, it will rise and fall in a clock-like fashion around the back of the model. So the camera itself is still pitching as to world's North and South. Not the model's North and South.

# Answer
> 1 votes
> ```
> public void updateCamera()
> {
>     cameraYaw(Vector3.Up, Yaw);
>     cameraPitch(Vector3.Right, Pitch);
> }
>
> ```

Usually, this is solved by pitching first, then yawing.. Like this:

```
public void updateCamera()
{
    cameraPitch(Vector3.Right, Pitch);
    cameraYaw(Vector3.Up, Yaw);
}

```

The short explanation is that the axis you need to pitch around changes as you yaw, but the axis you yaw around does not change as you pitch.

here's the long explanation: http://www.screencast.com/users/sh8zen/folders/Xna/media/929e0a9a-16d1-498a-b777-8b3d85fd8a00

---
Tags: xna, camera, rotation
---


# Question
Title: Is this a reliable method of parsing glGetShaderInfoLog()?
I want to get a list of errors and their line numbers so I can display the error information differently from how it's formatted in the error string and also to show the line in the output.

It looks easy enough to just parse the result of glGetShaderInfoLog(), look for `ERROR:`, then read the next number up to `:`, and then the next, and finally the error description up to the next newline.

However, the OpenGL docs say:

> Application developers should not expect different OpenGL implementations to produce identical information logs.

This makes me worry that my code may behave incorrectly on different systems. I don't need them to be identical, I just need them to follow the same format.

So is there a better way to get a list of errors with the line number separate, is it safe to assume that they'll always follow the "ERROR: 0:123:" format, or is there simply no reliable way to do this?

# Answer
This is too long for a comment, so i have to put it in an answer. Here are error codes i got when developing an engine in OpenGL 3.3 GLSL 330 about 3 months back. Latest drivers on both platforms.

Sample Vertex Shader error on my friend's laptop (NVIDIA). It wouldn't recognize a matrix layout specified locally in an UBO structure:

```
0(35) : error C3008: unknown layout specifier 'row_major'
0(36) : error C3008: unknown layout specifier 'row_major'

```

Sample Fragment Shader error on my own PC (ATI):

```
Fragment shader failed to compile with the following errors:
ERROR: 0:83: error(#143) Undeclared identifier blinn_phong
ERROR: 0:83: error(#132) Syntax error: 'term' parse error
ERROR: error(#273) 2 compilation errors.  No code generated

```

You can't expect the same format for all drivers, but the values you're looking for should be distinguishable enough to let you rely on regular expressions to get the information without the need to detect which drivers the user has installed.
> 0 votes

# Answer
It has different formats in different graphics card drivers, however it should be possible to detect common things and retrieve them. There are things that should be common between various drivers:

* First word should specify error type.
* First two integers will be File ID and line number.
* The rest of the text will most probably be error text.\*

There are things to look out for:

* Symbols separating items may differ. Order may differ too.
* Error text can contain almost anything.
* Any of these rules can be broken at any time so if you start using something like this, be prepared to enable driver version detection and driver-specific hacks, at least if you plan to make the feature available to users.

\*- According to images found in Google with queries "glsl compile error"/"glsl error", in one case, before reading text, the colon should be skipped while apostrophe shouldn't. More info inside these images: image 1; image 2; image 3
> 0 votes

---
Tags: opengl, glsl
---


title: What is the point in using real time?

text:
# Question
Title: What is the point in using real time?
I understand that using real time frame elapses (which should vary between 16-17ms on average) are provided by a lot of frameworks. `GetTimeElapsedSinceLastFrame`, and it gives you the wall clock time.

But **should we use this information in basic physics simulation?** It looks to me to be a *bad* idea.

Say there is a slight lag on the machine, for whatever reason (say a virus scanner starts up). The calculations *all* jump, and **there is no need for this**. Why not use a virtual second and ignore wall clock time? For gameplay on the level of Commander Keen, shouldn't you always use the virtual second and not real-time? (Besides stopwatch timing for race games) I don't see a need to use real time and not a fixed 16ms time step.

# Answer
What you mention is a well understood problem in general. The "virtual second" you mention is generall just thought of as a fixed time delta that is updated baed on an accumulator from wall time. The reason some developers use wall time directly is mostly ignorance on their part in most cases, and special circumstances in others.

The usual article to link folks to if you see them using wall time is the Glenn Fidler article Fix Your Timestep: http://gafferongames.com/game-physics/fix-your-timestep/
> 7 votes

# Answer
You seem to assume that most games aim for 60FPS, but actually it's much more varied than that. Console games tend to be either 60FPS or 30FPS. And games for PCs and other platforms tend to be wildly variable, though often related to the monitor refresh rate (which can be 60Hz, or 70, or 75, etc).

The reason you would want to tie game time to real time is because the player lives in real time. You don't want the gameplay to run at half the speed just because the player has selected high resolution graphics, for example. So when the game needs to update things, you want to update them proportional to the amount of real world time that has passed since the last time you updated them, or the player will notice odd behaviour.

But if your question is really about whether it's a good idea to let a variable visual frame rate affect a physics simulation, then the answer is that it usually isn't a good idea - but it's mostly trivial to work around, by picking an arbitrary timestep for physics and executing enough of those timesteps to keep up to date, based on the current real time, and maybe interpolating/extrapolating the rendering to smooth things out.

The reason this isn't done more widely is because it makes very little difference to most of the smaller games which don't perform any complex physics or where gameplay doesn't depend on the outcome of those physics.

There is plenty of discussion of this in other questions:
> 6 votes

---
Tags: fixed-timestep
---


# Question
Title: Is there any relation between Game Theory and Game Development?
I'm a Java programmer interested to learn games on Java, recently I looked on a book on Operations Research written by Wayne L.Winston. There is a topic on Game Theory.

It's truly mathematical. I'm just an app developer, but would that book be helpful to start a game career?

# Answer
The **game** in game theory and game development are not talking about the same kind of games. Game theory is mainly used in economics and political science. Sounds like the book you were reading was about business strategy?

I would say it's more accurate to say that game theory can be applied to computer science and the development of logical theories related to high level algorithms. But studying game theory will not necessarily help you become a better game developer.
> 11 votes

# Answer
Most of the games in game theory wouldn't make very good video games. For example, one game goes something like this:

There are people bidding on $100. The rules are if you win you pay what you bid and get the $100. If you're in second you also pay what you bid but you don't get anything. A pretty boring game and if the bids go over $100 both people lose.

The kind of things you'd learn in game theory would probably apply more to thinking about how a player might approach your game rather than help development. Since I feel like the other posts have already established that it wouldn't really be beneficial, altough its pretty interesting if you're into that kind of thing, I'll talk about maths that might be helpful.

Linear algebra is a must, mostly because it's used in a lot of other branches of math, including game theory. It's the kind of math I've run into the most when developing games. I imagine if one got into engine development this kind of math would be even more relavant. It's also more useful in 3D games as opposed to 2D.

Combinatorial maths could be helpful. Especially for probability. Also Combinatorial game theory is about games but exclusively turn based and generally the games are simple.

Discrete probability is also useful. I haven't really seen too much continuous stuff but discrete things come up quite often and might actually cut back on testing time. Basically any time you use random numbers you'd use probability. Sometimes it's pretty basic but who knows, sometimes probability problems look a lot less involved than they actually are.

And I imagine if you were to develop a physics engine Calculus would be used but I don't know anything about engine development.
> 6 votes

# Answer
There is a relationship, as game theory is also known as "interactive decision theory" (Wikipedia), but it's an extremely complex subject and you would probably be better off starting down a more traditional path.

Basically, yes it would be helpful, but there are arguably "better" ways to start game development, like studying the fundamentals of computer science.
> 5 votes

---
Tags: java, game-theory
---


# Question
Title: Unity 5.1 audio issues (no sound in back channels)
I've trying to bring in surround sound audio into my project. I've set my computer up to run in 5.1 and when I play a 6 channel audio through windows media player (it's a test audio that does left speaker, right speaker etc) it works fine.

However, when I run it through Unity, all I get is the front 3 channels. I've set it in the Edit -\> project settings -\> audio to be 5.1 in there. I even set it in code with following:

void Start() { AudioSettings.speakerMode = AudioSpeakerMode.Mode5point1; } How ever, when I run a debug line of:

print ( AudioSettings.driverCaps); It tells me that Unity is only playing in stereo. Is there something I'm still not doing?

I should also add I've ran 10 different tests using the 3D audio pan and spread options. I've set both to either being fully off, half way on and full. Still the same results.

# Answer
> 1 votes
Taking a quick look at the AudioSettings reference, it says that **AudioSettings.driverCaps** gives the speaker mode *capability* of the current audio driver. If the current audio driver is only *capable* of stereo playback, then that's why you aren't hearing 5.1. Try debug printing the value of **AudioSettings.speakerMode** to see what's actually set. The speakerMode reference says: "If a speaker mode is set beyond the drivers capability, the audio behaviour is undefined."

---
Tags: unity, audio
---


title: How can I protect my games?

text:
# Question
Title: How can I protect my games?
How can I protect my game database/website from getting hacked by anyone? And how can I prevent some hacks ingame, such as god mode and so on?

Thanks!

# Answer
> 1 votes
This question is far more important and difficult than a standard *1 million question*.

The answer is just under your nose and it's basically this: you can't and you are in an arms race.

There is a much more modern answer and it's: make it online and make it a service.

Games like Battlefield or Call of Duty are hacked and cracked but the fact that a big portion of their value is about online gaming on closed networks contributes to keep things under control even if the original game is hacked.

There is not even a viable approach to encription that can ensure you that your data is safe, you just need people working on this day by day in keeping your software up to date, no other real answers here if you care about your data.

If your users do not care about censorship and/or a limited amount of possibilities you can take alternative paths like the one taken by the games that i have mentioned before, but usually this requires a very good marketing approach.

---
Tags: security
---


# Question
Title: How to design 2D collision callback methods?
In a 2D game where you have a lot of possible combination of collision between objects, such as:

object A vs object B =\> object B vs A;

object A vs object C =\> object C vs A;

object A vs object D =\> object D vs A;

and so on ...

Do we need to create callback methods for all single type of collision? and do we need to create the same method twice? Like, say a bullet hits a wall, now I need a method to penetrate the wall for the wall, and a method to destroy the bullet for the bullet!!

At the same time, a bullet can hit many objects in the game, and hence, more different callback methods!!!

Is there a design pattern for that?

# Answer
I recommend defining an interface for all of these object types (*ICollidable*, for example), that contains the following method:

```
void ApplyCollision(List<ICollidable> colliders)

```

In your collision detection loop, when examining obj\_A for collisions, you create a new `List<ICollidable>`, and add all other objects to this, which collide with obj\_A.

Once this list is built (you finished examining obj\_A), you can call the ***ApplyCollision*** method with the list as an argument. In the ***ApplyCollision*** method, you're stepping through the items of the list, and yes: you will probably need a switch statement at this point, since a *Bullet* will probably be destroyed with a nice visual effect when it hits a *Wall*, while the *Wall* might only get a decal. And the *Bullet* will cause damage to a *Player* or a *Vehicle*, etc. But everything else is generic in the collision detection method.
> 1 votes

# Answer
You do not need to have a different collision callback method for each type of collision.

You could implement one callback: `collisionEvent(objA, objB);`

To treat different types of objects you can have collide-able objects implement an Interface `ICollide` that has a function, collideWith(obj); and perhaps `getMass();` and possibly `getSurfaceType();` Then each object checks the attributes of the object it collided with and responds appropriately. For instance a bullet may pass through a wooden wall, bounce off a metal sheet and knock off a tin can.

The insides of `collisionEvent(objA, objB);` will look like:

```
{
    objA.collideWith(objB);
    objB.collideWith(objA); // You may need to elaborate depending on the game
}

```

Instead of having a switch statement, you could use 'low resolution attributes' to keep things simple.

For instance add a density to each collideable object. It could be a Enum to reflect the needs of the game.

1. Lets take a solid metal sheet, it will have a density of High and a bullet will check against that and bounce off it.
2. A wooden wall will have a density of Low and the bullet will pass through.
3. A thick sturdy plaster wall will have a Medium density and the bullet will get trapped inside it.

In reality I am pretty sure the bullet would pass through a plaster wall, that was just an example for a third option.

You will probably need a mass property if you have many objects of different sizes.

For instance, a tin can will be low density and have a low mass value, meaning it will bounce off when hit by a bullet and the bullet will continue in its trajectory. Some items will need to be of a fragile variety such as glass, so you will destroy the item if it is hit by a bullet and animate this process.

All the properties I described exist in physics engine except fragility, however physic engines mostly assume objects cannot pass through one another. You could try and override that behavior programatically. Simply by not checking/acting on collisions between bullets and materials of low density.
> 0 votes

# Answer
I had the following problem few months ago (I was implementing a little physics engine in C++), and I didn't get to any clean solution to this problem.

I try to share a little bit of what I came up with.

> Do we need to create callback methods for all single type of collision?

Basically the answer is YES.

> and do we need to create the same method twice?

Basically the answer is yes. You can eventually avoid creating the same collision dispatch method, but you would always need some double/triple dispatch technique in order to manage all possible collision combinations.

---

There would be a nice solution using Visitor pattern if `C#`(or `C++` in my case) would allow multiple dispatch. I posted a quite generic question, but you can interpret the answer linked above like if:

* Visitor-\>**collision dispatcher** interface (to be implemented)
* Base-\> **Collidable** interface (eventually exposing some common methods like GetMass(),...)
* Derived1 -\> **Wall**, Derived2-\> **Bullet** (using your example)

You can emulate multiple dispatch in C# like shown here (You can eventually translate it from C++ to C#, but I don't think it's a good solution). This esoteric solution has several drawbacks:

* **bad performances**: too much method calls. This is particularly negative because you usually need to handle a lot of collisions at almost each frame.
* **readability**: even if visitor is a well know pattern, the multiple dispatch variant exposed in the link is not easy to understand
* **maintenability**: even if all derived class share the same identical implementation, you can't enclose this inside a Macro, like would be possible in C++. So you'd have to modify all base classes implementations once you add a shape.

---

Finally I decided to use std::map with an std::pair as key, and a function pointer as value. You can achieve the same result in C# this way:

* Define a common Collidable Interface
* Implement a collision handler function for all collision pairs
* Use a class or a struct to hold pair of collision object that also implements IEqualityInterface( let's call it ColliderPair)
* Declare a dictionary to store delegates associated with each CollidePair:

```
 Dictionary<CollidePair, Action<Collidable,Collidable>> handlerTable;

```
* Populate handlerTable with the desired delegates, for each combination of pairs, while initializing your app
* When you need to resolve a collision, build a CollidePair and use it to find the right delegate into the Dictionary.

Sorry for the long esoteric answer :). I hope to have given you some hints. I post a C# implementation when I have time.
> 0 votes

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


# Question
Title: Where does the money to make a video game come from?
So 360/ps3 video games takes a few months to a few years to make I assume. If so where does the money to pay employees and costs of everything needed to make the game come from during those few months/few years?

# Answer
> 20 votes
Depends on the game and the people making it. There are common sources for nearly any product being created, games aren't that different, but the below are tailored slightly more towards games:

* Publisher: A company that partners with a development studio to create a game. This is very much like an investor below, but the publisher will typically have considerably more control and influence over the final product.
* Investors: People or companies with money. They invest the money to make the game, they share in the profits.
* Capital from previous games: The game companies themselves fund the games with money they made from previous games.
* Personal funds: Indie devs often work for no money, have jobs on the side or burn through their savings while working on their game.
* Crowd sourcing - Kickstarter or similar sites allowing the crowd funding of games.
* Grants: Via the government of their country or various organizations promoting arts.
* Loans: Companies or individuals can take out a loan to pay for the development costs of a game (this is similar to investors, but with banks and likely more liability).

---
Tags: costs, pricing
---


# Question
Title: Animate sprite/texture position with VBO
I'm currently worlking on a renderer for my projects and I want animate a sprite on screen. I've got a spritesheet but I don't know what is the the best way to update the texture coordinates for each vertex.

* Update vertices then update vertex buffer. (Heavy ?)
* Send to the shader my texture coordinates (It is possible ?)
* Don't use VBO ?

By the way, I've got this structure : Object class with Geometry (Faces + Vertex + Buffer) and Material (Shader + other stuff ) properties, it is a good structure ?

Thanks!

# Answer
IF you're using GLSL, pass a uniform or two into the fragment shader to say what x and y offsets you need to use to shift to the current frame / rect in the spritesheet / texture atlas, and then use those uniforms in the shader, to shift the texture coordinates appropriately. That's way better than having to reupload per-vertex data (i.e. texture coordinates) every frame.

I suppose it would be easier, too, if you set your GL\_TEXTURE\_WRAP\_S and/or GL\_TEXTURE\_WRAP\_T to mode GL\_REPEAT rather than GL\_CLAMP, since that would allow you to jump around the spritesheet more deftly. But it's not absolutely necessary, it's just the equivalent of using modulo in detecting where your next position should be so that you wrap to the next row of animation frames.
> 4 votes

# Answer
Create a VBO containing *all* of the sprite's frames, and make your glDrawArrays call with the appropriate (frameNumber * 4) in the *first* param.

If you want to get even more clever about it, you could make it a static VBO and do your billboarding formula in your vertex shader. The sprite origin would then become a shader uniform, as would the up and right (or left, as appropriate) vectors.

Sample vertex shader code:

```
uniform mat4 mvpMatrix;
uniform vec3 upVec;
uniform vec3 rightVec;
uniform vec3 spriteOrigin;

layout(location = 0) in vec2 position;
layout(location = 1) in vec2 texcoord;
.....
.....
gl_Position = mvpMatrix * vec4 (rightVec * position.y + (upVec * position.x + spriteOrigin), 1);

```

Filling the VBO (load-time only, adjust the indexes into framedata to suit the orientation of your texture):

```
framedata[0].positions[0] = frame->down;
framedata[0].positions[1] = frame->left;

framedata[0].texcoords[0] = // whatever
framedata[0].texcoords[1] = // whatever

framedata[1].positions[0] = frame->up;
framedata[1].positions[1] = frame->left;

framedata[1].texcoords[0] = // whatever
framedata[1].texcoords[1] = // whatever

framedata[2].positions[0] = frame->down;
framedata[2].positions[1] = frame->right;

framedata[2].texcoords[0] = // whatever
framedata[2].texcoords[1] = // whatever

framedata[3].positions[0] = frame->up;
framedata[3].positions[1] = frame->right;

framedata[3].texcoords[0] = // whatever
framedata[3].texcoords[1] = // whatever

glBufferSubData (
    GL_ARRAY_BUFFER,
    framenum * 4 * sizeof (spritevboframe),
    4 * sizeof (spritevboframe),
    framedata
);

```

Here, frame-\>up/down/left/right are just derived from the width and height of each frame; you could potentially double them up with the texcoords or it may be useful to keep them separate if you want to use different scalings.

Draw call:

```
glDrawArrays (GL_TRIANGLE_STRIP, frameNumber * 4, 4);

```

From here you can easily go more advanced and use instancing if you need to draw many sprites with the same frame; the uniform data above would become per-instance data. But that's a topic for another time.
> 1 votes

---
Tags: opengl, sprites, vbo
---


# Question
Title: How to make an object stay relative to another object
In the following example there is a guy and a boat. They have both a position, orientation and velocity.

The guy is standing on the shore and would like to board. He changes his position so he is now standing on the boat.

The boat changes velocity and orientation and heads off. **My character however has a velocity of 0,0,0** but I would like him to stay onboard. When I move my character around, I would like to move as if the boat was the ground I was standing on.

**How do keep my character aligned properly with the boat?** It is exactly like in World Of Warcraft, when you board a boat or zeppelin.

This is my physics code for the guy and boat:

```
this.velocity.addSelf(acceleration.multiplyScalar(dTime));

this.position.addSelf(this.velocity.clone().multiplyScalar(dTime));

```

The guy already has a reference to the boat he's standing on, and thus knows the boat's position, velocity, orientation (even matrices or quaternions can be used).

# Answer
> 3 votes
Your best luck is to learn some matrix math.

You should have some kind of scene graph that establishes the character as a child node of the boat. It then would store it's position relative to the boat.

The boat would have a transformation matrix, you apply that to the child nodes, and the child nodes could stack some more transformations on the matrix letting you move around the boat while moving relative to it.

---
Tags: matrix, vector, gameobject, orientation
---


# Question
Title: Billboarding + aligning with velocity direction
I'm working on a particle system where I'm orientating the billboard using the inverted orientation matrix of my camera. This works quite well and my quad are rotated correctly towards the camera.

But, now I want to to rotate the quads in such a way that they point towards the direction they are going to.

In 2D this can be done by normalizing the velocity vector and using that vector for a rotation around the Z-axis (where vel.x = cos(a) and vel.y = sin(a)). But how does this work in 3D?

Thanks roxlu

# Answer
> 1 votes
It works the same in 3D. Use your inverted camera matrix to transform the particle velocity as well as their position, and this will put the velocity into screen space. You will then have, effectively, a 2D vel.x and vel.y which you can use to construct a rotation to apply to your quads.

# Answer
> 0 votes
In 3d it is often easier to use linear algebra rather than trig to create the matrix. Assuming your 3d world is a Y up world, it goes like this:

1.) You start with the normalized vector representing `quadPosition - camPosition`. these x, y, z components become your m31, m32, m33 values.

2.) Cross the normalized velocity with the result of #1 and normalize the result which becomes your m11, m12, m13 values.

3.) Cross those two vectors (result of #1 & #2) and this result becomes your m21, m22, m23 values.

4.) the location of your particle in world space becomes the m41, m42, m43 values.

5.) set m44 to 1. Set m14, m24, m34 to 0.

You now have a matrix that would orient the quad to face the camera but rotated in a way that the upper edge of the quad is 90 degrees to the velocity.

---
Tags: c++, opengl, mathematics, vector
---


# Question
Title: Legal concerns with orchestrating a music submission contest
My team and I are getting pretty far along in the development of our latest game and have been thinking about audio. We decided to host an audio submission contest where we will offer a little cash and some equity stake in the game as prizes. We are also giving away copies of the game to participants. We hope not only to find audio for our game, but to meet some cool sound artists and promote the game a bit through the process.

First of all, **is this even a good idea? What are some potential dangers in doing this?** Will it even be well received among artists?
Secondly, I wrote up some Terms and Conditions in my best legal-speak to try to protect us and clarify how the contest will be run. **Are these sufficient to make sure everyone involved is treated fairly and is legally protected?** They are as follows:

* All submissions (The Submission) must be licensed under a Creative Commons Attribution 3.0 Unported License (CC-BY-3.0)
* By applying a CC-BY-3.0 license, you (The Submitter) expressly give Detour Games (and all members wherein) permission to copy, distribute, transmit, modify, adapt, and make commercial use of The Submission.
* The Submitter must own all rights to The Submission and be within their rights to license it as specified and submit it.
* The Submitter claims responsibility for the legality of The Submission. If The Submission is found to infringe on the rights of a person or entity other than those of The Submitter, Detour Games will not be held liable as all responsibility and liability for the legality of The Submission is that of The Submitter's.
* No more than two free copies of The Game per submitter.
* All flat cash prizes will only be disbursed pending the success of our first $5,000 Kickstarter campaign. These prizes will be disbursed 30 days after Detour Games receives the Kickstarter funds.
* All equity prizes (percentage of profits) are defined as the given percent of total profits after costs for a period of one year (12 months) after the release of RAW. These prizes will be disbursed semi-annually.
* All prize money will be disbursed through either an electronic fund transfer through a service such as PayPal or by a mailed money order. It is The Submitter's responsibility to cooperate with Detour Games in the disbursement of the funds.
* Detour Games reserves the right to change these Terms and Conditions at any time without notice.
* By participating in the contest, The Submitter agrees to and accepts all terms and conditions listed.

**What else could I do (legally) to protect everyone involved?**

# Answer
*Disclaimer: I am not a lawyer and this is not legal advice...*

> is this even a good idea?

I think you're idea is pretty sweet. If you market it right, the the contest could generate some good buzz for your studio and your game.

> What are some potential dangers in doing this?

You'll probably want to make sure that *all* submissions to your studio via this contest become property of the studio. You don't want to get sued for copyright infringement just because you didn't word your contracts properly. However, see below...

> What else could I do (legally) to protect everyone involved?

In my opinion, the only acceptable answer to this question is ***ask a lawyer***. Seriously. You've obviously put some time and effort into fleshing out this idea. You don't want to risk it all by not spending a few bucks on *proper* legal advice.
> 1 votes

---
Tags: legal, audio, marketing, music
---


# Question
Title: Best C++ Portable time library for game development
I'm venturing into the dark world of portable development and I'm looking for a nice library to keep track of system time for all game events. So far I've turned to trust boost and found:

This boost library

But I'm wondering if it there are some alternatives. I use boost a lot and (while I like it) I find that it sometimes takes me longer to figure out how to use the generic code than to write my own...not-so-generic code. (Ya, ya...I know. I should be less lazy). But anyway, advice appreciated! :)

# Answer
As general rule you should avoid to add more dependecies than the ones you really need and try to semplify the building process or keep it as simple as you can.

I honestly don't like the boost libraries because of their own build system and the fact that they use too much abstraction, meaning that most of the time there is a significative loss in terms of performance. They are also not so easy to port to new platforms, for example the boost libraries on Android are not really easy to port but Android provides complete support for a C++ toolchain, the problem is just the building system adopted by the boost project; also the boost libraries have a significative amount of Mb, meaning that they take time to build, debug and they make your application larger.

I know that i'm pedantic on this but this are the downpoints in my opinion, the boost libraries still are a great package in the C++ world, but for some specific task like the one that you describe i would just consider writing my own wrapper and probably this will contribute to keep everything else much easier to handle. I think that you will appreciate the boost libraries if you are going to use them for at least 3-4 generic tasks, and with tasks i mean the "names" of the internal libraries in the boost library; with this usage you can consider adopting boost libraries, otherwise i don't think that they will be worth the trouble.

If you are already using the boost libraries just keep using them and try to avoid adding new dependecies to your project, there are also the platinum libraries which are kinda like an alternative to the boost libraries.
> 2 votes

# Answer
Sorry for this dirty answer but here is my solution! I've used this code both in VS 2010 and xCode. Since the xCode version is based on linux tutorials I assume it works there you, any way you might want to clean somethings in there but it should work without any problems by itself. just use it like how you use unix gettimeofthe day variable.

```
#pragma once
#ifndef TIMESTAMPER_H_
#define TIMESTAMPER_H_
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif

class Timer
{
public:
#ifdef _WIN32
    struct timezone
    {
        int tz_minuteswest;
        int tz_dsttime;
    };
    struct timeval {
        long tv_sec;
        long tv_usec;
    };
    int gettimeofday(timeval* tp,timezone* tzp)
    {
        LARGE_INTEGER ticksPerSecond;
        LARGE_INTEGER tick;
        QueryPerformanceFrequency(&ticksPerSecond);
        QueryPerformanceCounter(&tick);

        tp->tv_sec = tick.QuadPart / ticksPerSecond.QuadPart;
        tp->tv_usec = ((tick.QuadPart % ticksPerSecond.QuadPart) * 1000000) /ticksPerSecond.QuadPart;
        return 1;
    }
#else
    typedef struct ::timeval timeval;
    typedef struct ::timezone timezone;
#endif
};

```

I've once heard that `QueryPerformanceCounter` is not very accurate due to the fact that these days processors may change their frequencies. But it worked fine on my coreI7 cpu so I guess that was not causing any problems.
> 0 votes

# Answer
Any game developer worth their salt should understand and be able to quickly write their own timekeeping implementations. This is too crucial to the very concept of developing any kind of real-time simulation, to pass the job of writing that code off to someone else. An excellent introduction to the topic is Glenn Fiedler's "Fix your Timestep", which has been quoted over and over and this site and will be quoted many times more.

The gist is that timekeeping is crucial to determinism in:

* Physics
* AI
* Networking
* General game logic
* Rendering (less important, but still important)

A deterministic simulation is one you can debug more easily, and thus develop more fruitfully, because using the same set of inputs, you will always get the same set of outputs. So you can reproduce bugs and undesirable emergent conditions instantly using program logs from a previous run where that problem was observed. An excellent source on how crucial this can be is "1500 Archers on a 28.8" which is about the development of Age of Empires.
> 0 votes

# Answer
If you are interested in the nitty gritty reality of high resolution timing on the PC, you should read the article Timing Pitfalls and Solutions by Jan Wassenberg. It is 5 years old now, but unfortunately the landscape has not improved significantly as far as I'm aware.

You may also be interested in the related GameDev.net discussion thread and article. Unfortunately, the formatting is badly broken on the latter, presumably from years of site redesigns, but the content by and large appears to simply be an earlier iteration of what's in the PDF I linked above.

The forum thread in particular has links that are supposed to go to source code, but they all 404 at this point. The article, meanwhile, has a small snippet of code at the bottom that you can get to a semi-readable view of by looking at the article revision history.
> 0 votes

---
Tags: c++, timer
---


title: Game Database Connectivity Java

text:
# Question
Title: Game Database Connectivity Java
I'm developing a simple multi-player puzzle game in Java. Both players should be able to view the same game board on his own computer. Then, when one player makes an action in the game (ex. drags an object onto a coordinate space), the game's view should update automatically on the other computer's game screen. I'd like all this to happen over the internet, not requiring both computers to be on the same LAN connection.

If I need to use SQL/PHP to accomplish this, I'm unsure how to design the database to accomplish something as simple as the following:

```
Player A drags element onscreen
Game sends coordinates of element to database/server

Player B's computer detects a change to an item in the database
Player B's computer grabs the coordinates of Player A's item
Player B's machine draws onscreen elements at the received coordinates

```

Could somebody point me in the right direction?

# Answer
> 2 votes
Using sockets for real-time communication, the idea would be something like the following:

* The server is listening; players A and B have connected to it.
* Player A drags an element onscreen; a dragging message is sent to the server, with the details of the drag.
* The server receives the drag message and sends it on to player B, wrapping it with player A's name.
* Player B receives the drag message and sees that it's from player A. It gets the data from the message and uses it to update player A's representation on screen.

A good start would be Oracle's official lesson, "All About Sockets".

---

This is possible with PHP & MySQL, but the flow is much different; it requires repeated polling for updates (or a trick like Comet; which is still polling, just less frequently).

Your database would have the typical data; a table for `Players`, a table maybe for `PlayerDrawnObjects`... (you should probably choose better names). But it should have one more table, let's call it `Actions`. Your flow would now be like this:

* Player A "connects" by requesting the PHP page; the PHP page gives it the information of the player drawn objects and the currently logged on players. It also gives a timestamp value, which is the current time on the server (time()), and which player A's client saves in a variable. The `Players` record for Player A is updated to set the "LoggedIn" column to TRUE. In addition, the PHP page adds a record to the `Actions` table which says that Player A logged in, and that record is timestamped with the current `time()`.
* Player B does the same.
* It's been a couple seconds since Player A got the initial state of the game, so his client decides it's time to update. The PHP page is requested again, this time sending along the timestamp that was given to it and asking for an update rather than a "connection". The PHP script does a `select` on the MySQL server, of all the records in the `Actions` table where the timestamp is newer than the given timestamp; i.e., all the records saved in the past couple seconds. This would include the Player B login event. It returns back those records (player B's login event), along with a new `time()`. Player A's client now updates to show player B, and that time variable is updated.
* This is repeated every few seconds by every player; or in the case of Comet, every player has requested the PHP page and the PHP page is looping, waiting for a new entry in the Actions table to send back to the client. Either way, the essence is that the client holds a timestamp (given by the server) of the last update it received, it keeps passing it back to the server and receiving new records and updating its timestamp, and this is how things stay current.
* Every action needs to be updated both as a line in the `Actions` table, and as a change in the permanent database schema. Because remember, when a new player logs in, it pulls data from other tables besides the `Actions` table; the `Actions` table is for players who already "connected". You certainly *could* just use the `Actions` table, but then every new player would have to "catch up" by reading all of the actions and fast-forwarding through them, and that would be a lot of extra bandwidth. (a hybrid solution could be designed if you're adventurous...)
* Alright, so Player A drags. His client requests a different PHP page, which inserts a record into the `Actions` table explaining the drag operation, and updates the `position` data for the object in the `PlayerDrawnObjects` table.
* On the next poll, Player B receives that new record in the `Actions` table and updates the on-screen representation of the object accordingly.

---

Sockets are truly real-time; messages are pushed across the wire and received very quickly. Comet can make PHP more real-time, but it's still a more complicated process to use MySQL as shared storage for message-passing.

I personally implemented the second method some years ago, when I didn't have access to run a server but had a shared web host which supported PHP. Nowadays, I would probably use the first method, writing a custom server and hosting it on a VPS or some other server I had access to; perhaps even a "cloud application" service like Heroku.

# Answer
> 1 votes
You can either do direct socket connection between the two computers, or you can mediate the connection with php/sql.

In the client it would propagate moves to the server would store it in the database, on the other end the user would poll the web service to detect any pending changes and update on their end.

The database should probably just be a list of moves and whether they have been delivered.

The idea being that if you exchange the list of moves you can recreate an identical state on both ends.

Be aware though, you would need to "push" the updates if you wanted them to propagate near realtime and this is not something that web-servers do. Web servers respond to request, they don't force anyone to consume anything they didn't ask for.

So you might want direct socket communication so that you can directly communicate between clients with lower latency. You can maybe use a website/php/database to help with matchmaking which would be a more appropriate use of a website.

---
Tags: java, multiplayer, data-structure, databases
---


# Question
Title: Moving a body in a specific direction using XNA with Farseer Physics
I have a custom polygon attached to a body, which looks like this: What I am trying to accomplish is getting the body to move according to wherever the tip of the body is. So far this is what I've tried:

```
        if (ks.IsKeyDown(Keys.Up))
        {
            body.ApplyForce(new Vector2(0, -20),body.GetLocalPoint(new Vector2(0,0)));

        }
        if (ks.IsKeyDown(Keys.Left))
        {
            body.ApplyTorque(-500);
        }
        if (ks.IsKeyDown(Keys.Right))
        {
            body.ApplyTorque(500);
        }

```

The body rotates fine - but when I try making the body accelerate according to the tip of the body - assuming I have specified the tip correctly(I am pretty sure I haven't), it just spins around, as if I have applied Torque to it. Can anyone point me in the right direction of how to fix this problem?

# Answer
Apply the force to the objects center as suggested by Gajoo. Conviently WorldCenter is a property of the body class so.

```
Body.ApplyForce(forceDirection, Body.WorldCenter);

```

Also if you want to move the body in a specific direction you need to apply the force in that direction so "new Vector2(0, -20)" doesn't make any sense. To create a the unit vector that faces int the same direction as your body do the below.

```
var forceDirection = Vector2.UnitY;
var test = Matrix.CreateFromAxisAngle(new Vector3(0, 0, 1), Body.Rotation);
forceDirection = Vector2.Transform(facing, test);

```

Now simply scale the forceDirection vector to alter the speed.
> 1 votes

# Answer
ApplyForce does not work like that. The problem is you are always applying a force to the left down corner of your shape, with always same direction. here is a picture explaining it (I might be wrong about the corner the force is applied to but the idea is the same):

to fix this issue you should always apply the force to the center of your ship, and the rest is the same as explained in byte56 suggested. It means you need to rotate force vector **yourself** and then pass it to farseer
> 1 votes

# Answer
```
direction = body.GetWorldVector(new Vector2(0,1));

```

When using Farseer Physics calculating the direction isn't so hard. If your body starts off with it's tip point upwards you can find the direction by simply updating direction(as shown above) in your update loop, and then when the user presses the up-key simply apply(after calculating the velocity's as shown in this questions answered by Byte56:https://gamedev.stackexchange.com/questions/37623/move-sprite-in-the-direction-it-is-facing)

```
body.ApplyForce(velocity * -100);

```

Play with the values to get the desired output :)
> 1 votes

---
Tags: c#, 2d, xna-4.0, physics, farseer-physics-engine
---


# Question
Title: Farseer Physics for Xna missing ConvertUnits class
Im using Farseer Physics with Xna 4.0. Im following a starter guide. It said that to draw, I need to convert the meters to pixels with the ConvertUnits namespace. I looked through all of the engine, but I cant find the ConvertUnits class. Im basicly stuck without it. Where is it stored, or do I need another resource?

# Answer
> 3 votes
Starting with 3.x, FPE(Farseer Physics Engine) now uses the MKS (Meter-Kilogram-Second) system of units.

The ConvertUnits class can be found under Farseer Physics Engine 3.3.1 Samples XNA\Samples XNA\Samples XNA\ScreenSystem. ConvertUnits is a helper class that lets us switch between display units (pixels) and simulation units (MKS) easily.

This file can be downloaded here: http://farseerphysics.codeplex.com/releases/view/64108

Original Post at: http://farseerphysics.codeplex.com/discussions/247635

So you basically need to add the ConverUnits.cs file to your project, and you should be able to convert meters to pixels just fine :)

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


# Question
Title: Multi threaded game - updating, rendering, and how to split them
From the StackOverflow post (it was recommended I move this):

So, I'm working on a game engine, and I've made pretty good progress. However, my engine is single-threaded, and the advantages of splitting updating and rendering into separate threads sounds like a very good idea.

How should I do this? Single threaded game engines are (conceptually) very easy to make, you have a loop where you update -\> render -\> sleep -\> repeat. However, I can't think of a good way to break updating and rendering apart, especially if I change their update rates (say I go through the update loop 25x a second, and have 60fps for rendering) - what if I begin updating halfway through a render loop, or vice versa?

# Answer
> 6 votes
You're going to want to double/triple buffer any data necessary for rendering that gets altered in the update pass. That way you won't be rendering with something that's been partially changed. The reason you'll probably need to triple buffer is needing 1) the copy you're updating, 2) the last copy you updated fully, and 3) the copy that is currently being used for rendering that you don't want to change.

The hardest part is probably working out the best way to organise your data for this.

# Answer
> 4 votes
This website discusses the problem and has implemented a triple-buffer solution as Roger suggested:

http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part1/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part2/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part3/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part4/

It is quiet difficult to implement, but the website has both a source and binary distribution of the implementation if you're interested.

---
Tags: java, performance, game-loop, multithreading, efficiency
---


# Question
Title: How to separate my rendering from game loop?
If I have a (complex) operation that takes a long time for it to finish, for instance, a couple of seconds, my frame rate drops far below the acceptable. How could I still implement it while it is not messing up my frame rate?

# Answer
> 3 votes
Without using threads, here are two ways.

* do all at once (cLogic)
* using something I call a state machine (cLogicStateMachine)

---

Call cLogic::Update(), check if its member updating is TRUE, if so return or else turn it on. Do the logic. Before exiting the function, turn off updating.

---

In the state machine you do one thing at each frame. Leaving the state as it is afterwards. So it catch on there where you left off.

A possibility can be, make a variable that catches the time, do some iterations until 0.1 seconds has passed and leave, the states stay as they are.

---

Not familiar with cocos2-iphone myself I produced a pseudo-code-like example based on c++. As you are asking the principle, I think that would be okay. It surely can use optimizations.

```
class cLogicStateMachine
{
    cLogic()
    :   // initialize members
        Iterating( FALSE ),
        IteratorX( -1 ),
        IteratorZ( 0 ){};
    void    Update()
            {

                if( Iterating )
                {

                    ++IteratorX;
                    if( IteratorX > 31 )
                    {

                        IteratorX = 0;

                        ++IteratorY;
                        if( IteratorY > 31 )
                        {

                            // Reset
                            IteratorX = -1;
                            IteratorY = 0;
                            Iterating = FALSE;
                            return;

                        }

                    }

                    playfield[ IteratorY * 32 + IteratorX ] = TILE_TYPE_NONE;

                }

            }
    BOOL    Iterating;
    int     IteratorX;
    int     IteratorY;
};

class cLogic
{
    cLogic()
    :   // initialize members
        updating( FALSE ){};
    void    Update()
            {

                if( updating )
                    return;

                updating = TRUE;

                /* do logic */

                // loop around the current tile to check walkability
                for( int y = 0; y < 32; ++y )
                {

                    for( int x = 0; x < 32; ++x )
                    {

                        playfield[ y * 32 + x ] = TILE_TYPE_NONE;

                    }

                }
                /* end logic */

                updating = FALSE;

            };
    BOOL    updating;

};

class cMain
{
    cMain()
    : // initialize members
      m_timeUpdateGameLogic( 0.0f ){};
    void    update()
            {

                /* collect all data you need to know */

                m_timeUpdateGameLogic += elapsedTime;
                if( m_timeUpdateGameLogic >= 0.5f )
                {

                    m_timeUpdateGameLogic -= 0.5f; // set to 0 but without lagging

                    if( using_statemachine )
                    {

                        if( m_logic.Iterating == FALSE )
                        {

                            // start over
                            m_logic.Iterating = TRUE;

                        }

                    } else
                    // if using cLogic
                    {

                        m_logic.Update();

                    }

                }

                if( using_statemachine )
                {

                    m_statemachine.Update()

                }

                /*
                    handle other stuff like view movement
                    score update
                    and such
                */

            }
    void    render()
            {

                /* conclude the logic, i.e. render everything */

            }
    float               m_timeUpdateGameLogic;
    cLogic              m_logic;
    cLogicStateMachine  m_statemachine;

}

```

# Answer
> 4 votes
It is possible to separate the render thread from the update thread, but it is quiet difficult to make. You'll need a triple-buffer of the render state. For an explanation of the problem and solution check out:

http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part1/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part2/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part3/ http://blog.slapware.eu/game-engine/programming/multithreaded-renderloop-part4/

The site contains both source + binary distribution if you're interested.

# Answer
> 2 votes
Create separate threads for drawing and logic, if you want improved performance.

But, you can have `update()` and `render()` functions, which get called at different times. By doing this, you ensure that these two are *separated*, and that they do not depend on each other. That's the general direction you want to take, because it makes debugging a lot easier. Plus, once you've done that, creating separate threads for these things will be a piece of cake!

If you were a bit more specific and told us what problems are you having exactly, it would be easier to answer the question.

# Answer
> 1 votes
Hrm...

My first guess would be multithreading. For example, if you had your logic and render in the main loop, if logic takes a long time, you don't get anything rendered till it is done. With multiple threads, the render can be independant of the logic, and so evedn if the logic is bogged down, stuff still gets rendered, etc.

As per how to calculate it every 1/2 seconds, I am sure whatever libraries you are using contain the simple contraption of some sort of timing devices/timers, etc. Or, in the case the logic is threaded by itself, a sleep might also suffice.

The problem of ensuring the logic is completed by the time it must next be calculated might be tricky, depending on specifically what you are doing. You could: optimize the logic calculations, thread individual part of the logic (though I haven't actually used threads in a real application, so how to seperate but coordinate the logic, I don't know much on). Alternatively, perhaps you can either set a minimum calculation time (say 0.5 seconds) and give it as much time as it needs, or somehow otherwise coordinate the application to the time it takes.

---
Tags: c++, cocos2d-iphone, multithreading
---


title: How can I handle copyrighted music?

text:
# Question
Title: How can I handle copyrighted music?
I have a curious question regarding on musics used in music rhythm game. In Guitar Hero for example, they used all different music albums in one program. Then, each album requires to ask permission to the owner, composer of the music, or the copyright owner of the music. Let's say, if you used 15 albums for the music rhythm game, then you have to contact 15 copyright owners and it might be that, for the game developer, that the profit earned goes to the copyright owner or owner of this music. For the independent game developers, was it okay if either used the copyright music by just mentioning the name of the singer included in the credits and in the music select screen or use the non-popular/old music that about 50 years ago? And, does still earn money for the indie game developers by making free downloadable game?

# Answer
> 10 votes
Neither being an indie developer, nor releasing game for free, doesn't grant you some additional rights implicitly. You can either need to have agreement with rights owner, or use music that is in public domain or other license (like CC license) that allows some sort of free usage.

Also as Markus correctly mentioned in comment, Public Domain is a tricky thing. So I guess you are more limited in classics than it may seems.

# Answer
> 8 votes
Distributing copyrighted music without a license from the copyright owner is a violation of copyright, and is illegal in most parts of the world.

Yes, it's still a violation of copyright even if you distribute it for free.

Yes, it's still a violation of copyright even if you credit the artist.

Yes, it's still a violation of copyright even if you hold your breath until you go blue.

Distributing copyrighted music without a license from the copyright owner is a violation of copyright.

**period**.

---
Tags: game-industry, music, copyright
---


title: In-App Billing Library for Android Game

text:
# Question
Title: In-App Billing Library for Android Game
I'm trying to add in-app purchases into my Android game and it having some trouble figuring my around the Google Play Billing. Can anyone refer me to a good open source reference for how to do that?

# Answer
I came across an open source resource that simplifies in-app billing on Android. Take a look at http://soom.la. They also have a reference app that shows you how to use it. Here is the sample app on Github

I'm using Unity, they also provide a free plugin on the Unity Asset Store: https://www.assetstore.unity3d.com/en/#!/content/6103.
> 3 votes

---
Tags: android, mobile, economy, microtransactions
---


# Question
Title: Has anyone tried using one of those BAAS providers to create mobile games?
I'm hearing a lot about different companies offering back-end as a service (BAAS) for mobile apps but it seems like none of them are very successful with mobile games. Is there any reason why not outsource the server to a provider.

The premise here is that the game does need a back-end to implement multiplier ans social functions.

# Answer
In my opinion there are a few types of mobile games.

* **Single player / action / arcade puzzle -** these doesn't really require a server side anyway and you can go a long way with openfeint or gamecenter to implement the social functions.
* **Multiplayer / MMO / MMORPG -** These require a strong backend with very quick response times and the BAAS solutions are really not cut out for that.
* **Turn based Multiplayer / Resource Management MMO -** These are server based games that are ok with slower response times but require such a huge investment in backend that what the BAAS companies provide is insignificant.
> 8 votes

---
Tags: android, ios, multiplayer, server
---


# Question
Title: how to calculate intersection time and place of multiple moving arcs
I have rocks orbiting moons, moons orbiting planets, planets orbiting suns, and suns orbiting black holes, and the current system could have many many layers of orbitage.

the position of any object is a function of time and relative to the object it orbits. (so far so good).

now I want to know for a given 2 objects(A,B), a start time and a speed, how can I work out the when and where to go. I can work out where A and B is given a time. so i just need.

1: direction to travel in from A to B(remember B is moving(not in a straight line)) 2: Time to get to b in a straight line.

travel must be in a straight line with the shortest possible distance.

as an extension to this question, how will i know if its better to wait, EG is it faster to stay on object A and wait for a hour when the objects may be closer, than to set off from A to B at the start.

Cheers, it hurt my brain.

# Answer
> 1 votes
That's not so bad if you know the position of A and B at all times. Example:

A is at the origin. B is traveling around the origin at a distance of 1. (ie, it's orbit is the unit circle) Let Y be the object leaving A.

Let the speed of B be such that every second B crosses an axis. So the period of B is 4 seconds. Therefore the position of B at any given point in time is: (cos(t * pi/2), sin(t * pi/2))

Let the speed of Y be such that every second Y can travel s distance. So after one second, if travelling along the positive x axis, Y will be s away from A. Therefore A creates another "orbit" to how far it can go every second based on:

sqrt(x^2+y^2) = s\*t

Now you just need to determine what value of t is required to determine when these two things will intersect.

This is a very simple case but it will more or less work for any 2D situation you would just obviously need to change the numbers around. Since you already have a function for B you can just replace mine with yours. The other equation is the same for every case.

Now if you add another dimension and introduce physics modeling more of how our world works then this becomes nontrivial and could be very difficult and I'd just avoid it entirely.

You'll know to wait if it takes longer to travel at the current position than it does at the time it takes to travel at a later position plus the wait time.

# Answer
> 0 votes
If your bodies are subject to complex orbits it may well be difficult or impossible to solve using a closed-form expression (solve an equation to get the desired results.

One approach would be to perform a mathematical simulation over time to arrive at a solution.

In your case, a body leaving A at a time t0 travelling in a straight line with velocity v will be somewhere on the circumference of a circle or (sphere in 3D) with radius vt (t=time since leaving). The centre of the circle will be the position of A at the time of launch (Apos(t0)). You can imagine this circle like a ripple on a pond getting bigger over time)

Assuming you can calculate the position of B at time t+t0 (Bpos(t+t0)), you can create a simulation with a loop to find out the earliest time that the growing circle intersects B's path

```
searching=true
t=0
while(searching){
    if (distance between Apos(t0) and Bpos(t0+t)) < v*t then{
        searching=false //found a solution
        target_position=Bpos(t0+t) // can be used to find direction to head in
        time_to_reach_B=t
    }
    else
        t+=delta_t //a small time step (smaller = more accuracy)
}

```

You will of course have to add code to prevent an infinite loop in the case that there is no solution (or no solution to be found in reasonable time).

Depending on the complexity or B's motion and the value of delta\_t, this algorithm is not guaranteed to find the ideal solution in **every** case, but should work well for the vast majority of cases.

---
Tags: mathematics, algorithm, intersection, orbit
---


# Question
Title: Shuffle tiles position in the beginning of the game XNA Csharp
I'm trying to create a puzzle game where you move tiles to certain positions to make a whole image. I need help with randomizing the tiles start position so that they don't create the whole image at the beginning. There is also something wrong with my offset, that's why it's set to (0,0). I know my code is not good, but I'm just starting to learn.

# My start-up tile positioning code

```
        spriteBatch = new SpriteBatch(GraphicsDevice);
        PictureTexture = Content.Load<Texture2D>(@"Images/bildgraff");
        FrameTexture = Content.Load<Texture2D>(@"Images/framer");

        //Laddar in varje liten bild av den stora bilden i en array

        for (int x = 0; x < 4; x++)
        {
            for (int y = 0; y < 4; y++)
            {

                Vector2 position = new Vector2(x * pictureWidth, y * pictureHeight);

                position = position + Offset;

                Rectangle square = new Rectangle(x  * pictureWidth, y * pictureHeight, pictureWidth, pictureHeight);

                Square frame = new Square(position, PictureTexture, square, Offset, index);
                squareArray[x, y] = frame;

                index++;
            }
        }

```

# For reference, here is the square class:

```
class Square
{

    public Vector2 position;
    public Texture2D grafTexture;
    public Rectangle square;
    public Vector2 offset;
    public int index;

    public Square(Vector2 position, Texture2D grafTexture, Rectangle square, Vector2 offset, int index)
    {
        this.position = position;
        this.grafTexture = grafTexture;
        this.square = square;
        this.offset = offset;
        this.index = index;
    }

    public void Draw(SpriteBatch spritebatch)
    {
        spritebatch.Draw(grafTexture, position, square, Color.White);
    }

    public void RandomPosition() {  }

    public void Swap(Vector2 Goal )
    {
        if (Goal.X > position.X)
        {
             position.X = position.X + 144;
        }
        else if (Goal.X < position.X)
        {
            position.X = position.X - 144;
        }
        else if (Goal.Y < position.Y)
        {
            position.Y = position.Y - 95;
        }
        else  if (Goal.Y > position.Y)
        {
            position.Y = position.Y + 95;
        }
    }
}

```

# Answer
The easy way is to shuffle from a solved puzzle to a not solved puzzle. Don't just swap a random tile with another random tile, you might not be able to get back to the orginal (you created an unsolvable puzzle!)

The hard way involves some math, see http://mathworld.wolfram.com/15Puzzle.html
> 4 votes

# Answer
Not going to read your code. But I think it's important that you understand the problem conceptually, then should have no problems implementing it.

The easiest way for you to shuffle your tiles (not the most efficient -- but the easiest) is to:

1. Pick a random x and random y coordinate within your x and y ranges respectively, calling this coordinate loc1;
2. Repeat, calling this loc2;
3. Swap the contents between loc1 and loc2.
4. Repeat steps 1-3 as many times as necessary.

That's the naive approach, because it will often pick an already-shuffled tile to shuffle again. That means it will take more CPU time to get a good, even shuffle. But I would try it like this first. Then if you need to be more efficient, you can record exactly which locations have already been touched on by the shuffle algorithm, in a collection (list or hashmap/dictionary) and just avoid shuffling those again. That is, each time you do a shuffle between two tiles, you just push those locations into the collection, and on each subsequent shuffle you're going to only shuffle tiles that aren't in that collection. If you use a list, it will be a little slower, as you will have to run through many list elements to check what's already been shuffled.

On the other hand, if you use a hash, you may have the hash equality problem, which is easiest solved by assigning each tile a unique ID (or, for the more adept coder, use bitshifting to combine x & y into a unique key for each tile position). I suggest you use a list for now. It's likely you don't have hundreds of thousands of tiles to shuffle :)

EDIT: Another way is to push all your tiles into a linear list, then just do pairwise shuffle of individual elements in the list, then push those sequentially back into the 2D tile layout, row by row or column by column.
> 1 votes

---
Tags: xna, c#, tiles, random
---


# Question
Title: Building a touch event driven UI from scratch: what algorithms or data types?
I have a touch display. As input I can receive the coordinates and how many touch points are in use, basically I just get an X,Y couple for every touch event/activated point at a customizable rate.

I need to start from this and build my own callback system to achieve something like `Object.onUp().doSomething()` meaning that I would like to abstract just the detection of some particular movements and not having to deal with raw data: what algorithms can be useful in this case? What statements? Is there some C++ library that I can dissect to get some useful info?

Would you suggest the use of an heuristic algorithm?

# Answer
Touch screens are not inherently more difficult than mice or keyboards. Heuristics are not required in any sense. It's just a matter of comparing data from one tick to the next.

Simply maintain a structure to hold the previous raw data. Each frame, store the last frame's data into it, and then fetch new data. An up event is the former presence of a touch datum while the current frame lacks it. Motion is simply the current touch position minus the first.

Using those determinations, you can build up higher order functions like detection of gestures, multitouch patterns, etc.

Don't overthink it just because it's a touch screen. :)
> 1 votes

---
Tags: c++, events, touch
---


# Question
Title: Creating a newspaper that effects the game's economy?
I am writing a game in Objective C/cocos2d where a newspaper is a central part of what controls or rather effects the game's world economy as well as what a city might do (such as increase X, reduce Y)

The newspaper is a bit like a "Chance card" in Monopoly, it has an effect on something.

My question is, what is the best way to do write a newspaper that has both a random and specific effect within the game.

Would the best strategy be to write out all the things a newspaper can affect, a PLIST of headlines (with placeholders).

I think Tiny Tower uses a PLIST of events and it randomly picks an event, but I'm not sure how it actually parses it because certain events do different things.

But then how do I parse all the scenarios that a newspaper can deliver? A big switch statement seems very long and complicated to do.

I am wondering if there is a simpler way to handle this kind of thing.

Related to this is that there might be no news that day and I'm not sure what the newspaper should display, should it just display the last headline?

So, in summary.

1) A newspaper generates a headline, it affects different things, such as the world economy, prices, how city reacts

2) I need the newspaper to generate headlines (although there may be days when there are no headlines at all), but I am not sure how to parse it without using a big-ass switch statement.

Thanks in advance.

# Answer
> -1 votes
In order to "parse it without a big-ass switch statement" you'd use functors AKA function pointers. But since you do not mention which language you are using (PLISTS -\> Objective C?) I cannot tell you whether you have those available in your language of choice.

Here is an article on how function pointers work (Objective C).

If you are using a language which does not support function pointers, then you would use the Strategy Pattern instead.

---
Tags: random, events, special-effects
---


# Question
Title: Game based on Ajax polling for 12 players
I am planning on writing a small browser game.

The webserver is a shared server, with no root / install possible.

I want to use AJAX for client/server communication. There will be 12 players.

So each player would be polling the server for the current game status every X milliseconds (let's say 200ms). So that would be 200ms x 12 players x 5 = 60 requests per second

Can Apache handle those requests?

What might be the bottlenecks when using this attempt?

# Answer
> 2 votes
Apache can certainly handle the requests, but you will want to do some careful planning to ensure that things work as expected.

In order to handle such a high rate of requests with minimal latency, clients MUST be using HTTP keepalives. Keepalives are sometimes disabled in web servers.

You will also want to be very careful on the client-side to not issue a new request if the previous one is still pending. You might also want to disregard a response if it took too long.

If your game requires this request rate, it may be a good idea to limit it to players with low latency to your server (say \< 50ms) which will prevent players outside your geographical region (you could always set up new servers for those players elsewhere).

Personally I would always recommend using a FastCGI backend for Apache (or maybe Nginx or some other web server). Then you will need a pool of processes / threads to run your FastCGI. This does not need to run as root (and indeed, should not).

---

In the longer term though, if the client browsers support it, it might be a good idea to use Websockets.

---
Tags: javascript, server, php, polling, ajax
---


# Question
Title: Level and Player objects - which should contain which?
I've been working on a several simple games, and I've always come to a decision point where I have to choose whether to have the Level object as an attribute of the Player class or the Player as an attribute of the Level class.

I can see arguments for both:

The Level should contain the player because it also contains every other entity. In fact it just makes sense this way: "John is in the room." It makes it a bit more difficult to move the player to a new level, however, because then each level has to pass its player object to an upcoming level.

On the other hand, it makes programming sense to me to leave the player as the top-level object that is persistent between levels, and the environment changes because the player decides to change his level and location. It becomes very easy to change levels, because all I have to do is replace the level variable on the player.

What's the most common practice here? Or better yet, is there a "right" way to architecture this relationship?

# Answer
> 6 votes
There is another option. The player and the level are both members of the game object.

However, I think the most common practice is to make the player an object inside the level. This has numerous benefits. For example, the level will process collisions between objects. Adding all the objects into the same level pool allows you to reuse the collision code with the player object too. It allows the player object to more easily interact with other objects in the level. The code you use for moving the player from one level to another could also be used for moving other game objects from one level to another. And so on and so on.

I don't think "because it's a little more difficult" is a good enough reason to break the common object oriented structure.

It's good to follow the standard structure even when you're the only one working on the code. Easy to understand and *expected* code structure is crucial if you were to ever have someone else work on your code. Keep in mind, that "someone else" could be *you* a few years from now when you're looking back at your code and wondering what the heck you were doing.

# Answer
> 5 votes
There's certainly no "right" way to approach this problem, but there are better ways based on software engineering guidelines and principles. From what you've described, I'd approach the problem this way:

A *level* contains a set of *agent* objects that exist within the level. Agents could be any kind of character or other entity, player-controlled or not.

The *player* object deals with the actual human player sitting at the keyboard, things like score, name, lives left, et cetera. It might also (directly or indirectly via another interface) manage the transformation of keyboard or controller input into in-game responses, and it can accomplish this by maintaining a reference to the *currently-controlled agent* in a level.

In this fashion the level object and the player object don't actually know about each other directly at all; the level just knows it deals with a bunch of agents, and the player knows it deals with one particular agent that is the one the player is directly controlling right now.

There are three key principles at work here:

1. Minimizing the responsibilities of an interface. In an ideal world, an interface would have but one task.
2. Aggregation of functionality rather than inheritance. Instead of having the player *be* an agent, the player contains a reference to an agent it controls. This tends to also help you adhere to the idea that an inherited interface should be substitutable with its base interfaces, because a player probably does a lot more things, and a lot differently, than any other actor in the game.
3. Logical lifetime separation. As you note, the player should persist outside the lifetime of the actual level, so while it would be okay for a player to refer to a "current level" much like the player could refer to the "currently controlled agent," you don't want the opposite where the player is potentially destroyed when the level is, thus requiring a complicated process of serializing and deserializing transferrable state between levels.

# Answer
> 2 votes
I want to emphasize that there are many ways to solve this and that you shouldn't fool yourself into believing that one size fits all with this problem.

This is a little subjective and anecdotal from my own game, but here's how I view it. The world (level) and the beings that populate it (entities) are separate "things". That is, entities still exist even if the world doesn't and vice versa (ignoring realism for the sake of argument).

That said, I tend to structure my object "ownership" in terms of a hierarchy of what populates what. For example, while the world doesn't own the player (or any other entity), the player does populate the world and is subject to its rules. A player (and other entities) in my game are managed by a third party. This third party extracts necessary data from both the level and the player when they need to interact (collisions, events, etc...).

So really that was a long winded way of saying that another option is to do neither of your suggestions.

---
Tags: levels, objects, single-player
---