title: Ogre 3d and bullet physics interaction

text:
# Question
Title: Ogre 3d and bullet physics interaction
I have been playing around with Ogre3d and trying to integrate bullet physics. I have previously somewhat successfully got this functionality working with irrlicht and bullet and I am trying to base this on what I had done there, but modifying it to fit with Ogre. It is working but not correctly and I would like some help to understand what it is I am doing wrong.

I have a state system and when I enter the "gamestate" I call some functions such as setting up a basic scene, creating the physics simulation. I am doing that as follows.

```
void GameState::enter() {
...
// Setup Physics
btBroadphaseInterface *BroadPhase = new btAxisSweep3(btVector3(-1000,-1000,-1000), btVector3(1000,1000,1000));
btDefaultCollisionConfiguration *CollisionConfiguration = new btDefaultCollisionConfiguration();
btCollisionDispatcher *Dispatcher = new btCollisionDispatcher(CollisionConfiguration);
btSequentialImpulseConstraintSolver *Solver = new btSequentialImpulseConstraintSolver();
World = new btDiscreteDynamicsWorld(Dispatcher, BroadPhase, Solver, CollisionConfiguration);
...
createScene();
}

```

In the createScene method I add a light and try to setup a "ground" plane to act as the ground for things to collide with.. as follows. I expect there is issues with this as I get objects colliding with the ground but half way through it and they glitch around like crazy on collision.

```
void GameState::createScene() {
m_pSceneMgr->createLight("Light")->setPosition(75,75,75);

// Physics

// As a test we want a floor plane for things to collide with
Ogre::Entity *ent;
Ogre::Plane p;
p.normal = Ogre::Vector3(0,1,0); p.d = 0;
Ogre::MeshManager::getSingleton().createPlane(
    "FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
    p, 200000, 200000, 20, 20, true, 1, 9000,9000,Ogre::Vector3::UNIT_Z);
ent = m_pSceneMgr->createEntity("floor", "FloorPlane");
ent->setMaterialName("Test/Floor");
Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
node->attachObject(ent);

btTransform Transform;
Transform.setIdentity();
Transform.setOrigin(btVector3(0,1,0));

// Give it to the motion state
btDefaultMotionState *MotionState = new btDefaultMotionState(Transform);

btCollisionShape *Shape = new btStaticPlaneShape(btVector3(0,1,0),0);

// Add Mass
btVector3 LocalInertia;
Shape->calculateLocalInertia(0, LocalInertia);

// CReate the rigid body object
btRigidBody *RigidBody = new btRigidBody(0, MotionState, Shape, LocalInertia);

// Store a pointer to the Ogre Node so we can update it later
RigidBody->setUserPointer((void *) (node));

// Add it to the physics world
World->addRigidBody(RigidBody);
Objects.push_back(RigidBody);
m_pNumEntities++;

// End Physics
}

```

I then have a method to create a cube and give it rigid body physics properties. I know there will be errors here as I get the items colliding with the ground but not with each other properly. So I would appreciate some input on what I am doing wrong.

```
void GameState::CreateBox(const btVector3 &TPosition, const btVector3 &TScale, btScalar TMass)
{
Ogre::Vector3 size = Ogre::Vector3::ZERO;
Ogre::Vector3 pos = Ogre::Vector3::ZERO;
Ogre::Vector3 scale = Ogre::Vector3::ZERO;

pos.x = TPosition.getX();
pos.y = TPosition.getY();
pos.z = TPosition.getZ();

scale.x = TScale.getX();
scale.y = TScale.getY();
scale.z = TScale.getZ();

Ogre::Entity *entity = m_pSceneMgr->createEntity(
    "Box" + Ogre::StringConverter::toString(m_pNumEntities),
    "cube.mesh");
entity->setCastShadows(true);

Ogre::AxisAlignedBox boundingB = entity->getBoundingBox();

size = boundingB.getSize(); //size /= 2.0f; // Only the half needed?
//size *= 0.96f;    // Bullet margin is a bit bigger so we need a smaller size

entity->setMaterialName("Test/Cube");

Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
node->attachObject(entity);
node->setPosition(pos);
//node->scale(scale);

// Physics
btTransform Transform;
Transform.setIdentity();
Transform.setOrigin(TPosition);

// Give it to the motion state
btDefaultMotionState *MotionState = new btDefaultMotionState(Transform);

btVector3 HalfExtents(TScale.getX()*0.5f,TScale.getY()*0.5f,TScale.getZ()*0.5f);
btCollisionShape *Shape = new btBoxShape(HalfExtents);

// Add Mass
btVector3 LocalInertia;
Shape->calculateLocalInertia(TMass, LocalInertia);

// CReate the rigid body object
btRigidBody *RigidBody = new btRigidBody(TMass, MotionState, Shape, LocalInertia);

// Store a pointer to the Ogre Node so we can update it later
RigidBody->setUserPointer((void *) (node));

// Add it to the physics world
World->addRigidBody(RigidBody);
Objects.push_back(RigidBody);
m_pNumEntities++;
}

```

Then in the GameState::update() method which which runs every frame to handle input and render etc I call an UpdatePhysics method to update the physics simulation.

```
void GameState::UpdatePhysics(unsigned int TDeltaTime)
{
World->stepSimulation(TDeltaTime * 0.001f, 60);

btRigidBody *TObject;

for(std::vector<btRigidBody *>::iterator it = Objects.begin(); it != Objects.end(); ++it) {
    // Update renderer
    Ogre::SceneNode *node = static_cast<Ogre::SceneNode *>((*it)->getUserPointer());
    TObject = *it;

    // Set position
    btVector3 Point = TObject->getCenterOfMassPosition();
    node->setPosition(Ogre::Vector3((float)Point[0], (float)Point[1], (float)Point[2]));

    // set rotation
    btVector3 EulerRotation;
    QuaternionToEuler(TObject->getOrientation(), EulerRotation);
    node->setOrientation(1,(Ogre::Real)EulerRotation[0], (Ogre::Real)EulerRotation[1], (Ogre::Real)EulerRotation[2]);
    //node->rotate(Ogre::Vector3(EulerRotation[0], EulerRotation[1], EulerRotation[2]));
}
}

void GameState::QuaternionToEuler(const btQuaternion &TQuat, btVector3 &TEuler) {
btScalar W = TQuat.getW();
btScalar X = TQuat.getX();
btScalar Y = TQuat.getY();
btScalar Z = TQuat.getZ();
float WSquared = W * W;
float XSquared = X * X;
float YSquared = Y * Y;
float ZSquared = Z * Z;

TEuler.setX(atan2f(2.0f * (Y * Z + X * W), -XSquared - YSquared + ZSquared + WSquared));
TEuler.setY(asinf(-2.0f * (X * Z - Y * W)));
TEuler.setZ(atan2f(2.0f * (X * Y + Z * W), XSquared - YSquared - ZSquared + WSquared));
TEuler *= RADTODEG;

}

```

I seem to have issues with the cubes not colliding with each other and colliding strangely with the ground. I have tried to capture the effect with the attached image. I would appreciate any help in understanding what I have done wrong. Thanks.

EDIT : Solution

The following code shows the changes I made to get accurate physics.

```
void GameState::createScene()
{
m_pSceneMgr->createLight("Light")->setPosition(75,75,75);

// Physics

// As a test we want a floor plane for things to collide with
Ogre::Entity *ent;
Ogre::Plane p;
p.normal = Ogre::Vector3(0,1,0); p.d = 0;
Ogre::MeshManager::getSingleton().createPlane(
    "FloorPlane", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
    p, 200000, 200000, 20, 20, true, 1, 9000,9000,Ogre::Vector3::UNIT_Z);
ent = m_pSceneMgr->createEntity("floor", "FloorPlane");
ent->setMaterialName("Test/Floor");
Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
node->attachObject(ent);

btTransform Transform;
Transform.setIdentity();
    // Fixed the transform vector here for y back to 0 to stop the objects sinking into the ground.
Transform.setOrigin(btVector3(0,0,0));

// Give it to the motion state
btDefaultMotionState *MotionState = new btDefaultMotionState(Transform);

btCollisionShape *Shape = new btStaticPlaneShape(btVector3(0,1,0),0);

// Add Mass
btVector3 LocalInertia;
Shape->calculateLocalInertia(0, LocalInertia);

// CReate the rigid body object
btRigidBody *RigidBody = new btRigidBody(0, MotionState, Shape, LocalInertia);

// Store a pointer to the Ogre Node so we can update it later
RigidBody->setUserPointer((void *) (node));

// Add it to the physics world
World->addRigidBody(RigidBody);
Objects.push_back(RigidBody);
m_pNumEntities++;

// End Physics

}

void GameState::CreateBox(const btVector3 &TPosition, const btVector3 &TScale, btScalar TMass)
{
Ogre::Vector3 size = Ogre::Vector3::ZERO;
Ogre::Vector3 pos = Ogre::Vector3::ZERO;
Ogre::Vector3 scale = Ogre::Vector3::ZERO;

pos.x = TPosition.getX();
pos.y = TPosition.getY();
pos.z = TPosition.getZ();

scale.x = TScale.getX();
scale.y = TScale.getY();
scale.z = TScale.getZ();

Ogre::Entity *entity = m_pSceneMgr->createEntity(
    "Box" + Ogre::StringConverter::toString(m_pNumEntities),
    "cube.mesh");
entity->setCastShadows(true);

Ogre::AxisAlignedBox boundingB = entity->getBoundingBox();
    // The ogre bounding box is slightly bigger so I am reducing it for
    // use with the rigid body.
size = boundingB.getSize()*0.95f;

entity->setMaterialName("Test/Cube");

Ogre::SceneNode *node = m_pSceneMgr->getRootSceneNode()->createChildSceneNode();
node->attachObject(entity);
node->setPosition(pos);
node->showBoundingBox(true);
//node->scale(scale);

// Physics
btTransform Transform;
Transform.setIdentity();
Transform.setOrigin(TPosition);

// Give it to the motion state
btDefaultMotionState *MotionState = new btDefaultMotionState(Transform);

    // I got the size of the bounding box above but wasn't using it to set
    // the size for the rigid body. This now does.
btVector3 HalfExtents(size.x*0.5f,size.y*0.5f,size.z*0.5f);
btCollisionShape *Shape = new btBoxShape(HalfExtents);

// Add Mass
btVector3 LocalInertia;
Shape->calculateLocalInertia(TMass, LocalInertia);

// CReate the rigid body object
btRigidBody *RigidBody = new btRigidBody(TMass, MotionState, Shape, LocalInertia);

// Store a pointer to the Ogre Node so we can update it later
RigidBody->setUserPointer((void *) (node));

// Add it to the physics world
World->addRigidBody(RigidBody);
Objects.push_back(RigidBody);
m_pNumEntities++;
}

void GameState::UpdatePhysics(unsigned int TDeltaTime)
{
World->stepSimulation(TDeltaTime * 0.001f, 60);

btRigidBody *TObject;

for(std::vector<btRigidBody *>::iterator it = Objects.begin(); it != Objects.end(); ++it) {
    // Update renderer
    Ogre::SceneNode *node = static_cast<Ogre::SceneNode *>((*it)->getUserPointer());
    TObject = *it;

    // Set position
    btVector3 Point = TObject->getCenterOfMassPosition();
    node->setPosition(Ogre::Vector3((float)Point[0], (float)Point[1], (float)Point[2]));

            // Convert the bullet Quaternion to an Ogre quaternion
    btQuaternion btq = TObject->getOrientation();
    Ogre::Quaternion quart = Ogre::Quaternion(btq.w(),btq.x(),btq.y(),btq.z());

            // use the quaternion with setOrientation
    node->setOrientation(quart);
}
}

```

