title: Who controls my player's movement?

text:
# Question
Title: Who controls my player's movement?
In my game, does my player object control the movement, or does the map object control it? (Or some other object?)

The player doesn't know about the map's contents to stop at solids, interact with objects etc. Am I doing it wrong?

I'm currently dispatching data from a virtual joypad.

**EDIT:**

What if I dispatched movement notifications to my player and had it check with the map before moving, but the player would do the actual moving? Would that work?

**EDIT2:**

At this point I'm thinking about a top down game. Just to clarify, I want the player to move in 4 directions, not 8, and to be centered on the tile which they are standing on.

# Answer
> 9 votes
My approach to this is two-fold

* First, I abstract the source of control for every game object. That lets me implement a "user controlled entity", which takes input from gamepad/keyboard/mouse/etc for the player entity, and implement AI routines for NPCs.
* Second, each entity can only express an "intent" ... so the output from the abstracted control object in point 1 only says, "I want to move in that direction". That intent is then implemented by some other routine which checks against map details, does collision, etc.

# Answer
> 1 votes
Depends on the type of game. For a platformer, your movement is basically a large series of hacks, comprised of a lot of ray tests and highly specialized logic. For a top-down action game, you should have a basic physics/collision system that's independent of any particular type of game object, and player controls just set velocities/forces that move the avatar in the indicated direction. Other types of games have other types of controls and use less or more physics engine as appropriate.

In general, though, you have some kind of concept of a physics object. Players, enemies, items, etc. all have a physics component. This component in tandem with the physics engine (which knows about the level layout, among other things) will "correct" motion in response to collision. The player component then responds to movement requests by setting forces, which push the player around, and the physics component deals with things like "the object is moving into a wall, push it back out again and adjust accordingly."

If you provide more information on what exactly you're trying to do, someone may be able to provide a more detailed answer.

# Answer
> -1 votes
you can implement your object control in map calss, but that would create some god object and it'll be too difficult to debug or add features your program in future. there are two approches for this problem :

1- one is to handle all the inputs in the player class, and then ask map to move your player as player calculated, this can also be applied for any other dynamic or static objects in your scene. note that in this apprich map class only check for collision or other similar things , and doesn't care how or why is the object moving.

2- you can also share all map data with other dynamic classes (using physics engine and creating an object for every child of map is a way of doing this) and check all the thing you have to consider while moving objects inside their own class.

the first approch is much more simpler and take less time to implement, because you consider all your object the same and move them in a same manner, but in the second aproch you have much more flexibility with your obejects moving (for example you can make some object to ignore collsion)

# Answer
> -1 votes
There is really no right way to do this, because you are talking collisions and character control it really boils down to exactly the problem you are trying to solve, as no matter your approach you are going to have to look at your game mechanics and see if it fits ( order of resolution etc.. ).

My approach to this problem and as it seems you want to keep a certain level of abstraction would be to different layers that process the player data, so if your player controlled object has a velocity and a direction then these would be updated based on the input, these inputs are not checked against anything, the input knows about the player object and simply updates its values, this would be your first layer.

After this first stage is done, your map system then needs to scan through the data and validate it, at this point all controller input has been resolved, the map can then decide to accept or change the forces ( velocity and direction ) associated with player entity based on collisions, wind, whatever can affect the player movement, this is your second layer that affects the data.

The last and final stage would be to simply update any entities position based on their direction and velocity ( as is ), this movement is assumed correct, this could mean the velocity is 0 because he collided with a wall, or he is now being taken on the opposite direction by a river he stepped in.

The key in this type of solution is to have different layers that affect your data, after each successive stage your data is assumed correct and valid for all previous stages, which means each processing stage could be designed to be plugged in and out at run time and even re-ordered.

---
Tags: architecture, cocos2d-iphone, movement
---


# Question
Title: How do i get my tilemap to move at the same speed as my character
I have a little problem in my solution, i'm trying to make a pretty big map for the players to walk around in.

I decided to use a tile-engine, but when I move my character it moves faster than my tile-engine draws the ground so I end up catching up to the edge. It's quite hard to explain so I've added the solution at the end. Just keep walking down or right and you'll see the problem: while the world keeps generating slowly my character moves faster. Sounds like it's just a matter of changing my characters movement speed, but that doesn't help at all.

This is the code for drawing the tiles

```
 Vector2 firstSquare = new Vector2(cam.Pos.X / Tile.TileWidth, cam.Pos.Y / Tile.TileHeight);

        //Vector2 worldFirstSquare = cam.GetWorldPosition(firstSquare);
        int firstX = (int)firstSquare.X;
        int firstY = (int)firstSquare.Y;

        Vector2 squareOffset = new Vector2(cam.Pos.X % Tile.TileWidth, cam.Pos.Y % Tile.TileHeight);
        //Vector2 worldSquareOffset = cam.GetWorldPosition(squareOffset);
        int offsetX = (int)squareOffset.X;
        int offsetY = (int)squareOffset.Y;

        if (Mouse.GetState().LeftButton == ButtonState.Pressed)
        {
            Console.WriteLine(firstSquare + " " + squareOffset);
        }

        for (int y = 0; y < squaresDown; y++)
        {
            for (int x = 0; x < squaresAcross; x++)
            {
                if(firstY >=0 && firstX >=0)
                foreach (int tileID in myMap.Rows[y + firstY].Columns[x + firstX].BaseTiles)
                {
                    spriteBatch.Draw(
                        Tile.TileSetTexture,
                        new Rectangle(
                            (x * Tile.TileWidth) - offsetX, (y * Tile.TileHeight) - offsetY,
                            Tile.TileWidth, Tile.TileHeight),
                        Tile.GetSourceRectangle(tileID),
                        Color.White);
                }
            }
        }

```

This is for moving my character

```
if (keystate.IsKeyDown(Keys.W))
        {
            if (keystate.IsKeyDown(Keys.A))
            {
                _PlayerRect.Y -= _PlayerSpeed -2;
                _PlayerRect.X -= _PlayerSpeed -2;
            }
            else if (keystate.IsKeyDown(Keys.D))
            {
                _PlayerRect.Y -= _PlayerSpeed -2;
                _PlayerRect.X += _PlayerSpeed -2;
            }
            else
            {
                _PlayerRect.Y -= _PlayerSpeed;
            }
        }
        else if (keystate.IsKeyDown(Keys.S))
        {
            if (keystate.IsKeyDown(Keys.A))
            {
                _PlayerRect.Y += _PlayerSpeed -2;
                _PlayerRect.X -= _PlayerSpeed -2;
            }
            else if(keystate.IsKeyDown(Keys.D))
            {
                _PlayerRect.Y += _PlayerSpeed -2;
                _PlayerRect.X += _PlayerSpeed -2;
            }
            else
            {
                _PlayerRect.Y += _PlayerSpeed;
            }
        }
        else if (keystate.IsKeyDown(Keys.A))
        {
            _PlayerRect.X -= _PlayerSpeed;
        }
        else if (keystate.IsKeyDown(Keys.D))
        {
            _PlayerRect.X += _PlayerSpeed;
        }

        playerPosition.X = _PlayerRect.X;
        playerPosition.Y = _PlayerRect.Y;

```

And this is the update for my camera

```
Vector2 cameraDirection = Vector2.Zero;
        const int TO_MOVE_SIDE_DISTANCE = 300; // the distance to the side required to move.

        Vector2 playerScreenPosition = cam.GetScreenPosition(new Vector2(
                    player.PlayerRect.X, player.PlayerRect.Y));
        Rectangle playerScreenRect = new Rectangle((int)playerScreenPosition.X,
                    (int)playerScreenPosition.Y, player.PlayerRect.Width, player.PlayerRect.Height);

        //We make the camera follow the player if he goes too close to the sides.

        if (playerScreenRect.Left < TO_MOVE_SIDE_DISTANCE) // move to the left
        {
            --cameraDirection.X;
        }
        if (playerScreenRect.Right > GraphicsDevice.Viewport.Width - TO_MOVE_SIDE_DISTANCE) // move to the right
        {
            ++cameraDirection.X;
        }
        if (playerScreenRect.Top < TO_MOVE_SIDE_DISTANCE) // move up
        {
            --cameraDirection.Y;
        }
        if (playerScreenRect.Bottom > GraphicsDevice.Viewport.Height - TO_MOVE_SIDE_DISTANCE) // move down
        {
            ++cameraDirection.Y;
        }

        cam.Pos += cameraDirection * player._PlayerSpeed; // move with the player.

```

The Solution is here.

# Answer
> 2 votes
The easiest way to solve this issue is, to put it simply, draw more :-) it's usually ok if you draw stuff just outside of the viewport. That reduces instances where the visible area "catches up" with the edge of the screen before it redraws.

You can of course get more complex with it where you increase the drawing distance only in the direction that you're moving ... but usually this is overkill.

# Answer
> 2 votes
Your code is really hard to read, and I can't get it to run, so I'm not sure what is actually going on.

But as far as I can tell you are both moving around the camera and changing the place where the tiles are drawn depending on player position, you should only do one of those.

Edit: I got it running, no performance problems, this is a simple case of camera/object position mismatch.

---
Tags: xna, c#, software-engineering, tiles, movement
---


title: How would I use GLM for Bullet Physics?

text:
# Question
Title: How would I use GLM for Bullet Physics?
Right now im working on my c++ game, and im having alot of trouble using GLM and Bullet Physics to create my world correctly.

The main problem is that when i export my physics with Blenderv2.57, and export my models for GLM, the models never line up with the physics correctly...

Im wondering if there are any model loaders that would be good to use with Bullet Physics, and I can export the vertices,texture coords, etc. from Blender to be loaded and used as btTriangleMeshes..

I managed to make a `btBvhTriangleMesh` with my GLM model, but I think its falling, or my character is not picking it up correctly..

heres the code:

```
void BulletifyContinent(GLMmodel* mesh,float x,float y,float z,float scale)
{
    btTriangleMesh* trimesh = new btTriangleMesh();
    for(int t=0;t<mesh->numtriangles;++t)
    {
        GLuint index0 =3*mesh->triangles[t].vindices[0];
        GLuint index1 =3*mesh->triangles[t].vindices[1];
        GLuint index2 =3*mesh->triangles[t].vindices[2];

        GLfloat* p0 = &mesh->vertices[index0];
        GLfloat* p1 = &mesh->vertices[index1];
        GLfloat* p2 = &mesh->vertices[index2];

        btVector3* v0 = new btVector3( p0[0], p0[1], p0[2] );
        btVector3* v1 = new btVector3( p1[0], p1[1], p1[2] );
        btVector3* v2 = new btVector3( p2[0], p2[1], p2[2] );
        *v0 *= scale;
        *v1 *= scale;
        *v2 *= scale;
        trimesh->addTriangle( *v0, *v1, *v2 );
        ///trimesh->addTriangle(mesh->triangles[t].vindices[0]*100,mesh->triangles[t].vindices[1]*100,mesh->triangles[t].vindices[2]*100);
    }
    btCollisionShape* shape = 0;
    bool useQuantization = true;
    shape = new btBvhTriangleMeshShape(trimesh,useQuantization);
    btDefaultMotionState *StillStateMOT = new btDefaultMotionState(btTransform(btQuaternion(0,0,0,0),btVector3(x,y,z)));
    btScalar Mass = 1;
    btVector3 FallInertia(0,0,0);
    btRigidBody::btRigidBodyConstructionInfo StillRigidCI(Mass,StillStateMOT,shape,FallInertia);
    btRigidBody *ContiRigid = new btRigidBody(StillRigidCI);
    PhysicsWorld->addRigidBody(ContiRigid);

```

Edit 1:

```
btScalar Mass = 1;
btVector3 FallInertia(0,0,0);
// This line is missing in your code
shape->calculateLocalInertia(Mass, FallInertia);
btRigidBody::btRigidBodyConstructionInfo StillRigidCI(Mass,StillStateMOT,shape,FallInertia);
btRigidBody *ContiRigid = new btRigidBody(StillRigidCI);
PhysicsWorld->addRigidBody(ContiRigid);

```

Edit 2:

There is no need to create the bullet vertices on the heap with new:

```
btVector3 v0( p0[0], p0[1], p0[2] );
btVector3 v1( p1[0], p1[1], p1[2] );
btVector3 v2( p2[0], p2[1], p2[2] );
v0 *= scale;
v1 *= scale;
v2 *= scale;
trimesh->addTriangle( v0, v1, v2 );

```

Edit 3:

This is not a proper identity quaternion:

```
btDefaultMotionState(btTransform(btQuaternion(0,0,0,0),btVector3(x,y,z)));

```

either do it this way:

```
btTransform trans;
trans.setIdentity();
trans.setOrigin(btVector3(x,y,z));
btDefaultMotionState *StillStateMOT = new btDefaultMotionState(trans);

```

or by passing a proper identity quaternion either yourself:

```
btDefaultMotionState *StillStateMOT =
    new btDefaultMotionState(btTransform(btQuaternion(0,0,0,1),btVector3(x,y,z)));

```

or using quaternion's identity member function:

```
btDefaultMotionState *StillStateMOT =
    new btDefaultMotionState(btTransform(btQuaternion::getIdentity(),btVector3(x,y,z)));

```

# Answer
> 2 votes
> What would be a good model loader for Bullet Physics?

Bullet has a build-in model/world-loader. Export everything in blender to `.bullet` and simply load it using `btBulletWorldImporter`

Here is a wiki explaining the details

# Answer
> 0 votes
> And when doing so, the models that are textured do not line up with the collision meshes that the .bullet file provides

How much off are they? Bullet adds a little margin to the boundaries of each body depending of the collision shape, that's ok and pretty small (~0.04) This is what the Docs say:

**Collision Margin**

*Bullet uses a small collision margin for collision shapes, to improve performance and reliability of the collision detection. It is best not to modify the default collision margin, and if you do use a positive value: zero margin might introduce problems. By default this collision margin is set to 0.04, which is 4 centimeter if your units are in meters (recommended).*

*Dependent on which collision shapes, the margin has different meaning. Generally the collision margin will expand the object. This will create a small gap. To compensate for this, some shapes will subtract the margin from the actual size. For example, the btBoxShape subtracts the collision margin from the half extents. For a btSphereShape, the entire radius is collision margin so no gap will occur. Don’t override the collision margin for spheres. For convex hulls, cylinders and cones, the margin is added to the extents of the object, so a gap will occur, unless you adjust the graphics mesh or collision size. For convex hull objects, there is a method to remove the gap introduced by the margin, by shrinking the object. See the Demos/BspDemo for this advanced use*

---
Tags: opengl, c++, 3d-meshes, blender, bullet-physics
---


title: Using index arrays with OpenGL VBOs

text:
# Question
Title: Using index arrays with OpenGL VBOs
I've recently started reading about VBOs.

If, for example, I want to draw a cube using VBOs, can I use one VBO to hold the coordinates for the 8 vertices, and another one as an index array, to specify the order in which the vertices are drawn?

If it's possible I'd appreciate some help on the matter, or a link to good tutorial you may know on the subject.

Thanks.

# Answer
> 2 votes
You want to do something like:

```
glBindBuffer(GL_ARRAY_BUFFER, vertex_id);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, index_id);
glDrawElements(GL_TRIANGLES, num_indices, index_type, 0 /*index_offset*/);

```

where index\_type is something like GL\_UNSIGNED\_SHORT, depending on what kind of data your index buffer contains.

This asumes you have created your two buffers and filled them with data already, and are using the builtin glsl attributes or fixed function pipeline. If you have specified your own attribs in the vertex program you will need to call

```
glBindAttribLocation(program_id, 0 /*index*/, "position");

```

before linking the program to register position as attrib 0, and then call

```
glVertexAttribPointer(0 /*index*/, 3 /*num_elems*/, GL_FLOAT, GL_FALSE, 0, 0);

```

Filling is done with

```
glGenBuffers(1, &vertex_id);
glBindBuffer(GL_ARRAY_BUFFER, vertex_id);
glBufferData(GL_ARRAY_BUFFER, num_bytes, data, GL_STATIC_DRAW);

```

Same thing for index data, but with GL\_ELEMENT\_ARRAY\_BUFFER as target instead. You can change GL\_STATIC\_DRAW to something else depending on your usage patterns.

# Answer
> 1 votes
From OpenGL.org :

```
Vertex data can be either vertex attributes and/or indices.'

```

So yes, you can store vertices and indices on your VBO's.

NeHe tutorials are generally a good resource, for tutorials, maybe you can find your joy here.

---
Tags: opengl, vertex-arrays
---


# Question
Title: Creating a full-screen window in Windows API
I've got a Windows API Window. I've managed to make it windowed, and "fullscreen windowed". But I can't seem to make the window just full-screen- for example, even if I specify `WS_POPUP`, I can still freely move the cursor to my second screen. However, if I launch full-screen games, they don't permit it, and exist only exclusively or minimized. How can I make a window that behaves this way?

Edit: Excuse me. Limiting the mouse movement was just one example of how a full-screen window behaves differently to a non-fullscreen window, I'm not looking for how to limit the mouse movement.

Or is this *set* in the D3DPRESENT\_PARAMETERS, rather than just communicated?

# Answer
> 1 votes
Yeah, D3DPRESENT\_PARAMETERS has a BOOL called "Windowed" in it; you want to set that to false at the time you make your call to CreateDevice on your IDirect3D9 pointer.

# Answer
> 1 votes
Limiting the mouse movement has previously been discussed here: Mouse aim in an FPS

---
Tags: c++, directx9, winapi
---


# Question
Title: Is it possible to develop games using Google's App Inventor?
Google's App Inventor is a WYSIWYG application development environment for Android. It allows you to control logic of your program using jigsaw type pieces.

* Is it possible to develop games using this technology?
* Are there any obvious potential pitfalls?
* What are the limitations of using this technology as compared to programmatic development for Android (such as using Java)?

A screenshot showing how behaviour can be controlled using the blocks editor:

# Answer
> 3 votes
Of course it is possible to develop basic games like the one given in the tutorial. http://appinventor.googlelabs.com/learn/tutorials/molemash/molemash.html

High end graphical games are difficult to create using this app since it requires advanced programming knowledge.

# Answer
> 2 votes
Possible - Sure why not.

Pitfalls - Depending on the blocks provided you may not be able to everything you want. I haven't investigated theirs but other WYSIWYG program builders I have seen put out very poorly performing apps.

Limitations - Limited in what you will be able to create. (I doubt they put a high performance 3d engine in there.) If you aren't capable of building what you want from their pieces then you are out of luck.

# Answer
> 1 votes
As @Vaishakh said, there are games for App Inventor, including Mole Mash (which I wrote). I've also written a game in which you can move a sprite by tilting the phone, having it chase or avoid other sprites.

@stonemetal was right on about the pitfalls and limitations. At least for now, there's no way of extending App Inventor, so if you want to do something not built in to the system, such as 3D graphics, you are totally out of luck. There are also limits on the language, such as the inability to pass a component as a parameter or to have local variables, which provide a practical, if not theoretical, limit on the size of a program. The App Inventor implementation is also not optimized for high-performance games.