The QuaternionToEuler function isn't needed so that was removed from code and header files. The objects now collide with the ground and each other appropriately.

# Answer
> 5 votes
* The Ogre ground plane is at y=0, but the Bullet ground is at y=1, because the motion state transform has its position set to (0,1,0) by this line: `Transform.setOrigin(btVector3(0,1,0));` This is why the boxes are sinking into the ground.
* Do the dimensions of cube.mesh match the TScale dimensions which are being used to create the rigid body? I'd guess the cube.mesh is bigger, which makes it look like the cubes are not colliding.
* The Ogre SceneNode::setOrientation function does not use Euler angles, it uses the quaternion components directly.

---
Tags: c++, ogre, bullet-physics
---


title: How to port a game from IPad to Iphone

text:
# Question
Title: How to port a game from IPad to Iphone
I just finished developing a 2D side scroll game for the IPad using Cocos2d and Box2d. Now we want to make an IPhone 4 version of the game, but I'm still not sure what is the best way to do it.

I was thinking to just create a new target on my project, remove all the current resources from the Build Phases and create a new Resources folder with all the assets of the game scaled to the new resolution.

Of course this approach would take a lot of work, specially from the designer, since there are a lot of images on the game, 30 levels with 3 layers of parallax, and over 100 animations between all the elements, plus the SVG levels that map physics world (we are using level SVG parser).

I would also have to check all the touch functions and the sprites with a hard coded position (mostly Hud and the Menu). I did tried to use the win Size for this, but I'm pretty sure there are sprites with fixed positions.

I know that checking the Menu and Hud position should not take much time, but I'm worried about the time it could take to scale all the images, and specially the SVG files that map the physics of the game.

I would like to know if I'm in the right path regarding the porting of the game or if there if someone have though of a better easy solution.

I tried modifying the gluLookAt eye z parameter, but this didn't work really well. I haven't work with OpenGL since college around 3 years ago, and I don't remember very well the math behind the low level pipeline of it. Anyway, I don't think that modifying the Cocos2d rendering steps could work for my problem.

# Answer
> 4 votes
That sounds like a solid path you are taking.

You will most likely need to scale down your textures (unless they aren't already high res) and change the hard coded positions. When I am creating an iPad game (with the intention of porting to iPhone) I create two copies of each texture and any hard coded position I create as constants to make them more manageable.

Depending on the game, you may have to reduce the draw calls or limit the amount of sprites/textures on screen.

Also don't forget about text, sure you can try to scale everything down by half. But your text may look blurry or too small.

# Answer
> 1 votes
The way you are trying to port your game is the standard format. but I think you can easily try scaling all your game to 1/2 when your game starts. Something like `glpushmatrix(MATRIX_IDENTITY / 2)`. but even using this method you have to convert touch positions manually and you also might run out of memory due to high resolution textures.

# Answer
> 1 votes
You also need to be aware of the device's memory. An iPad is more powerful than, say a 3DS, which in turn is less powerful and an iPhone4.

You really need to focus on which iphone you are going to develop for as well. As I think most aps aim for 3GS and that allows you to play on 4 and above with no problems.

# Answer
> 1 votes
I mentioned in my comment to the question, that your assets need little to no modifications, since the iPhone 4 (960 x 640 px) has almost the same resolution as the iPad (1024 x 768 px). If a slightly smaller viewport doesn't have a negative impact on your game, then you can basically leave your assets as they are.

In cocos2d, high-res assets (for retina display) use the `-hd` suffix, as opposed to the `@2x` suffix introduced by apple. So you might want to add a `-hd` suffix to your existing assets and create scaled down versions without the suffix if you plan to support iPhone 3GS and older.

**More importantly though:**, the native unit for coordinates on iPhone and iPad is not pixels but points. The screen of an iPhone has 480 x 320 points (if it's a retina display, one point contains 4 pixels). The screen of the iPad has 1024 x 768 points. So while your assets probably don't need scaling, your coordinates are vastly different.

You might be tempted to simply scale all your stuff down, but in case of physics, this could result in quite different results (differing object mass, etc.). You should **not** change your physics-world at all, only perform the scaling on the view (eg. multiply coordinates with another factor (`PTM_RATIO`) than used on the iPad).

If you didn't use any easy modifiable constants to convert from physics-units to device-units, then you'll probably have a lot of work ahead of you now :)

Here's an interesting post about creating an universal app (iPad, iPhone 3, iPhone 4). It might help you tackle some of your problems.

---
Tags: iphone, box2d, cocos2d-iphone, ios, ipad
---


title: Image spinning in c#

text:
# Question
Title: Image spinning in c#
I'm currently in the process of making a top-down shooter for my programming class, and one idea I had, but don't exactly know how to implement is image rotation in order to spin the object continuously. What I have are spaceships, and right now all they do is face one static direction. All I want is to have them non-stop spinning at a rate that people can see (not so fast that it looks like a blur). I've seen some code about rotating by a certain degree, etc; but no constant rotations. I'm not too sure how to go about this, but any help would be appreciated greatly.

Also, I'm using C# and Visual Studio 2010.

# Answer
> how to implement is image rotation in order to spin the object continuously

If you use XNA it's quite simple: Update and Draw methods will be called continuosly at the frame rate interval.

Have a look here. The only things you need to do are:

1. Get the input inside your Update(GameTime gameTime) method and update a use a variable to store the rotation angle relative to the texture you want to rotate
2. Use SpriteBatch.Draw() method specifying the rotation angle and the origin of the rotation.
> 2 votes

---
Tags: c#, rotation
---


# Question
Title: Is there a pattern for writing a turn-based server communicating with n clients over sockets?
I'm working on a generic game server that manages games for an arbitrary number of TCP socket-networked clients playing a game. I have a 'design' hacked together with duct-tape that is working, but seems both fragile and inflexible. **Is there a well-established pattern for how to write client/server communication that is robust and flexible?** (If not, how would you improve what I have below?)

Roughly I have this:

* While setting up a game the server has one thread for each player socket handling synchronous requests from a client and responses from the server.
* Once the game is going, however, all threads except for one sleep, and that thread cycles through all players one at a time communicating about their move (in reversed request-response).

Here's a diagram of what I have currently; click for larger/readable version, or 66kB PDF.

Problems:

* It requires players to respond exactly in turn with exactly the right message. (I suppose I could let each player respond with random crap and only move on once they give me a valid move.)
* It does not allow players to talk to the server unless it's their turn. (I could have the server send them update about other players, but not process an asynchronous request.)

Final requirements:

* Performance is not paramount. This will mostly be used for non-realtime games, and mostly for pitting AIs against each other, not twitchy humans.
* The game play will always be turn-based (even if at a very high resolution). Each player always gets one move processed before all other players get a turn.

*The implementation of the server happens to be in Ruby, if that makes a difference.*

# Answer
I'm not sure what it is exactly that you want to achieve. But, there's one pattern that is used constantly in game servers, and may help you. Use message queues.

To be more specific: when clients send messages to server, do not process them immediately. Rather, parse them and put into a queue for this specific client. Then, in some main loop (maybe even on another thread) go over all clients in turn, retrieve messages from the queue and process them. When processing indicates that this client's turn is finished, move on to the next.

This way, clients are not required to work strictly turn-by-turn; only fast enough so that you have something in the queue by the time client gets processed (you can, of course, either wait for the client or skip its turn if it lags). And you can add support for asynchronous requests by adding an "async" queue: when a client send a special request, it's added to this special queue; this queue is checked and processed more often then clients' ones.
> 11 votes

# Answer
There's certainly more than one way to do it, but personally, I'd skip the separate threads entirely, and just use an event loop. The way you do this will depend somewhat on the I/O library you're using, but basically, your main server loop will look like this:

1. Set up a connection pool and a listening socket for new connections.
2. Wait for something to happen.
3. If the something is a new connection, add it to the pool.
4. If the something is a request from a client, check if it's something you can handle immediately. If yes, do so; if not, put it in a queue and (optionally) send an acknowledgement to the client.
5. Also check if there's something in the queue that you can handle now; if so, do it.
6. Return to step 2.

For example, let's say you have *n* clients involved in a game. When then first *n−1* of them send in their moves, you just check that the move looks valid and send back a message saying that the move has been received but you're still waiting for other players to move. After all *n* players have moved, you process all the moves you've saved up and send the results to all the players.

You can also refine this scheme to include timeouts — most I/O libraries should have some mechanism for waiting until new data arrives *or* a given amount of time has elapsed.

Of course, you could also implement something like this with individual threads for each connection, by having those threads pass on any requests they can't handle directly to a central thread (either one per game or one per server) that runs a loop like shown above, except that it talks with the connection handler threads rather than directly with the clients. Whether you find this simpler or more complicated than the single-thread approach is really up to you.
> 2 votes

# Answer
Hardware threads don't scale well enough to make "one per player" a reasonable idea for a 3-digit number of players, and the logic of knowing when to wake them up is a complexity that will grow. A better idea is to find an asynchronous I/O package for Ruby that will allow you to send and receive data without having to pause an entire program thread while the read or write operation takes place. This also solves the problem of waiting for players to respond, as you won't have any threads hanging on a read operation. Instead your server can just check whether a time limit has expired and then notify the other player accordingly.

Basically 'asynchronous I/O' is the 'pattern' you're looking for, although it's not really a pattern, more an approach. Instead of explicitly calling 'read' on a socket and pausing the program until the data arrives, you set up the system to call your 'onRead' handler whenever it has data ready, and you carry on processing until that time.

> each socket has a turn

Each player has a turn, and each player has a socket which sends data, which is a bit different. One day you might not want one socket per player. You might not use sockets at all. Keep the areas of responsibility separate. Sorry if this sounds like an unimportant detail but when you conflate concepts in your design that should be different then it makes it harder to find and discuss better approaches.
> 1 votes

---
Tags: networking, server, client-server, state, turn-based
---


# Question
Title: How do I draw a multi-object mesh at once?
This is a very elementary question. At the moment I am drawing lots of faces separately by setting a location uniform separately for each one of them. This is very slow. As I understand it, the correct way to do this is to build a large mesh and draw it all at once.

I am not sure if I understand how to do this, and since it is quite a bit of work, I would prefer to know before I start doing.

The only thing I can think of is to create a large vertex coordinate array that has the information of global world position instead of the vertex coordinates in -1...1 range, and use that as vertex position attribute without changing the location uniform for each face. Then I need to create a corresponding array that takes care of the indices of the points to form proper faces.

In case this is correct so far, are texture coordinates and face normals produced the same way?

# Answer
A mesh is a simply a list of vertices. There are two ways to organize them into a buffer;

1) Stream all of the vertices into an array, one after the other, like so |X|Y|Z|X|Y|Z|X|Y|Z|... etc

Use the appropriate vertex buffer functions in OpenGL (check here, you can ignore the terrain part).

This is the fastest(depending..) way to process the vertices The problem with this method is that there are potentially a lot of duplicated vertices. Think of a cube, it has 8 vertices, each of those vertices is shared between 6 faces, some of the vertices are shared between 2 triangles! This adds up fast and can cause performance and memory issues.

2) Store all of the unique x,y,z groups in an array, use an array of indices to reference the unique vertices, like so

Verts: |XYZ|XYZ|XYZ|XYZ|... etc

Indices: |1|2|3|4|3|1|... etc

For simple models this is a tiny bit slower, but when you get into more complicated meshes this will save you tons of headaches with caching and overhead and will be faster than method 1. Again, reference the link above for how to do this, the only difference will be activating the index buffer.

To answer the last part of your question, yes. Normals and texture coordinates are done the same way, you'll just pack them into the vertex array with the position.
> 1 votes

---
Tags: shaders, javascript, webgl
---


# Question
Title: XNA Rotation results in a pixelated image
I have a "problem" with XNA 4 and spriteBatch. When I draw a rectangle and rotate it, the sides get quite pixelated and look bad: example:

What do I need to do to make the edges look smooth?

```
spriteBatch.Draw(box, new Rectangle(350, 350, 100, 100), null, Color.Red,MathHelper.ToRadians(65), new Vector2(50, 50), SpriteEffects.None, 0.0F);

```

EDIT: Found the solution.

As Tetrad's comment suggested, one needs to activate anti-aliasing. Under XNA4.0 you can use this code

```
GraphicsDeviceManager graphics;
graphics.PreferMultiSampling = true;
graphics.ApplyChanges();

```

# Answer
You need to activate anti-aliasing on your rendering device:

```
/* Your graphics device manager */
GraphicsDeviceManager gdm;
/* ... */
gdm.Device.RenderState.MultiSampleAntiAlias = true;
/* optional: */
gdm.Device.PresentationParameters.MultiSampleType =  MultiSampleType.SixteenSamples;
gdm.Device.PresentationParameters.MultiSampleQuality = 8;

```
> 5 votes

# Answer
did you pass SpriteBlendMode.AlphaBlend into the spritebatch.begin?

`spriteBatch.Begin(SpriteBlendMode.AlphaBlend);`
> 1 votes

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


# Question
Title: Does Pokemon use any deep A.I in battle?
A Pokemon wild battle. The enemy may have up to 4 moves.

I am wondering, is there any.. A.I going on here, or does the enemy simply take a random move and then executes it? Are there not any battle factors/conditions that may change the enemy's behavior?

I guess it makes sense to categorize moves by "Offensive" "Defensive" and/or "Healing", and from there make choices depending on HP etc... dunno.

# Answer
> 2 votes
Wild Pokémon use very simple AI to reflect having not much of a clue on their own. Trainers' mons use a more complicated system, where one of the bytes in the trainer data determines how smart *that trainer* is.

---
Tags: game-design
---


# Question
Title: Is there a good existing starting point for realistic 2d racing car physics?
I'm trying to get a realistic behaving racing car into my 2d top-down game.

Making a very simple car that drives around is straight forward but I want a reasonably sophisticated model that models Newtons laws and the forces on the car well and results in something great.

I searched the web for a good tutorial on how to do this but there doesn't seem to be much example code out there.

I followed this tutorial http://www.gamedev.net/topic/470497-2d-car-physics-tutorial/ which was very good and seems like a good starting point but if you have a play with the included demo you can see it still has a fair way to go before its a convincing racing car.

I hear that some 3d game engines like Unity come with a good starting vehicle model out of the box. Is there something like that out there for 2D?

Just want to make sure I am not missing some great existing 2d starting point I don't know about before I spend a LOT of time reading and figuring out all the correct forces etc needed to build my own from scratch.

This article seems to describe all the things you need: http://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html but the source code links are broken unfortunately.

# Answer
This started as a comment, but got too long. :)

If by "realistic", you mean including weight transfer back/front or left/right when accelerating/braking/turning, you need a 3d-model for the car it self (since there will be forces & rotation around three axis), even if it runs on a flat 2d surface. Thus using a 3d-model might be the only way to get what you need, and you could borrow/steal some existing code (but simplify the wheel to road surface distance computation).

If you don't need that, some basic newton + a static/dynamic friction model for each wheel based on it's slip angle (i.e. the wheel's angle in relation to it's direction of travel) should suffice. There's lots of info to be found in race car driving books about that. (Max side force is usually at 3-6 degrees slip, but this varies depending on slicks vs. threaded and the surface (tarmac, cement, gravel, etc.))
> 4 votes

# Answer
There are a few GPL driving physics engines around, which might work for you. I can't find the one I was looking for, but http://vdrift.net/ seems like it might be a good start. I think I would use a 3d physics engine even for a 2d game - you're presumably going to want jumps and so on even if they're only shown by scaling the car.
> 1 votes

# Answer
Box2D is a quite popular 2D physics engine. It doesn't have a racing model built-in, but it seems to be a solid general-purpose physics engine, so you won't have to bother with the details of basic rigid-body mechanics, collision, friction or constraints.
> 0 votes

---
Tags: xna, 2d, physics, racing
---


# Question
Title: Need some advice on designing components
So after reading about components for a bit I want to make a very simple spaceshooter game that uses components and systems. However, I'm a bit confused on how much scope each component should have. For example, let's say the game had asteroids that fly around and if you hit them, you take damage. They also have health. The asteroid entity may then contain these components:

* SpriteComponent (Texture2D texture)
* HealthComponent (int amount)
* CollidableComponent (bool rigid)
* MovementComponent (int x, int y)
* RotationComponent (int degrees)

Now let's say we had a RenderSystem. Its `Update()` method would require SpriteComponent, MovementComponent, and RotationComponent to draw an entity.

That's all fine and good but when would have MovementComponent and not RotationComponent? Couldn't we just have a TransformComponent that contains the x, y, and rotation? It feels a little weird designing these components to only be a container of one data-type. But then where do you draw the line? All sprites also have a position and rotation amount, so should the SpriteComponent contain the TransformComponent, or should the members of TransformComponent be moved to SpriteComponent?

But then the problem is if you wanted an entity with a position and rotation but no sprite. Then you either have to give it an empty texture (not necessarily a bad solution) or maintain TransformComponent and just make SpriteComponent contain it as well (or just pass both).

There's a lot of decisions to be made and I really feel similar to when I began object-oriented programming. "What should be objects? What should its methods be? Should this be public or private?" Obviously I've figured all that out now but this new component-based paradigm is giving me these same problems now. Does anyone have any advice or standards for component-based design for typically used components and how one normally would set something like this up?

# Answer
> 2 votes
> Couldn't we just have a TransformComponent that contains the x, y, and rotation?

Yes. This is exactly what the Unity Transform component does.

> It feels a little weird designing these components to only be a container of one data-type. But then where do you draw the line?

You don't have one data type. You have one *responsibility*.

> so should the SpriteComponent contain the TransformComponent, or should the members of TransformComponent be moved to SpriteComponent?

The way Unity does it, is that all components are contained by the GameObject itself. Components don't "contain" other components, but they can have references to them.

> All sprites also have a position and rotation amount..

There are two things Unity does to handle this.

1) All game objects innately have a Transform component.

2) When authoring game objects, you can specify that certain components require the game object they're attached to to have other components. They do this through their RequireComponent attribute. You can do things like say "when this component starts up, and the game object it's attached to doesn't have my required components, throw an error".

# Answer
> 0 votes
I would suggest to read the following post from StackOverflow (if you already haven't), because it has lots of information and references to Components documentation.

Component Based Game Engine Design

As previously said, entities (or GameObjects) contain components. And components do not contain other components but references to them. I hope this helps! ;)

# Answer
> 0 votes
> That's all fine and good but when would have MovementComponent and not RotationComponent? Couldn't we just have a TransformComponent that contains the x, y, and rotation?

There is no right answer to this question as it depends on the level of granularity you choose for a specific project. TransformComponent is very typical as far as I can judge. However for your test project you might want to have a PositionComponent for in-game GUI.

> All sprites also have a position and rotation amount, so should the SpriteComponent contain the TransformComponent, or should the members of TransformComponent be moved to SpriteComponent?

Neither. In first case some components will become semi-entities which is an unnecessary over-complication. In second case you will have to add similar Transform into elements that need spatial info but are not visible (e.g. some AI or physics related stuff).

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


title: how can you build with libTcod on OsX?