I'd recommend App Inventor as a way to help someone new to computing or intimidated by the SDK to get started with creating games. It can also be good for creating mock-ups or prototypes. Some games (such as quizzes) can be implemented just fine in App Inventor, but I'd recommend the Java SDK if you want to build a complex game with lots of objects and high performance. The App Inventor team (which I'm part of) has just released a library to help ease the transition from App Inventor to the Java SDK \[http://groups.google.com/group/app-inventor-instructors/browse\_thread/thread/10a64e64b7886afb\].

# Answer
> 0 votes
It's most definitely possible, and I'd wager that someone has already done it. The biggest question I can think of is how to manage a big project, I guess that is also quite possible, but you might need some adjustment of your usual methods to make it work smoothly.

In any case, I say go for it, the best way to find out what the tool can do is to try it out.

---
Tags: android, tools
---


title: Loading data for an RPG

text:
# Question
Title: Loading data for an RPG
I'm creating a small text RPG as a way to practice python and I'm running into a question about how to load data. The game is a wild west game, though that isn't too relevant, and I need to store lists of weapons and their properties, as well as lists of characters, scenarios, etc. I've got a good idea of how to represent this data as classes but I'm not as clear on how to store and load the data.

My main question revolves around the relationship between data and classes. I have read through some posts here on SE and many of them relate to storage, so I have some good information there.

When should I load that data in? For example, the player chooses from several weapons when the game starts. Should I load in all the weapons and instantiate all the weapon objects at that point? Should the weapon class have the ability to show weapons from the database without instantiating them?

Thanks for any help.

# Answer
Since you say a "small" text RPG, my advice would be to just preload everything. If we're not talking about an enormous amount of content, then it shouldn't make a great difference to startup time, and it keeps things, as Bjorn advises, simple.

One thing that occurs to me, reading your question, is that you may want to consider the difference between a *weapon* and a *weapon type*. My preference is always to have a clear distinction between the two, and to have both modeled in code so that I can ask questions about the weapon type without necessarily having to have an instance on hand. (One way of doing this is to have the weapon type be the class, with class methods that allow you to interact with it, and the weapon be an instance of that class. I actually do not prefer this approach because then it's either impossible or incredibly messy for a weapon to change type. Obviously that won't be relevant to all games.)
> 7 votes

# Answer
Load everything at the start. Don't complicate your program by splitting data between memory and disk unless you have to (eg. when there is too much to hold in memory at once).

The important thing is to understand the distinction between data that represents instances of an item and data that represents the type of an item. Generally several instances of the former share one common instance of the latter.
> 4 votes

# Answer
I'm not that very familiar with python. The general advice I would give is to keep it simple. You said that you already got an idea of how to represent the data. If you got some classes for the data you want to store, you can store them in a list. That list can then be serialized to disk onSave and deserialized onLoad. For a first implementation and if the data is not that big I would load everything on start of the game and save it at some given points in time.
> 0 votes

# Answer
You could use SQLite. Using SQLite, you can create databases in memory and on the hard drive, and you don't need a giant DBMS like MySQL installed.
> 0 votes

---
Tags: architecture, python, rpg, file-format
---


title: Adding multiplayer to an HTML5 game

text:
# Question
Title: Adding multiplayer to an HTML5 game
I am interested in making a game that I currently have a co-op experience, however I'm curious as to the best method of implementing this in HTML5.

I have made games before using straight C sockets, and also with the Net library for SDL.

What are some of my best options for doing this in a canvas-based environment?

At present, all I can come up with are either AJAX/database solutions (with a high refresh rate), or somehow implementing a PHP server that would funnel the data through sockets.

---

The overall gameplay would be a 2.5D platformer-ish type of game, so both clients would need to be continually updated with player positions, enemy positions, projectiles, environmental data, etc.

# Answer
Socket.IO offers a system built on top of several other layers (including websockets, flash, comet techniques) with graceful selection.

Node.js is one option for running it server side.
> 12 votes

# Answer
See this answer:

> You can, however, use Flash where available to provide your script with a fallback until WebSocket is widely available. Gimite's web-socket-js is one free example of such. However you are subject to the same limitations as Flash Sockets then, namely that your server has to be able to spit out a cross-domain policy on request to the socket port, and you will often have difficulties with proxies/firewalls. (Flash sockets are made directly; for someone without direct public IP access who can only get out of the network through an HTTP proxy, they won't work.)
> 5 votes

# Answer
Comet” is probably an umbrella term that you could make use of here. WebSockets will be a more desirable option though (when they’re happy that it is safe).
> 3 votes

# Answer
Node.js is the answer. I've used it to develop a realtime multiplayer shooting game, and it took about 1 month from start to finish. It presented some unique challenges, such that it needed to have minimal latency, and all players must stay in sync within another for the concept to work.

The client side, and server side are both written in javascript and share classes / logic between each other. That starts to count when trying to fix bugs, as you don't have to implement everything twice.

The game has been up, for about 2 months, without being restarted and thousands of matches have been played.

Socket.io is an implmentation of sockets and uses node.js, however it is too bloated at this point for a game. There are other websocket implementations on github for node.js and also examples of games using it.
> 3 votes

# Answer
You could always just use AJAX and some sort of message queue. ActiveMQ is a good example. You run ActiveMQ on the server, then your JavaScript can send and receive messages. Just make each player have a unique name, and send messages to the other player.
> 2 votes

# Answer
You could try to use http://easywebsocket.org/, it's easy to implement and is a serverLess solution based on websocket :)
> 2 votes

# Answer
Currently I am using this: http://code.google.com/p/phpwebsocket/ as my socket server to test. It makes calls to the C sockets you are use to. May be of some service.
> 2 votes

# Answer
We have been working on a multi-player platform that you might find interesting. You can see our project at www.16cubes.com -- we are providing a simple javascript layer to do peer to peer communication. It is somewhat based on the Comet principle, and we have plans to move to using websockets as it becomes a bit more standardized. On the other hand, we are providing some features off the shelf .. like automatic opponent matching, game chat, facebook friends one-click invitation etc.

We have a demo tic-tac-toe, you can probably get a better idea if you see it. And yes, you can play anonymously too. No registration required, if you don't want. There's less than 10 javascript API's you need to code against, and its available at www.16cubes.com/documentation

We are actively looking for feedback, so let us know both good and bad
> 2 votes

# Answer
Have a look at this framework I created specifically for creating realtime multiplayer html5 games using node.js in a Client/Server approach. Where the server runs the game simulation, and players only send inputs.

demo: http://vimeo.com/24149718

repo: https://github.com/onedayitwillmake/RealtimeMultiplayerNodeJs
> 1 votes

---
Tags: networking, multiplayer, html5
---


# Question
Title: Advice on game architecture/design patterns
I've been working on a 2d RPG for awhile now, and I've come to realize I've made some bad design decisions. Theres a few things in particular that are causing me problems, so I was wondering what sort of designs other people used to overcome them, or would use.

For a little background, I started working on it in my free time last summer. I was initially making the game in C#, but about 3 months ago, decided to switch to C++. I wanted to get a good handle on C++ since it's been awhile since I used it heavily, and figured an interesting project like this would be a good motivator. I've been using the boost library extensively and have been using SFML for graphics and FMOD for audio.

I have a fair bit of code written, but am considering scrapping it and starting over.

Here's the major areas of concern I have and wanted to get some opinions on the proper way others have solved them or would solve them.

**1. Cyclical Dependencies** When I was doing the game in C#, I didn't really have to worry about this since it isn't an issue there. Moving to C++, this has become a fairly major problem and made me think I may have designed things incorrectly. I can't really imagine how to decouple my classes and still have them do what I want. Here's a few examples of a dependency chain:

I have a status effect class. The class has a number of methods (Apply/Unapply, Tick, etc.) to apply it's effects against a character. For instance,

```
virtual void TickCharacter(Character::BaseCharacter* character, Battles::BattleField *field, int ticks = 1);

```

This functions would be called everytime the character inflicted with the status effect takes a turn. It'd be use to implement effects such as Regen, Poison, etc. However, it also introduces dependencies on the BaseCharacter class and the BattleField class. Naturally, the BaseCharacter class needs to keep track of what status effects are currently active on them so that's a cyclical dependency. Battlefield needs to keep track of the fighting parties, and the party class has a list of BaseCharacters introducing another cyclical dependency.

**2 - Events**

In C# I made extensive use of delegates to hook into events on characters, battle fields etc. (for an example, there was a delegate for when the character's health change, when a stat changed, when a status effect was added/removed, etc.) and the battlefield/graphical components would hook into those delegates to enforce their effects. In C++, I did something similar. Obviously there's no direct equivalent to C# delegates, so instead I created something like this:

```
typedef boost::function<void(BaseCharacter*, int oldvalue, int newvalue)> StatChangeFunction;

```

and in my character class

```
std::map<std::string, StatChangeFunction> StatChangeEventHandlers;

```

whenever the character's stat changed, I'd iterate and call every StatChangeFunction on the map. While it works, I'm worried this is a bad approach to doing things.

**3 - Graphics**

This is the big thing. It isn't related to the graphics library I'm using, but is more of a conceptual thing. In C#, I coupled graphics in with alot of my classes which i know is a terrible idea. Wanting to do it decoupled this time I tried a different approach.

In order to implement my graphics, I was imagining everything graphics related in the game as a series of screens. I.e. there's a title screen, a character status screen, a map screen, an inventory screen, a battle screen, a battle GUI screen, and basically I could stack these screens on top of each other as necessary to create the game graphics. Whatever the active screen is owns the game input.

I designed a screen manager that would push and pop screens based on user input.

For instance, if you were on a map screen (an input handler/visualizer for a Tile Map) and pressed the start button, it'd issue a call to screen manager to push a Main Menu screen over the map screen and mark the map screen to not be drawn/updated. The player would navigate around the menu, which would issue more commands to the screen manager as appropriate to push new screens onto the screen stack, then pop them as the user changes screens/cancels. Finally when the player exits the main menu, I'd pop it off and get back to the map screen, remark it to be drawn/updated and go from there.

Battle screens would be more complex. I'd have a screen to act as the background, a screen to visualize each party in the battle, and a screen to visualize the UI for the battle. The UI would hook into the character events and use those to determine when to update/redraw the UI components. Finally, every attack that has an available animation script would call an additional layer to animate itself before popping off the screen stack. In this case, every layer is consistently marked as drawable and updatable and I get a stack of screens handling my battle graphics.

While I haven't been able to get the screen manager to work perfectly yet, I think I can with some time. My question about it is, is this a worthwhile approach at all? If it's a bad design I want to know now before I invest too much more time making all the screens I'm going to need. How do you build up the graphics for your game?

# Answer
Overall I would not say anything you listed should cause you to scrap the system and start over. This is something every programmer wants to do about 50-75% of the way through any project they are working on, but it leads to a never ending cycle of development and never finishing anything. So, to that end, some feed back on each section.