text:
# Question
Title: how can you build with libTcod on OsX?
I've had problems building on libtcod on OsX but i'm not the only one (see http://doryen.eptalys.net/forum/index.php?topic=621.0) but the beautiful RL Brogue uses Tcod and even builds on a Mac (https://sites.google.com/site/broguegame/).

anyone else get to developing on OsX with libtcod? hopefully with Make, not XCode tho...

# Answer
> 2 votes
I emailed Brian Walker and it turns out that they are using a Cocoa wrapper that emulates libtCod, so it looks like the answer is: you can't.

---
Tags: roguelikes
---


title: Pygame water ripple effect

text:
# Question
Title: Pygame water ripple effect
I have Googled for it but there are no ready scripts - as opposed to the same effect on Flash. I have checked the algorithm on The Water Effect Explained and also tested an implementation of the Perlin Noise, which provides a good simulation of the end of waves on a flat surface. I am looking for the same implementation found on several Flash Effects, based on mouseover/hover actions. This is targetting an interactive floor library, and I would enjoy moving away from Flash for this matter, particularly to avoid such easy reverse-engineering of the code - and yes, I know it could just use some ready-made flash code, but I would only use that as a last resort.

In time: Flash effect sample: flash-effects.com/tutorial-create-a-water-ripple-mouse-follow and a valid similar Java effect: Water Simulation using Java applet.

Has anyone seen a suitable implementation of this effect for Pygame (using OpenGL or not)?

The culprit here is the (code) interface to pass a list of values that will be sent from an external interpreter (tracker - not TUIO though) via Python. I have tried for some straight days but Pygame is not able to generate anything as fast as sheer C/C++ code (as used for the shaders in OpenGL), and my knowledge of C/C++ is null. So the target is to at least have that coming from Python code.

# Answer
> 1 votes
Check this answer (on stackoverflow). It is the same question, asked before posting it here.

Basically, the very core of it is that (1) Pygame isn't suited for the job, (2) OpenGL can do it easily, and (3) that Ogre3D has already provided that with the water demo and also (4) provides Python bindings via Python-Ogre.

---
Tags: opengl, python, glsl, graphic-effects, pygame
---


title: Very easy game builders?

text:
# Question
Title: Very easy game builders?
> **Possible Duplicate:**
> What are some good game development programs for kids?

I want very easy game builder for a kid - somebody who knows nothing about programming games (how they work inside) and just wants to build some (I could teach him but I am not available all the time). She tried Adventure Maker and got confused. It has to be something very straightforward. Do You know about any? Thanks. :)

# Answer
Alice by Carnegie Mellon University, was built explicitly for teaching those with no knowledge of programming, how to construct apps, by visually building interactive environments and simple games. It's well-geared for kids from what I've seen. The interface is good and allows you to build simple 3D games with basic parameters, teaching you Java as you go -- but it leads one very gently into the coding aspect.
> 4 votes

# Answer
Kodu, a visual game-making framework by Microsoft Research, was designed with kids in mind. It runs on an XBox 360 and uses a controller for input.
> 3 votes

---
Tags: tools, game-maker
---


# Question
Title: MySQL Recursive Query (kind of) help to determine tech tree prerequisites
I'm trying to figure out how to do what I can only call a recursive query (my knowledge of MySQL is extremely limited). The game I'm designing has a tech tree with items to research that will grant you stronger stuff down the line. The prerequisites are broken down in another table, since each tech item can have 0 or more prereqs.

```
CREATE  TABLE IF NOT EXISTS `tech` (
  `id` INT NOT NULL ,
  `name` VARCHAR(45) NULL DEFAULT NULL ,
  PRIMARY KEY (`id`) );
CREATE  TABLE IF NOT EXISTS `prereq` (
  `src_id` INT NOT NULL ,
  `prereq_id` INT NOT NULL );
INSERT INTO tech (`id`,`name`) VALUES(1001, 'Logic');
INSERT INTO tech (`id`,`name`) VALUES(1002, 'Classical Physics');
INSERT INTO tech (`id`,`name`) VALUES(1005, 'Global Economics');
INSERT INTO tech (`id`,`name`) VALUES(1008, 'Solar Power Collector');
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1008,1005);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1005,1001);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1005,1002);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1001,NULL);
INSERT INTO prereq (`src_id`,`prereq_id`) VALUES (1002,NULL);

```

With this set up, I can query the tables and find that if I want solar power, I need to first research Global Economics:

```
SELECT t.name, t.id, GROUP_CONCAT(p.prereq_id ORDER BY p.prereq_id ASC)
FROM tech t LEFT JOIN prereq p on t.id=p.src_id
WHERE t.id=1008
GROUP BY t.name, t.id
ORDER BY t.id

```

What I'm trying to get at is a result set that include the next level of prerequisites, then the next, until we hit nodes that have NULL. So I'm looking for this:

```
id     name
1008   Solar Power Collector
1005   Global Economics
1001   Logic
1002   Classical Physics

```

Is this even possible within MySQL? I tried to use a cursor, but was unsuccessful. I could handle this within the actual code, but I'd rather it be done server side somehow.

Any help in pointing me in the right direction would be greatly appreciated!

# Answer
> 2 votes
In postgreSQL or MS SQL Server, you'd use a recursive CTE for this.

Since MySQL doesn't support recursive CTEs, you'll have to change the structure of your table to use nested sets, or you could use as many self-joins as the depth of your tech tree. See this article http://explainextended.com/2009/09/29/adjacency-list-vs-nested-sets-mysql/ for how to do it.

However, there are quite a few drawbacks to doing this kind of operation in MySQL (nested sets are really slow to insert into, the Spatial index requires a table-lock), so you should consider calculating the depencies outside of MySQL if at all possible.

# Answer
> 2 votes
Seeing the discussion in comments, I guess I'd better put my recommendations as an answer.

See, I've used relational databases for all kinds of static data in the past. And it always lead to shenanigans like these. This question or this one have to deal with this too.

Relational databases are really quite inflexible in terms of data representation. Usually, you trade this flexibility for efficient storage and, first and foremost, *efficient querying of large datasets*.

Static game data is almost always very small, and fits easily in memory. And you very rarely need to query it in the way databases support. 99% of the time you just need the "give me object with this Id" request, and using RDBMS for it is overkill. 1% of the time, you have some crazy recursive query that becomes needlessly complex and slow, and an ugly hack.

On the other hand, static data tends to have complex schemata, lots of optional values, tree-like structure, etc. This is hard to represent efficiently in a database. Changing a database schema is also a pain usually. Lastly, you cannot put your database under source control - and you WANT your static data under source control.

So in the end, database does not give you any advantages. A better way is to store everything in config files: XML, JSON, YAML - anything goes, if you have/can develop a good library to work with the format. Config files can be put under source control, can be easily extended, and are not bound by a rigid schema. With some libs, like LINQ2XML, you can even run queries against them, just like with a DB. Config files are also human-readable and human-editable, which might come in handy. Of course, at runtime these files are read, parsed and stored in memory, using whatever data structure you want (and a simple hash table will be a billion times faster than a database query). Then your server works with this in-memory representation.

The only time when you can't do that is when you don't actually have a server, and your clients call DB directly. But then you have much, much worse problems than this (-8

# Answer
> 0 votes
Relational databases aren't suited to tree representations for precisely this reason. I advise you to just do this iteratively, in whatever code is using this SQL.

Note that you also have to specify how you want to traverse the tree, which isn't clear from your question. Your example has an ambiguous ordering as there either Logic or Classical Physics could go last - this will matter more when you have a bigger tree, and some of the nodes with no prerequisites might exist at different levels - should they all appear at the bottom, or should they appear some way through the structure depending on which options they make available?

Although, I second Nevermind's comment about this being the wrong data storage approach for static data. An in-memory structure would be faster and easier to process.

---
Tags: databases, sql
---


# Question
Title: Should I continue studying OpenGL or just switch to DirectX to  give me a better chance of landing a job in the game industry?
I've been learning graphics programming for some time now using OpenGL and Linux. I'm pretty familiar with most of the concepts, but I would really like to further my knowledge and eventually pursue a career in game development, especially game engine development.

So far it seems to me that the majority of game studios make games for Windows using DirectX.

Edit: I know that the OpenGL vs DirectX question has been asked here before, but I haven't found an answer in the perspective I want.

Edit 2: After reading all the responses/comments I've decided to continue diving deeper into graphics with OpenGL/GLSL, but I'll try to play around with DX as well, just to have a basic understanding of the API. I'd like to thank everyone for the answers and insight you've given me.

# Answer
> 28 votes
It really doesn't matter. The core concepts are the same in both, especially now that pixel shaders are the norm. And since most games are multiplatform they're probably going to use a subset of features that are similar in both languages. As long as you can write shaders in glsl or hlsl, you'll be fine.

That being said, the number of "game engine development" positions out there are small. Most companies use something off the shelf. For those positions that exist, even fewer of them are entry level. Most entry level game programmers don't write any graphics-related code (other than maybe shaders) because it's all been abstracted away.

# Answer
> 9 votes
It all depends on the job you want/will get. You probably think about a job in the PC market where DX is king. Just remember that most AAA companies aim for the console market where APIs are quite specific.

The PS3 for example has proprietary extensions to its OpenGL ES implementation.

OpenGL is growing in the mobile space. Now it's available on all modern platforms but Windows Phone 7.

Currently Only OpenGL ES is available in this space. But more Powerful PowerVR chips are coming with support for OpenGL 4 and DX11.

Your OpenGL skills are gold. You can reconvert to DX to land a job which requires that. But in the meantime remember that OpenGL is king on the quantity of devices and platforms where it is available.

---

**Edit**: Additionally more and more companies tend to use existing engines and often even core game developers are more and more screened from the low level APIs. It's always better to have a good knowledge of native APIs when you are facing bugs and strange behavior on specific platforms. But it all comes down to the concepts, and as others pointed out DX and OpenGL at the core will require knowledge of the same concepts.

---

**Edit**: As you are already familiar with OpenGL and probably shaders you should try OpenCL... This API has the potential of becoming the next big thing in parallel computing.

I'm mentioning it as the OpenCL kernels use datatype that are interoperable with OpenGL and are simple to understand for OpenGL devs. Have a look at that and see if you can acquire some experience with a great general computing solution (currently being integrated into bullet physics for example).

# Answer
> 6 votes
I agree, that it doesn't really matter which API you learn. It's important to know the basic concepts.

When looking at game development, Windows is not the only target platform. As I've heard, Apple is growing as a target platform, but the consoles are really important as well. Consoles normally have their own specialized graphics API (I think they're doing that just to bother us). While the console APIs tend to have more in common with OpenGL than with DirectX, it's still not a huge difference.

Go with whatever works for you.

# Answer
> 6 votes
How about the perspective of a Game Development Professor?

If you have the basics of OpenGL down then by ALL means venture into the world of DirectX (note going into DX) that Dx9 is still being used in development for compatibility reasons, as older platforms (specifically XP) don't support the newer graphics pipeline in Dx10 and Dx11. (that should read as a recommendation of starting in Dx9 and then noting the differences in Dx10 and then 11 as you progress) That will also make you more rounded.

Ideally you will want to spend some quality time in HLSL and CG (Note that these two seeming different shader languages are actually the same language (one is branded by Microsoft and the other by Nvidia) understanding how vertex and fragment (pixel) shaders work will be a huge asset to you and any game company that you go to work for (assuming that youre working on rendering systems or subsystems and not AI code. ;-)

Ogre3D is an open source rendering engine that supports both graphics subsystems (OpenGL / DirectX) and is used in many games... because the source is freely available you may enjoy digging through it and seeing by comparison how calls to OpenGL differ from calls to DirectX.

I would also recommend that because you have already spent some time in OpenGL that you poke at WebGL which looks like its going to blow up in the very near future.

Hope that Helps!

# Answer
> 4 votes
I read recently that John Carmack recommends DirectX for the simple fact that Microsoft, for awhile, played catch-up to openGL and by doing so they created a competitive product and pushed the envelope while openGL folks spent time arguing and doing design by committee allowing DirectX to become polished and, I guess, easier to work with but sticking with openGL.

http://www.tomshardware.com/news/john-Carmack-DirectX-OpenGL-API-Doom,12372.html

Maybe another option to consider if you like graphics in general and for what it's worith is what's going on in the embedded space.

I work in the embedded space using both Linux and WinCE. I was former Ford SYNC architect (was there for 6 years) and now I work on GM's CUE (GM's answer to Ford SYNC). Ford SYNC doesn't use openGL or DirectX. Ford, instead, opted for Flash & Action script; what Flash does under the hood I'm not sure but it's slow as hell; JD Powers gave it poor rating. GM's CUE is all Linux and openGL ES and although the GM CUE has a newer iMX processor the performance of animations in openGL on Linux are staggering. CUE/openGL is much faster. Again, Ford crippled their system with Adobe Flash.

So, if you're looking to make it in games but are concerned about the competitive nature but still love this type of work, maybe look at options that broaden your resume. It has been my experience that, at least in the embedded world, WinCE doesn't seem to use DirectX all that much. (WinCE has slightly different API than NT might be part of that reason). OpenGL is everywhere in the embedded world and people are doing more things such as tablets, automobile infotainment is hot right now, and of course smart phones...

# Answer
> 2 votes
I'd say it probably good on your resume to be able to say you have worked with both, regardless of which you've specialized in.

I say so because, as with anything, it's more about general techniques than API/syntax knowledge beyond a certain point. You need to be able to do stuff, and know your way around, but you don't have to have implemented huge pieces of stuff in both API:s. (Thats O(n\*m), which doesn't scale...). Knowing the APIs a bit, and knowing different tecniques (i.e. O(n+m)) works, and will be helpful.

Of course, you will score bonuses for doing something "advanced" in DX too, since it shows you have some deeper API knowledge, but you need some advanced techniques in any case, to prove that you know how the boxes should be connected (ignoring the specfic magic words you have to say to get it done).

It's the same with any API (3d or otherwise), or any programming language, really.

# Answer
> 1 votes
I found that DirectX is harder to learn and therefore a better skill. Directx usually has better support from board manufacturers, however, microsoft does not release that many updates to take advantage of those advances (and only a select subpopulation of hardcore gamers really use those boards). Regarding game development, all the major game platforms use their own proprietary graphics engines ... xbox -\> DirectX Box :) Knowing 3D concepts, meshes, lighting, transformations, etc, is a skill that is the same for all of them.

# Answer
> 1 votes
If you know one you can easily pick up the other.

If you know OpenGL you can easily program for smart phones (android and iPhone) plus win/Linux/mac.

DirectX is only Win/Xbox. So unless you want to target Xbox, I'd say stay with OpenGL since it can target more platforms.

# Answer
> -4 votes
I prefer OPENGL. Consider for example, Android the mobile operating system uses OPENGL. There are so many game engines that are developed based on the OPENGL platform.

---
Tags: opengl, directx, game-industry
---


# Question
Title: It is worth adding 'futuristic' features to our game, or should we put our focus elsewhere?
I'm lead programmer in a medium-sized indie game studio. This is our first game as a team. We're working on a futuristic FPS game, with a profit-sharing buisness plan.

Anyway, we have some very good programmers, who have the ability to create never-seen-before features (true realistic fluids, procedural mesh destruction, procedural skyboxes, etc.) And I'm wondering is there any point to implementing these things? They take a long time, but look brilliant. We're aiming for a 12 month development cycle. So should we do this, or just make a standard game.

# Answer
Do not try to do it because you know you can do it.

Gameplay should be first, all things (even graphics) are secondary. If the game is fun and enjoyable but has poor (or not so next gen) graphics, it will still be fun and enjoyable and people will play it, and also your metacritic will be good. Otherwise if the game has awesome graphics and features (realistic fluids, procedural mesh destruction, etc) but is not entertaining or difficult to play (bad controls, etc), people will not play it. No players = no money and also bad metacritic.

So first plan the game you want to do and think about its gameplay features, its playable situations. Do not try to push trying to make that feature X fit into the game just because it looks cool. If it doesn't really make sense, or if it's not going to represent an important part of the gameplay, simply drop it.

Also, avoid trying to build gameplay around one of those awesome features if it doesn't make sense or you think it's not going to be fun. For example: you might think "I have procedural mesh destruction, so let's force the player to destroy everything before he can continue advancing in the game (so he can see meshes being procedurally destroyed)".

To sum up: first think about your game and about its needs. From that base, plan your development phase, and then you will see if there is enough room to fit one or more of these awesome features (and if it makes sense to add them to your specific kind of game).
> 28 votes

# Answer
Keeping in mind that a 12 month cycle doesn't mean that you stop coding at week 52 and shove it out the door, I side with the answers already given that game play must come first and to only add neat features if they help the game play.

Ideally you'll have time to beta test with release candidates, so most work except emergency bug fixes and tuning stops at week 50.

Full features should be in place long before beta so maybe anything not in by week 46 so you can do internal testing to make everything solid before polishing in beta. So that's really only 46 weeks of work before you start getting the game ready to ship.

The key thought is to decide whether having your hot engineer working on a system is worth the trade of that engineer not already working on your next title. "What else could he be doing" is the hidden cost to any decision.

BTW, simulated fluid volumes, procedural destruction, dynamic sky boxes, etc... have all been done in commercial games and the reason you don't hear about them so much is that the game itself was always more important.

Best of luck, anything you do will be exciting!
> 15 votes

# Answer
If your programmers are that good, then use those skills to deliver on time and under-budget. And between now and the start of your next big project, think about how to better leverage those skills your team has, with the bigger budget that comes with a good track record.

But if you must do things this way, then pick ONE cool thing. Not all, not even two -- Never introduce too many risk factors at once. And that one that you pick MUST be somehow central to the gameplay, because all the rest is just fluff. When you're Blizzard, you can afford to sit around adding neat features -- although their decisions are always business-minded IMHO.

But trying to implement all or even just a few of the things your coders can do, because it seems cool and you kinda-sorta think you can, will head you for a very big fall.

Again, the key is DO NOT add anything that will not *with certainty* contribute to the core game dynamic -- whatever that is (it sounds as if that has yet TBD).
> 14 votes

# Answer
"we have some very good programmers, who have the ability to create never-seen-before features"

Nothing personal, but I have to say I doubt it. Valve (to pick just one) has some of the best programmers in the industry, if not the world. Havoc also has some pretty smart people - there are dozens of other examples. They all have more coders than you, more time, and higher budgets.

Now, maybe you have somehow managed to get a group of absolute geniuses together. But I would be vary careful about the gap between what programmers think they can do, and what we can actually do in a limited time and to a releasable standard. As other people have said, you can (if you are very confident) pick one. I personally would want to go through the process of getting a game to market at least once before I tried to shoot for the moon.
> 13 votes

---
Tags: game-design, software-engineering, business
---


# Question
Title: How to make box2d mouse joint works similar to box2d setposition
I want to make b2mouse joint working similar to b2setposition, though i know in mouse joint force is applied, so it's not possible to reach the desired point without any delay like setPosition(), but i want to make it works as close as b2setPosition(). So on which mousejoint/body properties should i work on so that it acts as close as b2setposition.

Thanks for your answer.

# Answer
You can look how MouseJoint is implemented and make some changes to it or create your own joint, to make it work the way you need.
> 1 votes

---
Tags: box2d, cocos2d-iphone
---


# Question
Title: Ara matrices calculated on the GPU or on the CPU? Would built-in matrix functions be faster than my custom ones?
If I add a math library (for example containing a Matrix class) and use it in my program drawing with OpenGL, will my be work slower than if I used standard OpenGL functions for matrix calculations? Does the same hold true for DirectX?

# Answer
Matrix manipulations are always done on the CPU. It doesn't really matter though, the total amount of floating point operations you'll do involving matrices will be less than 1000 and any modern CPU will deal with that in a few nanoseconds. Using an external library which is probably optimized is absolutely worth it, if only for the readability improvements. Not to mention that matrix manipulations in OpenGL are deprecated so you're obligated to write your own.

I can't give you any real data, but I profiled a program I wrote some time ago. It used a matrix library I wrote myself, without any optimizations. The matrix calculations didn't even show up in the profile.

So, don't worry about it unless you're absolutely sure it's a problem.
> 5 votes

# Answer
To answer the first question: on both

Usually not at all much on the CPU and then at least once per vertex (usually more) on the GPU.

I'd not care about speed except if you do heavy work with matrices in the (c++) code. If you don't (you just calculate worldView projection and so on, say some handfuls for each model at most) just use what you feel best at ease with.

The day you start to use a Lot of matrix multiplications, that day you'd know yourself what you need to do to speed up code (and if you need to speed up the "code" or the shader or maybe other things like profiling bandwith). If that day you don't know, then you are probably doing something wrong.

What about DirectX?