1. This can be a problem but is usually more of an annoyance than anything else. Are you using the #pragma once or #ifndef MY\_HEADER\_FILE\_H #define MY\_HEADER\_FILE\_H ... #endif at the top or surrounding your .h files respectively? This way the .h file only exists once within each scope? If you are, my recommendation then becomes removing all #include statements and compiling, adding in the ones as needed to compile the game again.
2. I am a fan of these types of systems and see nothing wrong with it. What is an Event in C# is commonly replaced with an Event System or Messaging System (can search the questions here for those things to find more information). The key here is to keep these to a minimum when things Need to happen, which it already sounds like you are doing so should be no to minimal worries here.
3. This also seems on the right track to me and is what I do for my own engines, both personally and professionally. This makes the menu system into a state system that either has the root menu (before the game starts) or the player HUD as the 'root' screen displayed, depending on how you set it up.

So to sum up, I see nothing restart worthy in what you are running into. You may want a more formal Event system replacement down the road but that will come in time. Cyclic includes is a hurdle all C/C++ programmers constantly have to jump through, and working to decouple the graphics all seem like logical 'next steps'.

Hope this helps!
> 15 votes

# Answer
Your cyclical dependencies shouldn't be a problem as long as you're forward declaring the classes where you can in the header files and actually #including them in the .cpp (or whatever) files.

For the event system, two suggestions:

1) If you want to keep the pattern you're using now, consider switching to a boost::unordered\_map instead of std::map. Mapping with strings as keys is slow, especially since .NET does some nice things under the hood to help speed things up. Using unordered\_map hashes the strings so comparisons are generally faster.

2) Consider switching to something more powerful like boost::signals. If you do that, you can do nice things like make your game objects trackable by deriving from boost::signals::trackable, and let the destructor take care of cleaning up everything instead of having to manually unregister from the event system. You can also have multiple signals pointing to each slot (or vice versa, I don't remember the exact nomenclature) so it's very similar to doing `+=` on a `delegate` in C#. The biggest problem with boost::signals is that it has to be compiled, it's not just headers, so depending on your platform it might be a pain to get up and running.
> 4 votes

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


# Question
Title: What to do to UV coordinates, when swapping Z/Y coordinates (axis) of the geometry?
In my Maxscript exporter I have the ability to flip the Z/Y axis by simply swapping the Z and Y co-ordinates.

When swapping the axis this way, what is the correct thing to do to the UV coordinates? (e.g. do I need to swap the U or V, or invert one or both?)

Thanks!

# Answer
> 2 votes
Unless you're trying to change how the object is textured you shouldn't need to adjust the UVs at all.

---
Tags: coordinates, 3dsmax, uv-mapping
---


# Question
Title: How to deal with crackers who are also trolls?
Assuming the following:

* the game will be cracked at some pont no matter what
* players are pushing to the limits
* trolls exist

What happens when these 3 combines?

Regulating a troll can be handled if the device / game is not cracked, i.e. kick out, ban etc.

But how to handle someone who comes online with different identities and ruins others fun?

Do you check patterns? (same IP, being cooperative instead of competitive?) Should this be crowd sourced like in wikipedia and add rights to trusted users?

We are having these issues, even though our game has only a small community.

Is the game free, or is a subscription / purchase required? Is the online element peer to peer or does it go through a server under your control? – Adam 5 mins ago

---

Answers to Adam's comment:

* iOS game. Free version is available without multiplayer
* Traffic goes through a server and is under our control

# Answer
> 4 votes
Can you elaborate on "cracked?" How have they "cracked your game?"

As far as players pushing the limits, this is normal. This is why you need to test your game as extensively as possible, and then also fix problems as they come up -- once the game is finished testing, firing the developers is the wrong thing to do because players will often still find other problems. And then when you add features in the future (because players might request something reasonable, or you wish to expand the story, etc.), it's possible to inadvertently introduce new problems that the developers will then have to fix (and then their fixes could break something else, ad infinitum...).

Trolls are a social problem. The technological things you can do will be helpful tools in dealing with trolls, but because it's really a social problem the solution will always require at least some level of human intervention (e.g., players in the game who are volunteers or staff that have powers to kick disruptive users off the system).

# Answer
> 4 votes
On a community based game, my honest opinion is that if you give the community the power, the game will regulate itself.

For example, an online arena zone with hackers is really annoying for everyone, therefore you should give people the power to kick hackers out of the current game. Obviously certain models owe themselves better to this, and it can be exploited in the opposite way also, but this is just an example.

By "cracking" I guess you mean that people have found a way to exploit your game and give themselves un unfair advantage. These can be dealt with by user regulation also, but more likely to better your security and heuristics.

Unfortunately, people will always try, and generally succeed, to find a way around your system. The only real way is to have active moderators and make it easier for users to spot and flag players who look like cheaters.

# Answer
> 1 votes
I am pretty sure every iOS device out there has a unique ID that you could register with the system when it connects. You could put something in your EULA that states clearly that if you play outside of the rules intended of the game then your multi-player access will be revoked at the decision of your company. Build in a little reporting mechanism for the game and that should be good enough for the community to find the people who appear to be having an unfair advantage due to outside means, giving you the ultimate control to remove their access to the network while still letting them play the game on their own. If you want to be Really nice, then you can also consider finding a way for people to put their game back in order and play normally, but that is going above and beyond.

Hope this helps

# Answer
> 1 votes
Ignore them. They are a minor, trivial part of your user base.

--edit--

OK based on your comment to my post, you don't have a cracker/troll problem, you have a design problem. I assumed you meant you had the typical hacker/cheater issue about every game has.

You need to start thinking about blocking HOW they are hacking you, not WHO is hacking you. Determine how they are creating fake scores and dominating your top 50 list, and block the method. When the cheater count goes below a certain level, then just ignore them as there will always be cheaters.

---
Tags: community-management
---


# Question
Title: Playing a Song causing WP7 to crash on phone, but not on emulator
I am trying to implement a song into a game that begins playing and continually loops on Windows Phone 7 via XNA 4.0. On the emulator, this works fine, however when deployed to a phone, it simply gives a black screen before going back to the home screen. Here is the rogue code in question, and commenting this code out makes the app run fine on the phone:

```
// in the constructor fields
private Song song;

// in the LoadContent() method
song = Content.Load<Song>("song");

// in the Update() method
if (MediaPlayer.GameHasControl && MediaPlayer.State != MediaState.Playing)
{
    MediaPlayer.Play(song);
}

```

The song file itself is a 2:53 long, 2.28mb .wma file at 106kbps bitrate.

Again this works perfectly on emulator but does not run at all on phone. Thanks for any help you can provide!

# Answer
We figured this out. The information is available online but it's really well hidden, so I'll post it here for good measure.

Basically if the phone is tethered to a computer and the Zune software is running, it locks the media on the phone, which means that MediaPlayers in apps will *never* have permission to play a Song.

In order to get it to work, the user must un-tether the phone (i.e. unplug the USB cord), or use the Windows Phone Connect tool which has been designed with this in mind with regards to debugging: http://msdn.microsoft.com/en-us/library/gg180729%28v=VS.92%29.aspx \- I haven't tried the tool, but untethering worked like a charm.

Also, when the app doesn't have permission to play a song, it will crash unless the exception is handled, so make sure to use try/catch blocks. The caught exception can simply be ignored.
> 13 votes

# Answer
The answer from Michael Zehnich is indeed correct. However I stumbled upon another problem that cause the same exception.

The problem for me was that I was missing the ID\_CAP\_MEDIALIB capability in my WMAppManifest.xml.

```
<Capability Name="ID_CAP_MEDIALIB"/>

```

Hope this helps.
> 2 votes

---
Tags: xna, c#, xna-4.0, audio, windows-phone-7
---


# Question
Title: XNA: Skinning sample, keyframes and time
I've been using the skinned sample from XNA tutorials to understand and play FBX files animation. While the animation in all my tests runs correctly, I fail to understand the technic to calculate time versus keyframes.

Most of the models I found so far for free and testing purpose on google store all animations into one "take" and split frames into all animations. So, walk would be frame 1 to 14, run 15 to 30, jump 32 to 48, etc. On the other hand, the skinning sample loads all frames and store a calculated time which it will be using to loop the animation.

The part where I'm getting confused is on the keyframe part. For example a model I've been trying to load gives me a 12 seconds timespan with 20160 keyframes. While the timespan seems right, the keyframe count seems to have been altered in some way since in Milkshape and in the Autodesk converter the frame count is at 300. What is it doing?

Here's my setup for model conversion.

1. I use Milkshape 3D to export a model and its animation to an FBX binary file.
2. Then, I use the Autodesk file converter to convert the file into an ASCII FBX (so far I tried and tested the FBX2012 and version 6.1, which is the same as the "dude.fbx" given with the skinning sample).
3. Processing model inside XNA with the SkinnedModelProcessor given with the skinning sample.

What I'm really trying to achieve here is to split animation into smaller clips so I can switch depending on the user action. I'm perfectly fine with counting keyframes, but as you can see, the keyframe count is way too high.

# Answer
It's been a couple of days, and I'm still searching for a perfect solution. I did, however, find something to work with for now. My main problem was to work with time span instead of frame span. Also, I think the models I'm using aren't rigged correctly. So, I still can't get the "walk" animation to play right.

I'm using this method to split up the clips at the PROCESSING time: http://forums.create.msdn.com/forums/t/1415.aspx?PageIndex=2 (see Spacedude's post in the middle of the thread).

Here's what I'm doing to test this out. SplitAnimations() is called in the Process() method after it has been processed.

```
Dictionary<string, AnimationClip> animationClips;
animationClips = ProcessAnimations(skeleton.Animations, bones);
animationClips = SplitAnimations(animationClips["Animation"], @"C:\defs.txt");

```

Then, in my component, I do this to start a clip:

```
    protected override void LoadContent()
    {
        base.LoadContent();
        var data = Model.Tag as SkinningData;

        AnimationPlayer = new AnimationPlayer(data);

        if (!string.IsNullOrEmpty(CurrentClip) && data != null)
        {
            var clip = data.AnimationClips[CurrentClip];
            AnimationPlayer.StartClip(clip);
        }
    }

```