Well, if you want to be compatible with both then go for a library (I use Irrlicht which is a whole graphic engine) so you can switch easily (beware though, OpenGL is righthanded and DirectX is lefthanded, shaders usually don't accept a simple switch between those if you use "complex" calculations like normal maps).
> 1 votes

---
Tags: opengl, mathematics, directx, matrix
---


# Question
Title: What early design decisions are important for creating "performant" multiplayer games?
I want to create online games and focus on the performance from the beginning.

I searched on the internet, but didn't find any an particular answer concerning the design level or development level aspect, such as

---

* Design Patterns,
* Protocols,
* Techniques,
* Data transfer(games state) ,
* Formats(JSON/serialization)

;

which are crucial to create high performance online games can most of the articles are talking about hardware consideration, but you know that is not what I am looking for.

# Answer
> 2 votes
I'm a chinese programmer.We usually transfer Packet like this:
Length,Type,Data
and Length is short in C/C++,Type short,Data is raw string(binary data). We did not serialize anything but just put the C/C++ struct into the Data,because doing this can get a good performance.
and,if you want to serialize your object into Packet,you should try protocol buffer or thrift.They are scalable and high performance.

And,performance is a big topic.The basic idea is having performance problem,you should get the Hot Code,and fix them.

I am takling with you about the same thing, right?

---
Tags: multiplayer, performance, online
---


# Question
Title: if you had a bunch of good server hardware - what would you do with it? make it game related?
i've just scored 8 Dell 2950's and a Dell Blade Chassis with 10 Dell 1855 Blades, including a NetApp NAS. i'm interested to hear what other game devs would do with the gear. :)

# Answer
It all depends on the specs. But I would use that hardware for an MMO. A particularly simple one.

On the other hand you could host a few dedicated game servers and earn a few buck that way.

There are many ways to use server hardware, and one of them is to host and store game states, scores, leader boards and web services for your games. Don't underestimate this.

You could also build a social game (Facebook, etc).

Anyway you will need some bandwidth to run all or any of this.
> 1 votes

---
Tags: hardware, hosting
---


# Question
Title: How can I implement view wobble when my player is running?
I'm creating a FPS in XNA. So far its' going great. What I'm looking at doing is replicating the camera movements that you see in Modern Warfare. So, if you are walking the camera stays pretty still except for the slight weapon movement, but if you sprint then it shakes left and right. Here is a good example : Modern Warfare 2 camera motion

Has anyone achieved this? If so, can anyone give any pointers or articles that I can take a look at?

# Answer
> 6 votes
To implement this technique you'd just want to adjust the view slightly every frame by some smooth factor, typically along axes that lie within the plane of the viewport.

In other words, you want to adjust your camera position upwards and rightwards by some small periodic factor whenever the player is moving. The sine and/or cosine functions can work well for this; you could just:

* At the start of a frame, if the player is still, set a "run time" variable to 0.
* Otherwise if the player is moving, increment the run time.
* Once your view position is computed, offset it to the left by (say) `sin(run time)` and upwards by (say) `cos(run time)`.

You will probably want to play around with how you increment the run time, and how to damp the resulting offsets so that the effect is quite subtle, otherwise you may disorient or nauseate your players.

You can also combine this with a similar effect applied to whatever gun or implement the player is holding -- this is best done with a specific animation for that object, however. You can see in the Battlefield videos that the guns precess far more than the actual view does. This disconnect in the magnitude of the relative motion helps make the illusion feel more grounded and gives it some depth (much like parallax motion) which can make it look less fake.

---
Tags: xna, camera, movement, first-person-shooter
---


# Question
Title: Conundrum with quality and virus reports: is our game releasable?
I've just got done talking to the CEO of our independent game studio about one of our projects nearing completion. We're considering canning the whole project for a number of reasons:

* There are partly, some quality issues. Combat can be fun and in depth but for the most part you can get by with mashing buttons. It leaves the feeling that the advanced combat was really tagged on just to add something. When in reality a lot of work went into it.
* The game didn't end up as envisioned. It's become really a mindless combat game when originally story was planned to be important. Now the story is rather nonexistent.
* And probably the biggest issue. Rather recently we've been getting reports from testers that the game is being reported as a virus(in a few cases). We looked into this and found it's the way the engine was made. We're using a 3rd party engine and while originally the maker was very approachable, he's become rather unreachable and apathetic to our problems.

Me and him have talked a long time on this and we lean on it not being releasable. This would also though be a very big hit to the lead programmer who's put in a considerable amount of time on this, nearly a year.

**What ramifications would happen if this is released?** I'm told it could get on steam, and I'm thinking it could be pulled and really hurt our image. Also I mentioned we could be backlisted by our publisher if they consider the virus issue to be deceiving them. Could we be sued? **Would you consider it releasable?**

I think this is a very important decision every game studio might have to make one day and I'd really like as much input as I can get.

Thank you

\[edit\] Also it might matter that we have another version of the game already being made for html5 which is being developed in house with our own custom engine. We're thinking of just focusing on this and learning from our mistakes.

# Answer
You could try and contact some of the antivirus makers. This could be caused because of a false positive in their database. If it is they will probably remove it. Since almost all antivirus makers share the same database the change can propagate through.

If you let them know now and you do eventually publish the game this problem might have gone away by then.
> 4 votes

---
Tags: legal, business, game-design
---


# Question
Title: How can I traverse a scene graph and hit only nodes in the view frustum?
**Scene Graph** seems to be the most effective way of representing the game world.

The game world usually tends to be as large as the memory and device can handle. In contrast, the screen of the device captures only a fraction of the Game World/Scene Graph.

Ideally, I wish to process(update and render) **only the visible game objects/nodes** on per-frame basis. My question therefore is, **how to traverse the scene graph so, that I will focus only on the game notes that are in the camera frustum?**

* How to organize data so that I can easily focus only on the scene graph nodes visible to me?
* What are techniques to minimize scenegraph traversal time?
* Is there such way as more effective traversal, or do I have to traverse whole scene graph on per-frame basis?

# Answer
> 4 votes
If your scene is static, you can build BVH. And if you want clever BVH, use SAH. You can also build BVH for static scene and dynamic part of scene test every frame.

But. What is most effective (mean HW effective) is sorting your geometry by shader it uses. Shader switching is one of most slowing down things for GPU. So i would prefer to prepare your scene graph traversal for no needless shader switching and frustum test every Bounding box/sphere. It would be more faster than any BVH/octree tests. **Sorting by shader can increase rendering performance twice.**

# Answer
> 2 votes
I'm going to explain how my little engine does it, as whilst it is not generally tested against alternatives - its my approach and I haven't tried many others - it does explain how things can work:

I store my scene in an octree or quadtree (recommend quadtree if the scene is mostly flat e.g. RTS even if units can have height; only go true 3D if things really are dense at all y).

There are various recipes for dealing with fast-moving objects or objects that span two or more cells. I just put these objects into the node that contains them, even if that node has children. If they are fast-moving I compute a reasonably large bounds e.g. position of the next n frames, and store that, so I don't have to wriggle them each update.

When the camera moves, I then compute the intersection of the viewing frustum on the tree. I put the intersecting items in a list. I note in a bit-flag if the node or which of its children intersect the frustum, so later when objects are moving and being moved in the tree I can avoid unnecessary frustum checks.

Then I sort them by shader program and front to back.

Then to draw, I iterate through the list drawing the opaque parts of the models. Those models that have semi-transparent parts I build a single-linked-list of, so I can then go a second pass quickly back through those items back-to-front drawing the semi-transparent parts.

As the items move, I have the bit-fields so I know if the node in the tree they are in is visible or not, so I know if I have to insert, remove or resort them in the visible array that the tree is maintaining. If I have to sort them, rather than doing the sort there and then, I just put a tombstone in their old position in the list and put them in a new 'dirty' list; its then only to sort those things that moved and then merge that into a new visible list in O(n). Those types of tricks gained real frames for me.

---
Tags: architecture, scene-graph
---


# Question
Title: What is causing this problem with my object rotation?
I'm having an issue here with rotation in OpenGL. Before I changed my rendering function the rotation I had for my object worked fine, but now it seems to be messed up.

I changed my rendering function because I wanted to be able to clip the image (render frames of the image), whereas before I was just rendering things on a 1 object, 1 image basis.

The rendering is fine, just the rotation to clarify that. Here's my current rendering code:

```
void DrawRotateAdv(int x, int y, int width, int height, float sourceX, float sourceY, float imageWidth, float imageHeight,
    GLuint texture, float angle, bool blendFlag)
{
    glTranslatef((GLfloat) x + (width / 2),  (GLfloat) y + (height / 2), 0.0);
    glRotatef(angle, 0.0, 0.0, 1.0);

    if (blendFlag)
    {
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    }

    glBindTexture(GL_TEXTURE_2D, texture);
    float texscaleX = 1.0f / (float)(imageWidth / width);
    float texscaleY = 1.0f / (float)(imageHeight / height);
    sourceX = sourceX / (float)imageWidth;
    sourceY = sourceY / (float)imageHeight;

    glBegin(GL_QUADS);

    // Top-left vertex (corner)
    glTexCoord2f(sourceX, sourceY);
    glVertex2i( (-width / 2), (-height / 2));

    //Bottom-left vertex (corner)
    glTexCoord2f(sourceX, sourceY + texscaleY);
    glVertex2i( (width / 2), (-height / 2));

    //Bottom-right vertex (corner)
    glTexCoord2f(sourceX + texscaleX, sourceY + texscaleY);
    glVertex2i( (width / 2), (height / 2));

    //Top-right vertex (corner)
    glTexCoord2f( sourceX + texscaleX, sourceY);
    glVertex2i( (-width / 2) , (height / 2));

    glEnd();
    glLoadIdentity();
}

```

I think that perhaps my translation is wrong? Unsure though, guess that's a stab in the dark on my part. As for the getting the angle:

```
     angle = atan2((cEnemy->position.y - (float)position.y), cEnemy->position.x -        (float)position.x) / 3.14159265f * 180;

```

But I don't think that's the issue, like I said it worked before-hand perfectly. Screenshot of the output:

# Answer
So it looks like the rotation is off by 90 degrees. This could be caused by your tex coords / vert coords being mismatched, which it looks like they might be. As a test, set the angle to zero; the object should point along the positive X axis (to the right, ordinarily).

Looking at just the first couple of verts,

```
// Top-left vertex (corner)
glTexCoord2f(sourceX, sourceY);
glVertex2i( (-width / 2), (-height / 2));

//Bottom-left vertex (corner)
glTexCoord2f(sourceX, sourceY + texscaleY);
glVertex2i( (width / 2), (-height / 2));

```

It doesn't make sense that when you go from top-left to bottom-left, you're changing the Y part of the texture coordinates but the X part of the vertex coordinates. Shouldn't you change the Y part of both? And similarly for the other verts.
> 1 votes

---
Tags: opengl, rotation
---


title: help animating a player in Corona SDK

text:
# Question
Title: help animating a player in Corona SDK
Working on a game in the Corona SDK with Lua and I need help so the player animates on the line drawn. Right now he animates at the beggining and the end but not on the line.

Here is the player code:

```
function spawnPlayerObject(xPlayerSpawn,yPlayerSpawn,richTurn) --spawns Rich where we need him.
-- riches sprite sheet and all his inital spirites. We need to adjust this so that animations 3-6 are the only ones that animate when moving horizontally
    local richPlayer = sprite.newSpriteSet(richSheet1,1,6)
    sprite.add(richPlayer, "rich", 1,6,500,1)
    rich = sprite.newSprite(richPlayer)
    rich.x = xPlayerSpawn
    rich.y = yPlayerSpawn
    rich:scale(_W*0.0009, _W*0.0009) -- scale is used to adjust the size of the object.
    richDir = richTurn
    rich.rotation = richDir
    rich:prepare("rich")
    rich:play()
    physics.addBody( rich, "static", { friction=1, radius = 15 } ) -- needs a better physics body for collision detection.
end

```

And here is the code for the line:

```
function movePlayerOnLine(event)
    --for the original image replace all rich with player.
 if posCount ~= linePart then
    richDir = math.atan2(ractgangle_hit[posCount].y-rich.y,ractgangle_hit[posCount].x-rich.x)*180/math.pi
    playerSpeed = 5
    rich.x = rich.x + math.cos(richDir*math.pi/180)*playerSpeed
    rich.y = rich.y + math.sin(richDir*math.pi/180)*playerSpeed
        if rich.x < ractgangle_hit[posCount].x+playerSpeed*10 and rich.x > ractgangle_hit[posCount].x-playerSpeed*10 then
            if rich.y < ractgangle_hit[posCount].y+playerSpeed*10 and rich.y > ractgangle_hit[posCount].y-playerSpeed*10 then
            posCount = posCount + 1
        end
    end

```

I don't think anything has changed recently but I have been getting an error when testing of "attempt to upvalue "rich" a nil value" on the second line, `richDir =` etc.

# Answer
Is movePlayerOnLine getting called before spawnPlayerObject? That would explain why rich is nil as it hasn't been assigned a sprite object yet.
> 0 votes

---
Tags: animation, lua, corona-sdk
---


# Question
Title: Why does my position interpolation code result in "jumpy" motion?
I am developing an android game with box2d and use a fixed timestep system for advancing the physics.

However as I use this system it requires the box2d positions to be interpolates. I read this article and have implemented an interpolation method very much like the one in the article.

The method seems to work nicely on the computer but on my phone the positions of objects are very jumpy. There is of course a big frame rate difference between PC and phone, but I think this algorithm should not mind that.

Here is the just of the code if you don't feel like looking at the article :

```
void PhysicsSystem::smoothStates_ ()
{
    const float oneMinusRatio = 1.f - fixedTimestepAccumulatorRatio_;

    for (b2Body * b = world_->GetBodyList (); b != NULL; b = b->GetNext ())
    {
        if (b->GetType () == b2_staticBody)
        {
            continue;
        }

        PhysicsComponent & c = PhysicsComponent::b2BodyToPhysicsComponent (* b);
        c.smoothedPosition_ =
            fixedTimestepAccumulatorRatio_ * b->GetPosition () +
            oneMinusRatio * c.previousPosition_;
        c.smoothedAngle_ =
            fixedTimestepAccumulatorRatio_ * b->GetAngle () +
            oneMinusRatio * c.previousAngle_;
    }
}

```

Does anyone know why my game is acting like this?

Thanks for the help

EDIT: Here is some logging as suggested in the comments bellow log data

EDIT2 : This log shows the jumpy effect I think ( you can see the position diff is sometimes positive and sometimes negative - and the object are just falling, it should be constant)log data 2

# Answer
> 4 votes
Looking at your second log file, I'm wondering if you're calling `resetSmoothStates()` in the right place?

On lines 42, 46, 50, and 54 you can see that the `original position` stays at a constant `[661.2183]`, indicating there hasn't been a physics update. On line 43, it looks like you're smoothing between the previous `original position`, `[671.2361]`, and the new one, `[661.2183]`. But on line 47 the interpolated value snaps to the new position, `[661.2183]`, and stays there until you get a new physics update.

Make sure `previousPosition_` is only being updated when there's a new physics update, not every frame. (i.e make sure you're only calling `resetSmoothStates()` inside of the `for (int i = 0; i < nStepsClamped; ++ i)` block)

# Answer
> 3 votes
**Problem:**

Your computer can achieve the target fixed physics framerate, but your phone cannot.

**Solutions:**

1. Reduce the physics framerate (Increase `FIXED_TIMESTEP`).
2. Reduce the physics calculations needed per frame.
3. Do you absolutely need interpolation? Just render the uninterpolated state. Interpolation is only for making the rendering look smoother. Dropping it could significantly reduce the calculations required per frame.
4. Get a faster phone!

**Explanation:**

Check if the phone is hitting the `MAX_STEPS` constant. If it is, that means the phone cannot complete the physics calculations fast enough to achieve the (logical) fixed framerate. As a result it's cheating the physics simulator of some simulation time by capping how much more time can be added to the accumulator. This will of course change the resulting physics.

Glenn Fiedler explains it pretty well:

> The spiral of death occurs when your physics simulation cannot keep up with the steps it’s being asked to take. If your simulation is told: “OK, please simulate X seconds worth of physics” and if it takes Y seconds to do so where Y \> X, then it doesn’t take Einstein to realize that over time your simulation falls behind. In order to ensure a stable update, I recommend having some headroom. You really need to ensure that it takes *significantly less* than X seconds of real time to update X seconds worth of physics simulation. If you can do this then your physics engine can “catch up” from any temporary spike by simulating more frames. **Alternatively you can clamp at a maximum # of steps per-frame and the simulation will appear to slow down under heavy load.** Arguably this is better than spiraling to death, assuming of course that the heavy load is just a temporary spike.

---
Tags: android, box2d, interpolation, fixed-timestep
---


# Question
Title: How do I implement side scrolling in a javascript platformer?
I'm building a side scrolling platformer with Javascript and the canvas element for a school project. I have the character all sorted out. He runs left and right, and has a different sprite set for standing still. The game has gravity, and I can jump. Now what I can't get my head around is how to implement side scrolling.

The game world will be tile based. Each tile will be 20x20 pixels. When the character gets to the edge of the screen, it should scroll with the character to explore the level further.

Can anyone point me in the right direction to a resource that explains how to programmatically do this? Language specific to Javascript would be good, but anything would be a help.

# Answer
> 1 votes
Pulled from some of last year's code, I was prototyping a top down scroller in JS/Canvas. The principles the same, you translate your canvas by some value representing your offset from the world origin, and then draw images to it, and lastly restore the canvas's transform state to what it was originally.

```
this.context = this.canvas.getContext('2d');
...
context.save(); //save the existing canvas transform state (identity matrix)
context.translate(x, y);
context.rotate(angle);
context.translate(-(sprite.width/2), -(sprite.height/2)); //centring
context.drawImage(image, 0 ,0);

//remove the just-created transforms so you're back to working with an identity
//matrix -- or whatever matrix you had in place before .save() -- they're nestable.
context.restore();

```

(The context acts like a stack to store to the transformations -- which is really just a multiplication of matrices where if you save the state of the master matrix, and multiply further matrices into it, you can remove them by restoring the saved state. Undo function for matrices.)

I remember that there were some issues for me with ordering, i.e. generally you will translate a sprite to centre it first, then rotate it, then position it in screen space, however as you can see above the order from my working code was actually the reverse order. Just a heads up so you know you'll probably have to fiddle this a bit to get it right.

PS. I can't recall whether `drawImage()` accepts negative coordinates, but if so you should be able specify your sprite centring there and remove the second call to `translate()`.

---
Tags: javascript, html5, html-canvas, side-scroller, platformer
---


# Question
Title: What are the fundamentals of a Quad Billboarding effect?
I'm taking my first venture in to writing a shader and what I really need to do is create a billboarding effect. A thorough Google search turns up a number of threads on the topic and they always end with

A) Figured it out. Thread closed.

B) Anyone?

C) "long language/system-specific answer without explanation"

Most commonly, people are directed to Riemers which is fine, except his code isn't compatible with XNA 4.0 (what I'm using) and he doesn't explain the shader itself.

Can anyone explain/direct-me-to a language/system agnostic answer of how quad billboarding works?

**EDIT:** For others so they don't need to dig through the comments: NtscCobalt pointed out that I was attempting to use an orthographic camera when applying the shader. This essentially voided some of the effects of the shader. After changing to a perspective-based cam, the shader worked as it should have.

# Answer
> 1 votes
Here is a simple solution that doesn't require any changes in code to change an object from 3d to billboard. It is probably a hack and might not work in every situation.

Set the constant 'WorldView' to the WorldMatrix\*ViewMatrix and 'Projection' to your Projection Matrix. No additional code required. This shader doesn't include lighting but you could use the same lighting code from per-pixel lighting pretty easily. This correctly works with textures by the way.

```
float4x4 WorldView  : WorldView;
float4x4 Projection : Projection;

texture texture0 : DIFFUSE <
    string ResourceName = "default_color.dds";
    string UIName =  "Diffuse Texture";
    string ResourceType = "2D";
>;

sampler2D colorMap = sampler_state
{
    Texture = <texture0>;
    MagFilter = Linear;
    MinFilter = Anisotropic;
    MipFilter = Linear;
    MaxAnisotropy = 16;
};

struct VertexShaderInput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TextureCoordinate : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput IN)
{
    VertexShaderOutput OUT;
    OUT.Position = mul(IN.Position + float4(WorldView[3].xyz, 0), Projection);
    OUT.TextureCoordinate = IN.TextureCoordinate;

    return OUT;
}

float4 PixelShaderFunction(VertexShaderOutput IN) : COLOR0
{
    return tex2D(colorMap, IN.TextureCoordinate);
}

technique BasicShader
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

**Edit:** To clarify the way this works is by multiplying the vertices position by the worldview matrix position but ignoring either's rotation and scale. That result is then multiplied by the projection matrix. In short: any object that faces the camera in model space that then uses this shader will face the camera.

# Answer
> 1 votes
In the Riemers tutorial, CylBillboardVS is moving each vertex so that the quad faces the camera. It calculates the vectors for how the quad should be facing (upVector points up and sideVector points to the right, perpendicular to the camera direction):

```
float3 upVector = xAllowedRotDir;
float3 sideVector = cross(eyeVector,upVector);