It'as all testing code for now. More to come.
> 0 votes

---
Tags: xna, animation, models
---


# Question
Title: looking for simple 3d games made with Qt
Hi i need to make simple education games in 3d for that i need GUI and editor like function this is no problem . but the openGL stuff i need to learn by example.
do you know places where i see example of simple 3d games made with Qt ?
Thanks

# Answer
I don't know any 3D game made with Qt, but here are some useful links about creating 3D scenes and animations using the Qt 3D rendering api (QtGL is based upon OpenGL) or about game creation with Qt.

First, here is a very interesting step by step tutorial/demo to present QML and 3D. Which I think could be very helpful for you, because all you need (for the 3D part) is in there:

Next one is about using QML for creating simple game (non 3D), but it can be interesting even if you want to create a 3D game, and particularly for the "Implementing the game logic" part:

Finally you can search read the forum section dedicated to games on the Qt Project's forum, and the QTGL documentation:
> 5 votes

# Answer
simple shooter Qt project
> 1 votes

---
Tags: qt
---


# Question
Title: Stuck in Wall after rectangle bounding box collision
Using XNA's built in Intersects() on two Rectangles, I can detect a collision and set my velocity to zero. However, the object is stuck there and can't get out! How can I resolve this collision properly?

# Answer
This is because once your object gets into the wall and you find the collision, you're simply stopping the object's movement by setting its velocity to zero, but the object is **still** within that wall.

To fix it, you have to **resolve** the collision by moving the object. You have two options here:

* Move the object back to its old position, by applying the opposite of the velocity to cancel the movement as soon as you detect a collision. **Pros:** extremely easy to implement. If it doesn't affect your game play go with this option. **Cons:** This will prevent the object from moving in any direction that would cause a collision (so you won't be able to slide along a wall for example).
* Find from where the object is and resolve the collision accordingly. For example, if the object came from the left and collided on the left side of the wall, you would simply move the object just to the left of the wall. By repeating this to all the sides of the rectangles, the object would be allowed to keep moving towards its desired velocity but would still avoid collisions.

---

**Implementation of second option**

Here I'll assume that the velocity represents the direction in which the object is going (basically that you are **not** changing the velocity between the object's position change and the collision check). I'll also assume that your origin is positioned at the top-left of the image (so when moving the object to resolve the collision I'll position the top-left corner).

Here is how I would do:

```
if (objRect.Intersects(wallRect)) // If there is a collision
{
    Vector2 newPos = obj.Position;

    if (obj.Velocity.X > 0) // object came from the left
        newPos.X = wallRect.Left - objRect.Width;
    else if (obj.Velocity.X < 0) // object came from the right
        newPos.X = wallRect.Right;
    if (obj.Velocity.Y > 0) // object came from the top
        newPos.Y = wallRect.Top - objRect.Height;
    else if (obj.Velocity.Y < 0) // object came from the bottom
        newPos.Y = wallRect.Bottom;

    obj.Position = newPos;
}

```

You could also use the old object's position to find where the object is from, but using the velocity is simpler in this case.
> 12 votes

# Answer
You can do this in various ways.

One method is storing the previous position of the Rectangle every frame. So, when your rectangles Intersects, just set the object position to the older one that not collided. This method is not the best, because if the Rectangle velocity is high, you may see the reposition that you made via code.

Another method is testing the collision with a Raycast, so you can preview a collision before it ever happens.

Take a look at msdn for documentation for Raycast collision, and you'll be able to do that.
> 1 votes

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


# Question
Title: resources on creating world editor / game IDE
The craftyjs javascript game engine is in the process of creating a game builder that will assist the developer in map design, sprites, animations and that kind of stuff.

Are there any good resources on how a game builder should be crafted, both from an ease of use point of view(you need these features, and the world should be displayed like this) and a technical point of view(You need to store the data like this). I figure there should be blogs and articles written by players in the traditional console and pc game industry that we can learn from, but i have a hard time finding any.

# Answer
For interface, efficient navigation will definitely be a high priority, and I suggest you take a look at how Google Earth makes it possible to view any part of our world with a minimal amount of "mousing around" -- need to go from Canada to China? Simple, zoom out from some street view in Canada, drag the world to view China, click a few times to zoom in to the desired province, city, etc., and you've travelled across the world faster than the grumpy customs official at the aeroport can say "Today is your lucky day, for you've been randomly selected for a private search session..."