```

Then it moves the vertex according to where it is in the texture:

```
float3 finalPosition = center;
finalPosition += (inTexCoord.x-0.5f)*sideVector;
finalPosition += (1.5f-inTexCoord.y*1.5f)*upVector;

```

So, if the vertex has UV-coordinates at the top-left of the texture, it'll move to the left (perpendicular to the camera direction) and up along the upVector.

---
Tags: graphics, graphic-effects, billboarding
---


# Question
Title: Why isn't my mouse input working as expected in a DX10 game?
I've made myself a camera for a DirectX 10 game, and the keyboard control works fine. However, I can't see to get the mouse to work. My biggest problem is I can't find out how to hide the mouse on the display to allow a crosshair (I don't need a visual one) and make movement like it would be in any other common 3D game. I looked at this tutorial, but it doesn't seem to work (The mouse part, that is). Everything I try just seems to result in the camera spinning very fast...

I'm using C++ and DirectInput.

# Answer
> 5 votes
You should *not* use DirectInput. It has been completely deprecated in favor of RAWINPUT.

The answer that uses `WM_MOUSEMOVE` is not the same as RAWINPUT and I expect it to not be fast enough.

An example using RAWINPUT in a Win32 app is available on my blog

# Answer
> -1 votes
Edit: Hide/Show mouse using ShowCursor - http://msdn.microsoft.com/en-us/library/ms648396

Keep resetting the mouse position to the center of the screen if you are working in a relative movement mode and track the movement.

This is pretty much Win32 related not having anything to do with Direct3D. I'm personally using it along side Direct Input which takes care of joysticks / gamepads.

Here is part of the code I'm using

```
    case WM_MOUSEMOVE:
    {
        //Most other messages are only sent to windows with the current focus
        //but mouse move is sent whenever the mose is hovering over, so we need
        //to ignore it if we don't have focus
        if (!IsWindowActive)
            break;

        //X and Y can be relative or absolute
        if (!MouseAbsolute)
        {
            if (IgnoreNextMouseMove)
            {
                IgnoreNextMouseMove = false;
                return 0;
            }

            POINT temp;
            GetCursorPos(&temp);
            // WM_MOUSEMOVE is 2 shorts, so I think it is safe to assume all mouse cooridnates are words
            int16 MouseX = (WORD)temp.x;
            int16 MouseY = (WORD)temp.y;

            //Add new changes to any existing
            //InputDriverInteral resets these to 0 when the axis is read
            uint16 cX = wX + wLength/2;
            uint16 cY = wY + wHeight/2;

            // This is a float array
            Axis[IA_MOUSE_X] += (MouseX - cX) / (float)wLength;
            Axis[IA_MOUSE_Y] += (MouseY - cY) / (float)wHeight;

            // This is a struct array with a float and a bool
            m_AxisMap[IA_MOUSE_X].Value = pDriver->Axis[IA_MOUSE_X];
            m_AxisMap[IA_MOUSE_X].Changed = true;
            m_AxisMap[IA_MOUSE_Y].Value = pDriver->Axis[IA_MOUSE_Y];
            m_AxisMap[IA_MOUSE_Y].Changed = true;

            // Set cursor position will send WM_MOUSEMOVE so we need to ignore that message
            IgnoreNextMouseMove = true;
            SetCursorPos(cX, cY);

        }else
        {
            int16 MouseX = LOWORD(lParam);
            int16 MouseY = HIWORD(lParam);

            //Get our absolute position within the window
            Axis[IA_MOUSE_X] = (float)MouseX / wLength;

            //Do the same as above but for y (note that windows is top left but we want from bottom left)
            //Get our absolute position within the window
            Axis[IA_MOUSE_Y] = (float)MouseY / wHeight;

            // Flag these axis as changed
            m_AxisMap[IA_MOUSE_X].Value = pDriver->Axis[IA_MOUSE_X];
            m_AxisMap[IA_MOUSE_X].Changed = true;
            m_AxisMap[IA_MOUSE_Y].Value = pDriver->Axis[IA_MOUSE_Y];
            m_AxisMap[IA_MOUSE_Y].Changed = true;
        }

        //Send an event notification
        pDriver->SendThreadingEvent();
    }
    break;

```

It works pretty well and the only issues I've had is if the user moves the mouse at an insane rate. The windows mouse position is limited to the size of the user's desktop so it cannot capture movement beyond that.

If you want to see the complete code for better context take a look: http://code.google.com/p/cobaltlibrary/source/browse/trunk/Drivers/Source/Input/DInput8/DInput\_WinProc.cpp

---
Tags: c++, camera, directx10, mouse
---


# Question
Title: Changing properties for multiple objects in unity 3d free?
So my team and I need to assign values to specific values in the inspector to large numbers of objects.

For example, we have a script that's assigned to all the walls, and all the floors.

We want to select all the walls in the Scene view and assign the value "1" to a variable in the inspector and then go and select all the floors and assign the value "2" to the same variable, for those objects.

Right now, when we select multiple objects and assign a value to the variable in the inspector, it just changes it for the last selected object.

We've got (potentially) hundreds of object that we need to do this to and it would suck to have to go in and change the values one at a time.

The equivalent I'm thinking of is the Attribute Spreadsheet in Maya, where you can see a list of objects, and assign the same value to a bunch of their attributes.

Hope somebody out there has an answer for this! Haven't been able to find one yet!

# Answer
> 4 votes
I don't know the specific limitations of Unity Free, but I wrote a little editor tool to do something like that.

Basically it consists of an editor window with a bunch of object fields setup to take game objects.

Whenever one of those object fields changes, it uses something like `GetComponent<MonoBehaviour>()` to determine what components are on those objects. It then populates a list of which components are shared between all of the game objects. When the user selects the field, it uses standard .NET reflection to determine which fields are either 1) public or 2) marked with `SerializeField`.

From there, of those fields, it displays editor fields for those types that make sense. So int editor fields for int fields in the class, etc. I think I store this in a `Dictionary<Type,object>` or something similar. I may store a bool with it as well so that you can check which fields you want to actually be applied.

Then when the user clicks the editor button, it goes through each of those game objects, gets that component, and sets the field value to be what's in the editor gui fields. I think I also had to do this with reflection, I don't have the code in front of me.

Now if you're going for something a little less general, you can do something similar where you only check for the predefined component instead of using reflection, but the concepts would be the same.

Unfortunately I couldn't find any way of showing something like the inspector gui shows for a given component without using a specific instance of that component, and Unity doesn't have any nice built in editor fields for things like arrays of serializable types and that kind of thing.

---
Tags: unity
---


# Question
Title: Getting rid of dead objects in a game effectively?
I'm using a for loop or foreach loop (doesn't matter) to loop through all my objects when they need to be updated or drawn. However, when an object gets killed, I want it to get removed from the collection again.

I do this by adding the object to a dead-objects list, and then, when everything has been drawn and updated, I go through everything in this list, removing the objects in the list from the original source as well.

Is there a better way of doing this?

# Answer
First of all: terminology. If you say "garbage list", people will think you are talking about the garbage collector. Let's call it the "dead list".

As you have probably discovered, hence your question, you cannot remove items from a collection while you are iterating through it. If your collection is a `List<>` then the simplest way to remove items from it is:

```
for(int i = list.Count-1; i >= 0; --i)
{
    if(list[i].IsDead)
        list.RemoveAt(i);
}

```

Note that you iterate *backwards*. You can remove items while iterating forward, but it's messier and requires a `goto`. You cannot do it with `foreach`.

You can either do the removal separately from your update loop. Or you can merge it into your update loop. Always do the `RemoveAt` at the end of the loop - after that point in the loop, `list[i]` cannot be considered valid (it becomes valid again on the next iteration).

Note, also, that each object has its own `IsDead` flag (if you are using the disposal pattern, you could make it `IsDisposed`) - you don't actually need to maintain a "dead list" at all.

Using a flag on each item is preferable for performance, as you avoid having to search through the list to do removal. And it is also preferable for design - it means that each object can easily check if it is dead - so you don't accidentally call any methods on it (if these objects are implementing the disposable pattern, they could throw `ObjectDisposedException` in this case).

If you have a collection other than a `List<>`, then removing dead items from that collection may still involve the creation of a dead list (as removal during iteration may not be possible). In my opinion, it is nicer, design-wise, to create the dead list right before it gets used, by iterating over the collection looking for `IsDead` flags, rather than trying to maintain the list as objects are killed.

Once you are finished with a dead list, you should `Clear()` it, and then keep it around to re-use it later on.
> 11 votes

# Answer
99.9% of the time, the garbage collector (GC) will take care of everything without hassles. Just let it do its work once you've deleted/nulled those objects. There is a latency in cleanup that depends on a number of factors (how many blocks of memory have been assigned for instance) but you don't need to typically even know about that, let alone worry about it. It's designed to just work. Which is one reason you're using C# and not C.

Re GC performance in general, don't concern yourself overly unless you happen to know (through profiling) that it is creating a bottleneck -- this is only in quite demanding games, generally. If this is the case, look into GC.Collect(), and its various pitfalls, so you know when it is appropriate to use it. I suggest googling "force gc xna", there is plenty of material out there.
> 0 votes

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


# Question
Title: How can I determine the velocity after impact of a 2D ball collision?
Consider two balls moving towards each other. Each has a given mass and velocity. Assuming the balls collide, how can you determine what direction the balls will take afterwards? (taking into consideration the mass & velocity)

I realise it's quite a big question, perhaps someone could direct me to an appropriate tutorial.

# Answer
> 3 votes
I definitely recommend reading Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres. It will give you a lot of information about circle to circle collisions, and how to handle them.

# Answer
> 0 votes
This site has a good tutorial just for your question, I like it because it has a lot of ***helpful diagrams*** to help you understand the concept, and gives plenty of example code:

The Physics of elastic collisions between particles

# Answer
> 0 votes
I think what you are looking for has already been answered on StackOverflow.

Hope that helps.

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