For data format, providing more options is definitely better. If you can let the output be tab-delimited format file (.tab), comma-delimited format file (.csv), or a series of SQL INSERT statements (.sql) that will work in major SQL servers like PostgreSQL, MySQL, Oracle, SQLite, etc., that would be great. The option for the developer to decide what information is output, and in what order, will be important too (default should be something that you choose which is sensible, starts with X and Y {and even Z if you're supporting multi-level buildings, basements, dungeons, etc.} co-ordinates, and includes all other fields).

Now, being able to attach arbitrary labels will be important. A reference to graphical images, which can be used in your editor, will help too. Of course, for the references to graphical images, if developers have the choice of using the filename (the default) or specifying an arbitrary ID number (which can alternatively be output in the resulting data files), this would certainly be helpful.

There should also be an "explore mode" that allows the developer to run around the world, even if the character is only a stick man (make sure you provide a stick woman as well, which should also be easy to draw because all she'll need is a triangular shaped dress and long hair). Even if the character can run through walls and drifts around like a ghost, that will still be okay because the main point is to just give a feel of some simple navigation which is valuable to world builders.

I hope this is helpful to you. Please let me know if you do release something as I would like to take a look at it and would be happy to provide you with some feedback if you like.
> 1 votes

---
Tags: tools, browser-based-games, map-editor
---


# Question
Title: Is it any good to make play game in zoom condition?
I'm developing a game with large obstacle and sprites(in cocos2d+box2d for iPhone), then after zooming out my sprites and layer (by increasing cameraZ), I make my game to play by user, which causes some problem in touch detection of dynamic objects.

Can it be said a good approach to work with? If No then what will be the solution to work properly(consider that I have traveled so far with this approach)?

# Answer
> 1 votes
I'm not quite sure I understand your question entirely.

I'm guessing you're having problems because the Z of your camera changes and makes all your collision detection off.

If this is the case, you could try changing the FOV of the camera for the 'zoom' effect, this will remove any problems with the axis.

---
Tags: game-design, iphone, box2d, cocos2d-iphone, cocos2d
---


title: Communication between objects in games?

text:
# Question
Title: Communication between objects in games?
I want to make a simple game where I have some characters fighting on a plane (level). I find the trickiest part as figuring out who should do what here.

I want my terrain to have friction (so you could play on ice).

I also want fairly customizable characters.

At first I was thinking of a mediator pattern where the game gathers information about the current player state and modifies them based on that, but I do not think this offers enough flexibility.

I was thinking more along the lines of each player / character does have some logic.

The Input from the game gives it the command the player pressed, then the character would load the correct animation for this.

As for friction and whatnot, I was thinking that the world would somehow need to multiply the player's velocity vector by its coefficient of friction. Because I don't think the player needs to know about the level (and preferably the level does not know about characters)

It's in these little design aspects that I get a bit confused.

Is this a good design? What could be improved / changed / added given what I want to do?

Thanks

# Answer
> 3 votes
Well, it's not how I would do it. Since the velocity of the character is a property of the character, I would attach that information to the character. In fact, I would have the character know both its position and velocity, Heisenberg be damned. If that means the character needs to "know about" the level, at least insofar as being able to ask what the coefficient of friction is at its position so as to be able to update its velocity, then so be it. Radical decoupling is a virtue only toward a particular purpose, not in and of itself.

I think you were on the right track to some extent with your mediator pattern, though. Pushing the control input directly to the character object and making it solely responsible for animation makes it awkward to, for example, have an action interrupted by external interference. I would make the character object responsible for modeling what it's *attempting* to do, while being open to being told that something else is actually happening by the mediator, and for providing animation information to a view which would do the actual management of the animation (rather than the character model doing so itself).

This isn't to say that I think all logic should live in the mediator. As implied above, I would make the character model responsible for logic that's *about it*. The mediator should be responsible for resolving things in a broader scope.

---
Tags: c++, 2d, architecture
---


# Question
Title: What is the difference between ambient lighting and skylight?
What is the difference between ambient and skylight lighting? Please give me a detailed description of the differences.

# Answer
> 4 votes
Ambient lighting is just a constant term modulated by surface color.

Sky light can mean many different things, it might depend a bit on engine/library/app:

* Directional light casting shadows. This gives you the direct illumination from a sun
* Multi directional ambient light, where incoming is sampled along world normal from some kind of data structure, usually a 4x4x6 cubemap or just an equation. This will give you an overall ambient term that is brighter in the suns direction, blue in the sky and brown/green from the ground.

Usually it is just the latter, or a combination of the two.

# Answer
> 3 votes
Ambient light is an abstract concept. Typical computer light simulations divide light into 4 categories: specular (light from a specific source reflecting directly off an object), diffuse (light from a specific source reflecting indirectly off the object), emissive (light being created by the object itself), and ambient (light from all other sources being reflected off the object). You blend these 4 (although emissive is rarely used) to simulate the effects of the various lights in the scene. A material or part of a material will have different reflectivity values for these 4 light types to determine how it appears - eg. a shiny surface will favour the specular, whereas a rough or fuzzy surface will favour the diffuse.

As such, you might use the ambient lighting to simulate some light from the sky, but you will probably simulate more of that light by a directional light that is seen as specular and diffuse reflections. The ambient light helps to simulate the daylight that hits the object from random angles due to bouncing off other objects. However there are a variety of different ways to achieve this, all more realistic than simply setting a simple ambient light level.

---
Tags: lighting
---


title: How to get and use delta time

text:
# Question
Title: How to get and use delta time
I have mice looking and walking in my game, but they are very slow and hard to use. I think it's because I'm using fixed speed. I heard that in big projects developers use delta time. How do I calculate delta time in glut? How do I calculate speed using delta time?

# Answer
> 21 votes
The "delta time" used to be the time elapsed between two frame updates (but it can also be used in other contexts; this is usually the result of a time subtraction).

You can get the delta time in glut using the glutGet method and the GLUT\_ELAPSED\_TIME parameter, plus some operations.
The following line returns the number of milliseconds since glutInit was called (or first call to glutGet(GLUT\_ELAPSED\_TIME)) :

```
int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);

```

So if you register the current timeSinceStart at each rendering loop, you can know the deltaTime by subtracting the old one to the new one.

```
int oldTimeSinceStart = 0;

while( ... )
{
     int timeSinceStart = glutGet(GLUT_ELAPSED_TIME);
     int deltaTime = timeSinceStart - oldTimeSinceStart;
     oldTimeSinceStart = timeSinceStart;

     //... stuff to update using deltaTime
}

```

---

You can also do it almost the same way, using the C/C++ ctime library with clock() and the macro constant expression CLOCKS\_PER\_SEC that specifies the relation between a clock tick and a second.

---

Basically, you can use deltaTime to update your movements in ratio to this elapsed time instead of using a fixed time value. This way, the movement speed of your character should be almost the same if your program runs at 60 fps or if it runs at 10 fps.

Here is a small example: suppose you want to move something by 10 units each second on the x axis. You could do something like this (if deltaTime use milliseconds indeed).

```
Position.x += 10/1000 * deltaTime;

```

This way, whether your program updated 2 times or 100 times, 1 second later the position should be almost the same, and the game-play is less impacted by the low fps of a small computer than if it use fixed values.

* With fixed values ==\> low fps = less updates = slow movements whereas high fps = more updates = very fast movements.
* With deltaTime ==\> "almost" the same movements.

---

Finally, you should read Fixed time step vs Variable time step on gamedev.stackexchange.

---
Tags: glut, timestep
---


title: Representing Wind in a Block-Based Game

text:
# Question
Title: Representing Wind in a Block-Based Game
I'm creating a game inside of a game called "ROBLOX". The game gives you some scripting tools to allow me to basically create anything I want. The world is created up by decently large blocks. There are few exceptions to this (such as ramps, spheres, tubes, etc.)

I want to create a subtle hint of wind. It will be affecting the game play a little bit and I want the wind to be predictable. I first thought of creating a flag, but, a flag isn't very well made in such a game as ROBLOX.

So my question is, what different kinds of way can I imply that there is wind? What other methods will provide me with a natural representation of wind (I don’t want to put a meter or something, I want them to have to find it/figure it out for themselves).

# Answer
Often games will use semi-transparent blocks with that good old 'wisp' effect that gives the impression of wind. A kind of white swirl in the direction the wind is, I'll try to find a sprite sheet to show you what I mean later.

Here is a screenshot of a tile-based game some friends of mine made, you can see the wind represented by the white 'swirls' and it tiled pretty well.

http://www.thomas-planques.com/wp-content/uploads/Level%20Design%205%20-%20Jump%20Gap.jpg

Here there are some prite sheets for special effects; the wind one looks more like a tornado, a bit of clever editing and transparency may help it 'calm down'.

As Olhovsky said, you could also use particles, this is really dependant on what type of 'feel' you want your game to have, you could mix particles with animated floor tiles (moving grass for example).
> 6 votes

# Answer
Draw small transparent particles that move in the direction of the wind.

Like snow particles, except they could just be (very) small grey puffs. Apply a combination of sin functions to the particle positions to offset them from their usual path, to make them swirve around a bit (e.g. move upward sometimes), so that they don't always simply fall in one direction (which would make them look like rain/snow instead).

If you want to maintain a blocky look, just make the particles small transparent squares (or cubes).
> 5 votes

# Answer
SFX can strongly improve the illusion of wind, especially when used in conjunction with a subtle visual effect.

You can even use the volume of the sound in comparison with the background sounds/music to imply strength of wind. (You don't necessarily have to keep raising the volume of the wind for this, having the background sounds/music fade slightly as you reach more intense wind can have just as much if not more of an effect without simultaneously making your game too loud)
> 4 votes

---
Tags: animation
---


title: XNA boundingbox 2d rectangle

text:
# Question
Title: XNA boundingbox 2d rectangle
I'm checking to see if the ray that I've created is intersecting with a rectangle. I'm using the boundingbox class to pass the rectangle into the intersect method in the Ray class, but unfortunately it isn't working I'm wondering if it has something to do with how I constructed either the boundingbox or the Ray.

The code is below, any help with this would be great.

```
  Ray bulletRay = new Ray(new Vector3(lensPosition, 0.0f), (new Vector3(lensPosition, 0.0f) - new Vector3(level.Player.Position.X, level.Player.Position.Y - 32.0f, 0.0f)));

Rectangle tileBounds = Level.GetBounds(x, y);
                        BoundingBox box = new BoundingBox(
                        new Vector3(tileBounds.Left, tileBounds.Top, 0), // Front = 0
                        new Vector3(tileBounds.Right, tileBounds.Bottom, 0)); // Back = 0

                        float? output;

                        bulletRay.Intersects(ref box,out output);
                        if (output.HasValue)
                        {
                          wallInWay = true;
                        }

```

# Answer
Here is a refactoring of your code (this does the exact same thing as what you posted in your question, I just wrote it a little differently):

```
Vector3 rayStart = new Vector3(lensPosition, 0.0f);
Vector3 pointOffset = new Vector3(level.Player.Position.X,
    level.Player.Position.Y - 32.0f, 0.0f);
Vector3 direction = rayStart - pointOffset;
Ray bulletRay = new Ray(rayStart, direction);

```

This ray always points straight down, which is not what you want.

Since you didn't tell us how your ray should be defined, I can't tell you exactly what code will fix your issue.

However, you should fix the above code so that `pointOffset` is a position that satisfies the following:

* It is on the ray.
* It is not the same as the player position.
* It is between the player and the desired box to collide the ray with.
> 4 votes

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


# Question
Title: Getting 2D Platformer entity collision Response Correct (side-to-side + jumping/landing on heads)
I've been working on a 2D (tile based) 2D platformer for iOS and I've got basic entity collision detection working, but there's just something *not right* about it and I can't quite figure out how to solve it.

There are 2 forms of collision between player entities as I can tell, either the two players (human controlled) are hitting each other side-to-side (i. e. pushing against one another), or one player has jumped on the head of the other player (naturally, if I wanted to expand this to player vs enemy, the effects would be different, but the types of collisions would be identical, just the reaction should be a little different).

In my code I believe I've got the side-to-side code working: If two entities press against one another, then they are both moved back on either side of the intersection rectangle so that they are just pushing on each other.

I also have the "landed on the other player's head" part working.

The real problem is, if the two players are currently pushing up against each other, and one player jumps, then at one point as they're jumping, the height-difference threshold that counts as a "land on head" is passed and then it registers as a jump. As a life-long player of 2D Mario Bros style games, this feels incorrect to me, but I can't quite figure out how to solve it.

My code: (it's really Objective-C but I've put it in pseudo C-style code just to be simpler for non ObjC readers)

```
void checkCollisions() {

    // For each entity in the scene, compare it with all other entities (but not with one it's already compared against)
    for (int i = 0; i < _allGameObjects.count(); i++) {

            // GameObject is an Entity
            GEGameObject *firstGameObject = _allGameObjects.objectAtIndex(i);

            // Don't check against yourself or any previous entity
            for (int j = i+1; j < _allGameObjects.count(); j++) {

                    GEGameObject *secondGameObject = _allGameObjects.objectAtIndex(j);

                    // Get the collision bounds for both entities, then see if they intersect
                    // CGRect is a C-struct with an origin Point (x, y) and a Size (w, h)

                    CGRect firstRect = firstGameObject.collisionBounds();
                    CGRect secondRect = secondGameObject.collisionBounds();

                    // Collision of any sort
                    if (CGRectIntersectsRect(firstRect, secondRect)) {

                            ////////////////////////////////
                            //                            //
                            // Check for jumping first (???)
                            //                            //
                            ////////////////////////////////
                            if (firstRect.origin.y > (secondRect.origin.y + (secondRect.size.height * 0.7))) {

                                    // the top entity could be pretty far down/in to the bottom entity....
                                    firstGameObject.didLandOnEntity(secondGameObject);

                            } else if (secondRect.origin.y > (firstRect.origin.y + (firstRect.size.height * 0.7))) {

                                    // second entity was actually on top....
                                    secondGameObject.didLandOnEntity.(firstGameObject);

                            } else if (firstRect.origin.x > secondRect.origin.x && firstRect.origin.x < (secondRect.origin.x + secondRect.size.width)) {

                                    // Hit from the RIGHT

                                    CGRect intersection = CGRectIntersection(firstRect, secondRect);

                                    // The NUDGE just offsets either object back to the left or right
                                    // After the nudging, they are exactly pressing against each other with no intersection
                                    firstGameObject.nudgeToRightOfIntersection(intersection);
                                    secondGameObject.nudgeToLeftOfIntersection(intersection);

                            } else if ((firstRect.origin.x + firstRect.size.width) > secondRect.origin.x) {
                                    // hit from the LEFT

                                    CGRect intersection = CGRectIntersection(firstRect, secondRect);
                                    secondGameObject.nudgeToRightOfIntersection(intersection);
                                    firstGameObject.nudgeToLeftOfIntersection(intersection);

                            }
                    }

            }
    }
}

```

I think my collision detection code is pretty close, but obviously I'm doing something a little wrong. I really think it's to do with the way my jumps are checked (I wanted to make sure that a jump could happen from an angle (instead of if the falling player had been at a right angle to the player below).

Can someone please help me here? I haven't been able to find many resources on how to do this properly (and thinking like a game developer is new for me). Thanks in advance!

# Answer
The simplest way to get you approximately correct beahviour would be to have your CheckCollisions() function consider the relative velocities of the two objects, in addition to their current positions.

Basically, you do this:

Vector3 RelativeVelocity = secondVelocity - firstVelocity;

And then only treat it as a "didJumpOnEntity" event if the resulting RelativeVelocity.y is less than zero. (And reverse this when you're testing the other case, whether SecondRect has jumped on top of FirstRect).

Conceptually, what this is doing is checking whether the objects are moving toward or away from each other on the y axis at the time of collision. If they're moving away from each other (as is the case when objects are bumping into each other from the side, and one jumps), then it doesn't trigger the "jump on" event. It'll only trigger once the first entity starts descending toward the second one, which matches what you see in most platformers. This approach also works in the (much less common) "I'm still moving upward, but the other entity is moving up faster than me, and hits me from beneath" situation, which a naive "am I moving up or down" test would fail on.

A correct solution for this would require a much more complicated set of collision checks. But just adding this simple velocity check should be more than enough for a standard 2D platformer.
> 3 votes

# Answer
What you could do is set a flag when you collide with a sprite that contains what kind of collision you are currently involved in. Then, if the jumping while touching sideways situation happens, you can tell because the sideways collision flag is still up, which means you can safely ignore the top down collision effect with that sprite.

Make sure to drop whichever flag you aren't using at the moment (so if you are pressing sideways and you jump above the other sprite, once you are no longer colliding sideways a top down collision should be possible) otherwise you could get some non-registering collision going directly from one to the other. You can also add a delay or dead-zone to making the flag reset depending on how much clearance you want before the changed collision behavior.

All of this would have the benefit of having whichever collision side happens first override the others, regardless of the number of sides you have unique behavior for.

Another option would be to make sure that sideways collision always takes precedent over top down collision, so if both are true it acts like a sideways collision, but how effective this would be would depend on the collision logic. It could easily flip your problem to counting as side collision when on top if you are not careful.
> 1 votes

---
Tags: 2d, collision-detection, game-mechanics, sprites, platformer
---


# Question
Title: How to do Digital Painting type of graphics art like in Braid?
I'm wanting to create the digital painting type of effect that you see in Braid for a game I'm creating. I was wondering if someone can point me in the right direction? I'm most familiar with OpenGL ES 2.0.

I'm wanting to have the background move like Braid does as well.

If anyone can get me started I would really appreciate it.

# Answer
> 4 votes
The background animation is done through a complicated combination of particle effects (snow, clouds, and so on) and what looks like a layering of many translucent layers that are not only parallaxed; they also slowly scale and rotate to give a feeling of drifting movement. When combined with traditional frame-by-frame animation, this has a very rich effect.

# Answer
> 6 votes
It's not an effect. The art in Braid is hand created digital art. It is time consuming and requires a great amount of artistic ability.

* Learn color theory.
* Learn how to paint.
* Learn how to use raster art programs.

Here is a page that has a lot of braid art explained, it has snapshots over-time to show the evolution.

To make the background move like braid, I think you are referring to parallax movement, where an object in the background moves slower than the foreground objects giving the illusion of distance. For that just link the background images to the camera movement, but with a multiplier from 0-1, 0 being infinite distance and not moving at all, 1 moving the same speed as the foreground.

---
Tags: graphics, effect
---


# Question
Title: Where should collision detection logic be placed?
I am developing a small 2D game engine. The characters have a paint method which currently does the following:

1. Calculate the new position of the character as per its speed, etc.
2. Update the collision grid cell \**
3. Draw the character at the new position

\** I have created a collision grid to reduce the number of intersection checks

Now the basic algorithm which I have thought for detecting collision is:

```
For Each Character
    Check intersection with characters in surrounding 8 cells

```

I can simply place this code in the paint method. But here is the problem I anticipate.

Suppose two characters A and B lie in adjacent cells in the collision grid. Now as per the above algorithm in the iteration of character A it will detect that it has collided with B. In the iteration for character B it will detect that it has collided with A.

But I have an idea that when A detects that it has collided with B, it should inform B that it has collided with A. This would save lot of comparisons when there are more than 2 actors colliding. But I am not sure how to handle this. I think instead of every character checking for its collision, I should check for the collision inside the game loop.

Would this approach be correct? How have you handled this kind of problem? I thought of the collision grid thing myself. Are there any alternatives to collision grid logic?

# Answer
The usual approach for collision detection is to not have either A or B detect collisions on their own.

Instead, you first move all objects, then have a separate collision system look for collisions between all pairs of objects, telling every object about the things that it has collided with, and then finally render all objects.

So in essence, instead of doing "move, check for collisions, draw" inside your Paint() function, you split up "move" and "draw" into separate functions which you call separately (first "move" for every object, then "draw" for every object). And between those, check for collisions.

Advanced note: If any of your objects move themselves in reaction to detected collisions, then you may need to repeat the "look for collisions between all pairs of objects" step, in case an object's collision-response causes another collision.
> 15 votes

# Answer
I run a loop for all my characters in the game loop like you say.

The way I do it is with a state on each of my characters, so if A and B collide while A is checking collision A and B are set to hit. at the beginning of B's loop it checks to see if it is already hit, if so id doesn't run the loop.

I put the affect code in the loop so any action that should be taken on B has happened in A's loop so there should be no reason for B to check as this would mess up the outcome of the collision, this may be different for you though.
> 1 votes

---
Tags: architecture, collision-detection, game-loop
---


title: Suitable programming language

text:
# Question
Title: Suitable programming language
Which in your opinion is the programming language of choice for game development?

Any special mention for .NET developers?

# Answer
It really doesn't matter, if you're trying to choose a language. Anything with graphical bindings can work - so close to anything. Early console games were hand-coded in Assembler, for instance.

Nowadays, the industry mostly uses C++. Some indie devs use C# (Terraria and Xbox Live Community Games for instance) and the XNA framework.

If it's .NET you want, I believe you can use C# or F# (or another .NET language, minus IronPython) with either Microsoft's XNA framework or with SlimDX. Again, since you seem to be of the opinion that you need the best language to use, I'm assuming you're going to find C# more comfortable..unless you know FP.
> 2 votes

# Answer
It depends on your platform of choice, but C++ is fairly standard in industry with occasional other languages on top.
> 2 votes

# Answer
For .Net developers - I think you should try C# and XNA - it's based on .Net Framework. It's primarly for XBox, but you can develop also for Windows Phone 7 and of course Windows.

It's really easy and it gives you a lot of usable functions.
> 2 votes

---
Tags: .net
---


title: Proper asset management?

text:
# Question
Title: Proper asset management?
I am unable to wrap my mind around designing a good way to manage resources in my game. For instance, a vertex buffer in DirectX or OpenGL would lead me to believe I should have one central buffer in which I would adapt to my game. But how would I efficiently manage this? If I had 2 game objects which used the same model but with different properties such as color or position, I would I assume reading from the same section of memory for geometry and having them each passing there own properties to the vertex/pixel shader. But what boggles me is having them read from the same section of the vertex buffer and having the vertex buffer manage the streaming of new data.

Textures and sound surface the same problem to me.

# Answer
> 1 votes
You need some raw data models. For example let's consider that you've made a model in blender of a sphere, let's call this sphere\_model.

On of your game classes is represented by a brown coloured sphere, the other one is represented by a blue sphere.

You first initialize the brown sphere, the asset manager checks it's cache and sees that the sphere\_model hasn't been loaded yet, it loads it for you and returns a pointer to a model primitive to the brown sphere.

The primitive type has a vertex buffer assoctiated and should have some methods to make it actual.

You then initialize the blue sphere, the asset manager sees that the sphere\_model has already been loaded and directy returns a pointer to the model primitive.

When drawing the brown sphere, you do something like SetVertexBuffer(my\_model\_primitive); after that you set the shader options (like colour = brown).

When drawing the blue sphere you do again SetVertexBuffer(my\_model\_primitive) which sets the same vertex buffer, however by setting different shader options, (like colour, texture, WorldMatrix, etc..) the sphere will look different.

In general proper asset management will need to statisfy the following:

* Content primitives are only loaded once (model files, texture files, sound files)
* Content primitives are mapped to a primitive class, like model\_primitive, texture2d, soundEffect, etc...)
* Primitive classes only retain the raw data, and methods to do something with this data, like actualizing the vertex buffer, but don't contain state.
* Higher level classes contain the state and use the primitive classes. They can contain (visual) state like scale, tinting, etc..

I hope this makes a bit of sense, feel free to ask more questions!

# Answer
> 0 votes
You store per-instance data in a vertex buffer too. You read from one section of GPU memory for the per-model data like the vertices and stuff, and then you read from a different section of GPU memory to determine the per-instance data.

The general rule is, you should only be sending commands to the GPU, not data- except when your data changes, of course.

---
Tags: opengl, c++, directx, management, asset-management
---


# Question
Title: Help computing visibility in old 3d game format
I am trying to compute visibility in an old 3d file format. I am using a BSP tree have finally gotten everything built and traversable.

Now I don't have any sort of PVS, potentially visible set to work with so I need to know the most efficient way to choose what polygons to render as there are literally thousands of them. I should ideally only render the polygons that are near me and then cull the non visible ones.

Does anyone have experience with this?

# Answer
> 2 votes
If you're looking for a way to *build* a PVS, I wrote a couple of articles about it at one point that you might find helpful:

http://accu.org/var/uploads/journals/overload89.pdf

http://accu.org/var/uploads/journals/overload90.pdf

The method I've described is the fairly well-known portal-based one.

An easy-to-implement alternative I saw once is to generate lots of random points in the various BSP leaves and do line of sight-testing between them -- that relies on having lots and lots of points, though, and isn't necessarily guaranteed to produce an accurate PVS.

# Answer
> 0 votes
Assuming your polygons should only be rendered in one of its faces (i.e. you should not render one if it's facing backwards), a "simple" approach would be:

1º Detect all polygons that are facing away from you and discard them from the rendering (use the surface normal of each polygon). Chances are that the 3D format selects the points of the polygons in such a way that the direction of the surface normal is consistent with where it is facing. This should roughly cut the number of polygons to be rendered to half.

2º Use a rendering algorithm. A "simple" one would be the Painter's algorithm.

---
Tags: c++, opengl, tree, binary-space-partitioning
---


# Question
Title: XNA: Retrieve texture file name during runtime
I'm trying to retrieve the names of the texture files (or their locations) on a mesh.

I realize that the texture file name information is not preserved when the model is loaded.

I've been doing tons of searching and some experimenting but I've been met with no luck. I've gathered that I need to extended the content pipeline and store the file location in somewhere like ModelMeshPart.Tag.

My problem is, even when I'm trying to make my own custom processor, I still can't figure out where the texture file name is. :(

Any thoughts? Thanks!

UPDATE:

Okay, so I found something kind of promising. NodeContent.Identity.SourceFilename, only that returns the location of my .X model. When I go down the node tree he is always null. Then there's the ContentItem.Name property. It seems to have names of my mesh, but not my actual texture file names. :(

# Answer
> 3 votes
Alright, I think I figured it out. Maybe not the best solution (so I would still appreciate other answers ;) )

```
public override ModelContent Process(NodeContent input, ContentProcessorContext context)
{
    ModelContent model = base.Process(input, context);
    foreach(ModelMeshContent modelMesh in model.Meshes)
    {
        foreach(ModelMeshPartContent meshPart in modelMesh.MeshParts)
        {
            MaterialContent materialContent = meshPart.Material;

            foreach(var texture in materialContent.Textures)
            {
                if(texture.Value != null)
                    meshPart.Tag = texture.Value.Filename;
            }
        }
    }
    return model;
}

```

The Tag property of my ModelMeshPart the file points to the .xnb file in the output directory.

---
Tags: xna, textures, pipeline
---


title: Math for Game Developers

text:
# Question
Title: Math for Game Developers
> **Possible Duplicate:**
> What math should all game programmers know?

How many need know(learn) Math for Game Developer? for 2D and 3D games? And where best learn Math for game development? in Wikipedia or maybe Books?

Thanks for answers.

# Answer
> 4 votes
I highly recommend Daniel Kodicek's Mathematics & Physics for Programmers. Great sample code and detailed, illustrated explanations of everything.

---

Google books page for 1st edition.

Table of contents to give an idea of topics covered:

* Part I General Techniques

+ Numbers
    + Arithmetic
    + Algebra
    + Trigonometry and Pythagoras
    + Vectors
    + Calculus
* Part II Ballistics and Collisions

+ Acceleration, Mass, and Energy
    + Detecting Collisions Between Simple Shapes
    + Resolving Collisions
    + Detecting Collisions Between Complex Shapes
    + A Simple Pool Game
* Part III More Complex Motion

+ Force and Newton's Laws
    + Angular Motion
    + Friction
    + Strings, Pulleys, and Conveyor Belts
    + Oscillations
* Part IV 3D Mathematics

+ 3D Geometry
    + Transforms
    + Collision Detection in Three Dimensions
    + Lighting and Textures
    + Modeling Techniques
* Part V Game Algorithms

+ Speeding Things Up
    + Tile-Based Games
    + Mazes
    + Game Theory and AI
    + Search Techniques

---

---
Tags: mathematics
---


# Question
Title: How to manage game components and their attributes?
Currently I am working with cocos2d for the iPhone. I want to make my game structured and consequential. How to manage all the game components?

What do I mean with game components? A game component is e.g. the terrain or any other object like a character that is drawn on the scene. These components have attributes and duties like "let's clean up that place" or something similar.

So actually I want to wrap a component with all its attributes to make the code reusable. E.g. think of terrain. There may be a terrain in the front. Behind this terrain there is another terrain, e.g. hills, it's still terrain but just with maybe another color.

How do I accomplish that in cocos2d? In my scene there is a draw method where I normally would draw the terrain. But if I would put everything that is drawn in that method it would get confusing.

It would be cool to create an object of a terrain class and add this to the scene which would draw the terrain automatically. How do I do that? What would be the parent class of the terrain class?

# Answer
> 3 votes
You probably want a **component-entity system**. It's a lot like mixins (versus interface and inheritance).

From Evolve Your Hierarchy:

> Up until fairly recent years, game programmers have consistently used a deep class hierarchy to represent game entities. The tide is beginning to shift from this use of deep hierarchies to a variety of methods that compose a game entity object as an aggregation of components. This article explains what this means, and explores some of the benefits and practical considerations of such an approach. I will describe my personal experience in implementing this system on a large code base, including how to sell the idea to other programmers and management.

One JavaScript library which implements this is Crafty. *Entities*, like players, trees, and bullets, are made up of *components*, like 2D, collidable, spritemap, text, etc.

Maybe this helps.

---
Tags: architecture, cocos2d-iphone, entity-system
---


title: How to create 2D game terrain?

text:
# Question
Title: How to create 2D game terrain?
Last month, I experimented a lot in game development using cocos2d for the iPhone, especially on moving and modifying sprites. However, vertices and polygons are still new stuff for me.

I developed an algorithm that creates a set of points. I now want to use them to create my 2D terrain. Here is how it looks like when I connect the points in java, so that you can get the idea

The points are connected with lines. However a real game terrain is a shape that is colored or has a texture overlayed, right? For example:

**How could I use my points to create such a terrain?**

What I tried so far is I created an array and filled it with my points. I pass this array to this method

```
void ccDrawPoly ( const CGPoint *  vertices,
    NSUInteger  numOfVertices,
    BOOL  closePolygon
)

```

> draws a poligon given a pointer to CGPoint coordiantes and the number of vertices measured in points. The polygon can be closed or open

This actually draws a plain shape. But from the blue picture it looks like there is not one shape but many.

Please share you knowledge on how to create 2d game terrain.

**Update 03.06.2011**

Based on the two good answer I have following result

# Answer
> 5 votes
The easy/naive solution would simply be to take your existing points, and for each point have a corresponding point that's at the same Y position but off screen. From there, create your polygon by taking, say, points 0, 1, 1's pair, and 0's pair and pass that to your DrawPoly method. Then continue on with (1, 2, 2's pair, 1's pair), etc.

# Answer
> 4 votes
I would loop through your array two points at a time, extrapolating two more points (by using the X value for each of the two and making the Y value 0) to give you the bottom of your shape. Pass those four points into ccDrawPoly() and repeat until you run out of array values.

so, if you have say:

```
P1 = (0, 25)
P2 = (5, 30)
P3 = (10, 20)
P4 = (15, 25)
for the first shape, you pass in P1, P2, (0, 0), and (5, 0)
second shape is P2, P3, (5, 0), (10, 0)
third shape is P3, P4, (10, 0), (15, 0)
etc...

```

---
Tags: 2d, terrain
---


# Question
Title: Using an engine to create content with PHP - but how should it happen?
I need to create an engine that will allow me to add content to a website. The website is a browser-based game. This is a verbose engine that should be able to handle many different aspects of the project.

For an example, I want the developers to be able to insert "dreams" into the game. A dream is called each night for the player, and upon login they will see the dream they had. A developer will write up a cool dream for the game and insert it... but to where?

That's what I'm struggling with. Naturally, I think to myself that all content for the game will enter a database once a developer is done with it. However, the amount of content could be potentially very high, and it may be too hard on the server's resources once the game grows bigger - userbase included. The other way to do it to simply hardcode everything in: a simple "dreams" file that a developer would append their dream to. I cannot have such a system, however, if this project were to have five casual developers that don't know how to even open a PHP tag! ;)

Presently the best way I can imagine a player receiving a dream is to have a developer write it and then the database pulls the dream the player receives from the database. It seems unnecessarily arduous and I'm hoping that if I still must use a database, that you folks can steer me into the right direction for how to execute this efficiently.

# Answer
From reading your question and comments, I get the sense that you don't quite understand relational databases. So I guess my biggest recommendation to you, is for you to make sure you understand their strengths; the concepts of a primary key and a foreign key are especially important.

It is also difficult to discern exactly the question here - I think you're not even sure exactly what you are asking. Your actual question is "how should it happen?" and from the description you seem to be weighing the use of a database against hardcoding these dreams. And somewhere in there you seem to have a notion that a database won't be able to handle a large amount of data - which, I mean, isn't that sort of the point of a database? So if you think a database somehow can't handle some magnitude of data, you must not have much experience in the corporate world. Let me tell you, databases handle ungodly amounts of data and they retrieve it faster than you would think possible. They're made for that kind of thing.

Anyway, all of the above is subjective, and if you're dead set on storing these dreams in files, by all means do so. Just make sure you know your reasons, and that they are true, measured reasons. To guess that a database is slower is simply unfounded (or I'd like to know where you got that idea).

So go read about relational databases, know what a primary key and a foreign key are, and then look at this simple schema that I think is basically what you need:

```
table 'users'
  id int primary key
  ...

table 'dreams'
  id int primary key
  description text
  ...

table 'userdreams'
  id int primary key
  userid int foreign key on users.id
  dreamid int foreign key on dreams.id
  ... (maybe some data about whether the user has read the dream, or a timestamp)

```

(the above is, of course, pseudocode)

So the users table is where user details are stored - username, hashed password, etc. The dreams table is added to by the designers, and you can make a nice designer-friendly form that lets them write dreams and submit them into this table. And then the userdreams table is what ties the two together; each night you insert one row into this table per user, which has their userid and the id of the dream the user has (or more likely, when an user logs in you check if they haven't logged in since the previous day, and if not then assign them a dream and pretend as if the dream had been given to them overnight - but that's an answer to a different question).

Does this sound like the appropriate answer to your question? If not, please try to clarify a bit more. As I said, it's difficult to tell exactly what needs answering.
> 1 votes

# Answer
> However, the amount of content could be potentially very high, and it may be too hard on the server's resources once the game grows bigger - userbase included. The other way to do it to simply hardcode everything in:

What makes you think that a system can cope with it in hardcoded form, but not when it's stored in a database? Databases are designed to store far, far, FAR more information than you would find in any typical code base.

Most online games, and indeed most sites, use a database these days. It shouldn't be arduous if you use a reasonable database API for it.
> 7 votes

# Answer
I would like to introduce you to this neat concept we call a content management system.

Also, listen to Kylotan.
> 2 votes

---
Tags: databases, php
---