# Question
Title: How to work with two layers or more in cocos2d?
I want to make a game in cocos2d. I don't know too much about it.

My question is related to communication between two layers or more. For instance, let's say I want a layer with a scrolling road and another on top with scrolling clouds.

Is there anything built-in cocos2d for doing that, or any reference link?

# Answer
> 2 votes
In cocos2d you can add a layer/node to another layer/node. So for instance, your parent layer could contain the scrolling road and have a child layer that scrolls the clouds. With this you have a reference to both your parent layer and child layers to work with. It all really depends though.

---
Tags: 2d, cocos2d-iphone, graphics-programming
---


# Question
Title: Offset Forward vector of object based on Rotation
I'm using the Bullet 3D physics engine in a iOS application running openGL ES 1.1

Currently I'm accepting info from the gyroscope to allow the user to "look around" a 3d world that follows a bouncing ball (note: it only takes in the yaw to look around 360 degrees). Im also accepting information from the accelerometer based on the tilt to push the ball. As of right now, to move forward, the user tilts the devise forward (using the accelerometer); to move to the right, the user tilts the devise to the right and so on. The forward vector is currently along it's local Z-axis.

The problem is that I want to change the ball bounce based on where the user has changed the view. If I change the view, the ball bounces in the fixed direction.

I want to change the forward facing direction so that when a user changes the view (say to the look at the right of the world, the user rotates the device), tilting the devise forward will result in a forward force in that direction.

Basically, I want the forward vector to take the rotation into consideration.

Sorry if I didn't explain the issue well enough, its kind of confusing to write down.

# Answer
Figured out the answer for anyone who gets the same issue.

If you get your RigidBody's btTransform and then multiply it by your force btVector3 and subtract the RigidBody origin from that, the return will be your force relative to your object's orientation. Now just apply this as a centeralForce/Impulse and it goes in the new direction.
> 0 votes

---
Tags: opengl-es, ios, bullet-physics
---


# Question
Title: Low CPU/Memory/Memory-bandwith Pathfinding (maybe like in Warcraft 1)
Dijkstra and A\* are all nice and popular but what kind of algorithm was used in Warcraft 1 for pathfinding?

I remember that the enemy could get trapped in bowl-like caverns which means there were (most probably) no full-path calculations from "start to end". If I recall correctly, the algorithm could be something like this:

A) Move towards enemy until success or hitting a wall

B) If blocked by a wall, follow the wall until you can move towards the enemy without being blocked and then do A)

But I'd like to know, if someone knows :-)

\[edit\] As explained to Byte56, I'm searching for a low cpu/mem/mem-bandwidth algo and wanted to know if Warcraft had some special secrets to deliver (never seen that kind of pathfinding elsewhere), I hope that that is more concordant with the stackexchange rules.

# Answer
Actually this turned out to be a more interesting question than I thought.

Video

I forgot about the "right hand rule" for pathfinding, but it appears that the game uses it.

Say you're lost in a basement and it's dark. The easiest way to find an exit (if there is one!) is to place your hand on the nearest wall and "follow the wall", following all it's turns and going through it's crevices, until you find an exit. The only time this doesn't work is if you happen to grab a pole ("island") in the basement, then you'll be walking around that pole forever.

I think the game uses some variation of this "follow the wall" rule until the unit can find a beeline to the destination point.
> 10 votes

# Answer
I don't think "how did X game accomplish Y?" is technically in the scope of this stack, but I'll hazard a guess as to why some pathfinding algorithms get stuck in a bowl: They run something like A\*, but only up to a certain depth. This limits the amount of processing time spent pathfinding, but doesn't guarantee exhaustive search \[which might be a good thing, Starcraft had that issue where dragoons would wander to the other side of the map trying to find a path\]

In the top scenario, the top orc's search radius is too small. The "best" visible point is marked A, the "best" navigable point is on the closer side of the wall across from A.

In the bottom scenario, point A is now navigable, but point B should be the "best" navigable point, and that would be the path a constrained A\* would take.
> 4 votes

---
Tags: algorithm, path-finding
---


# Question
Title: moving box2d bodies in an arc or curved path
How can I make a b2Body move in a arc-like or curved path? I have heard about cocos2d Bezier curve function (ccBezier) but this is for moving cocos2d sprites. Or can it be modified to move box2d bodies? Any help is appreciated. Thank you.

# Answer
For box2d with gravity enabled, if you apply force to an object in the upwards direction, you will automatically get a parabolic trajectory.

Create a b2vec2 and apply that as the force to your body.

If you want to move the body or sprite manually, then use parabolic formulas to calculate your position in your update method.
> 1 votes

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


# Question
Title: How to get faster iteration times in android development
I'm creating a game on the android platform that uses the resources/raw folder for assets and scripts. The problem is that every time I change something I have to rebuild the application to test the new variant. Of course this is bad for iteration times.

Any ideas about what I can do to avoid rebuilding every time I change something? This \*.apk format is getting on my nerves now that I have to recreate it every time I change a word in my scripts.

Or at least how to make eclipse auto-rebuild every time I change something in my resources folder so that I don't have to go to Project-\>Build every time?

# Answer
Have you tried to use something like libgdx? It allows you to build your app with a PC runtime and then you can publish to the device less often. Makes tweaks like you are dealing with much easier to handle.
> 2 votes

# Answer
Not sure if this applies to Android development, but this is what I do when I'm doing Java development with Eclipse. I select `Project->Build Automatically`. If you're making the changes to your scripts using Eclipse as your editor, **on save** the project will build automatically. However, if you're editing the files outside of Eclipse, you will have to select your project in the Project Explorer and press `F5` to refresh external changes. If changes are detected, it will build automatically.
> 6 votes

# Answer
My approach to this problem was to support native builds of the same project on Linux/Windows. The same assets I use in Android are also used on my development platform, so I can build and deploy within seconds without having to spend lots of time rebuilding Android asset files, APK's, push to phone / emulator, etc.
> 1 votes

# Answer
Similar to what stephelton said, I think the best way to do this is to have a Java-only (not Android) version of your game that you run on your PC.

If you think about it, the only parts of your game that actually are specific to the Android OS are implementing rendering calls and converting raw input to serialized Input. **The game loop, framework, messaging system, physics, AI, sounds, etc. should all be the same,** regardless of the target platform.

It may seem like a pain to have to port your game from Java on your computer to Android, but I think you'll end up being able to work a lot faster in the end.

If you don't decide to do this, then try stripping your app of all unnecessary/extra resources, activities, etc and having the app boot right to the game. This will decrease installation times, boot times, and time-to-finding-a-bug. For example, that 3 second splash displaying every time you open your game will add up quickly.
> 1 votes

---
Tags: android, pipeline, eclipse
---


title: Unit Testing with Cocos2D

text:
# Question
Title: Unit Testing with Cocos2D
How to implement Unit Testing with Cocos2D framework? What are the good practices?

Is there any testing framework like JUnit Framework at Eclipse for Android?

# Answer
If you are using XCode, it has a testing framework called OCUnit built in. Otherwise there are other framework options. I would try adding a mocking framework if it is not already included by now.

This is a good start:

http://www.raywenderlich.com/3716/unit-testing-in-xcode-4-quick-start-guide

http://developer.apple.com/library/ios/#DOCUMENTATION/DeveloperTools/Conceptual/UnitTesting/00-About\_Unit\_Testing/about.html
> 1 votes

---
Tags: cocos2d-iphone, ios, cocos2d, unit-testing
---


# Question
Title: What methods should save/load a game state
There are a lot of articles about how to save a state of a game and they are pretty good. But I have one conceptual misunderstanding where should I save the state?

My game has number of screens and pair of them are *MainMenuScreen* and *MainSceneScreen* these are inherited from *Screen* class. *MainMenuScreen* is shown at start of the game the *MainSceneScreen* little later.

What is the problem? I navigated to *MainSceneScreen*, forced Android to stop the application (I change a language settings on the device to achieve it, please let me know if I'm wrong). After that I select the application again and I can see *MainMenuScreen* is shown. But I want *MainSceneScreen* to be shown.

I suppose I should override resume method. But what class I should override? I have class *PsGame* that extends *Game* class of libgdx. I put breakpoints to its resume method and it turned out that method was not called. I investigated the problem and I've found little strange code in *onResume* method of *AndroidApplication* class of libgdx:

```
    if (!firstResume)
        graphics.resume();
    else
        firstResume = false;

```

My debugger said *firstResume* was true and didn't go to \*graphics.resume()\*line.

Sorry for a lot of words but could you answer following question:

1. What did I do wrong?
2. What methods should I override?

Thank you in advance.

# Answer
> 1 votes
I override resume() in the class tha extends Game in libgdx, and when i press the home button and enter the app again it executes and it enters that method.

---
Tags: android, state, libgdx, savegame
---


title: Rotate model using quaternion

text:
# Question
Title: Rotate model using quaternion
Currently I have this to rotate my 3D model that rotates on it's local axis independent from the world's axis:

```
// Rotate model with Right Thumbstick
modelRotation -= pController.ThumbSticks.Right.X * mRotSpeed; // float value

```

What I'm trying to do is rotate the model using quaternion and not by a matrix.

I've searched for tutorials, but have found none that explains thoroughly on how to achieve this. Does anyone know how to I can use quaternions to rotate my model or a complete tutorial?

# Answer
> 3 votes
A quaternion has a vector part and a scalar part. To represent a rotation, a quaternion has to be of unit length. A quaternion that rotates by angle alpha around an axis represented by a normalized vector v is calculated like this:

```
q = [v*sin(alpha/2), cos(alpha/2)]

```

The rotation follows the right hand rule.

Now to apply this quaternion to a vector or a point you take your x, y and z and write it as a quaternion. Given a vector v, you can write it in quaternion form as such:

```
qv = [vx, vy, vz, 0]

```

Now to transform this vector by a quaternion you premultiply it by the rotation quaternion and postmultiply it by the inverse of the rotation quaternion, as such:

`v_rotated = q*qv*q(-1)`, the (-1) means the quaternion is inversed.

To get an inverse of a quaternion you have to calculate it's conjugate and divide it by the quaternion's length squared, but since our quaternion is of unit length, this just means calculating the conjugate. You calculate the conjugate by negating the vector part of the quaternion.

You do this for every vertex like you would with a matrix.

This is from Jason Gregory's "Game Engine Architecture".

# Answer
> 3 votes
```
//in the fields section:
Quaternion modelQuat;

//in the update method:
// Rotate model with Right Thumbstick
    modelRotation -= pController.ThumbSticks.Right.X * mRotSpeed; // float value

    modelQuat = Quaternion.CreateRotationY(modelRotation);

//Later, in the draw call when setting the effect:
    effect.World = Matrix.CreateFromQuaternion(modelQuat);// (and if needed) * Matrix.createTranslation(someLocationVector);

```

Is this something like what your looking for?

---
Tags: xna, quaternion
---


# Question
Title: OpenGL 3.0+ framebuffer to texture/images
I need a way to capture what is rendered on screen, i have read about glReadPixels but it looks really slow.

Can you suggest a more efficient or just an alternative way for just copying what is rendered by OpenGL 3.0+ to the local RAM and in general to output this in a image or in a data stream?

How i can achieve the same goal with OpenGL ES 2.0 ?

EDIT:

i just forgot: with this OpenGL functions how i can be sure that

* I'm actually reading a complete frame, meaning that there is no overlapping between 2 frames or any nasty side effect
* I'm actually reading the frame that comes right next to the previous one so i do not lose frames

# Answer
> 4 votes
The OpenGL 3.3 way:

The OpenGL ES 2.0 way:

* I'm not sure how to achieve the same in OpenGL ES 2.0, but there are probably OGL extensions which allow you to do the renderbuffer/framebuffer part as described in the OGL 3+ way.

# Answer
> 3 votes
You can boost the performance of glReadPixels a lot by using Pixel Buffer Objects. This tutorial gives an example on how to do it. The idea is to use two PBOs. After a frame is rendered (either to the screen or to an FBO), bind one PBO and read the pixels to the PBO. This starts an asynchronous data transfer. In the next frame the data has been transferred and you can map the buffer for reading the data from it fast and also issue another read command for reading the current data to another PBO. Note that PBO itself doesn't speed up the transfer, but it allows asynchronous data transfer.

With this approach I can capture HD-video from OpenGL with 60 FPS without noticing any performance penalty. With ffmpeg I can also encode it realtime as an .mp4 video in another thread.

---
Tags: textures, opengl-es, opengl-es2, image, frame-buffer
---


# Question
Title: Collision detection - player gets stuck in platform when jumping
So I'm having some problems with my collision detection with my platformer. Take the image below as an example.

When I'm running right I am unable to go through the platform, but when I hold my right key and jump, I end up going through the object as shown in the image, below is the code im using:

```
if(shapePlatform.intersects(player.getCollisionShape())){

     Vector2f vectorSide = new Vector2f(shapePlatform.getCenter()[0] - player.getCollisionShape().getCenter()[0],
             shapePlatform.getCenter()[1] - player.getCollisionShape().getCenter()[1]);
            player.setVerticleSpeed(0f);

            player.setJumping(false);
            if(vectorSide.x > 0 && !(vectorSide.y > 0)){
                 player.getPosition().set(player.getPosition().x-3, player.getPosition().y);

            }else if(vectorSide.y > 0){
                player.getPosition().set(player.getPosition().x, player.getPosition().y);

            }else if(vectorSide.x < 0 && !(vectorSide.y > 0)){
                 player.getPosition().set(player.getPosition().x+3, player.getPosition().y);
            }

}

```

I'm basically getting the difference between the centre of the player and the centre of the colliding platform to determine which side the player is colliding with. When my player jumps and walks right on the platform he goes right through. The same can also be observed when I jump on the actual platform, should I be resetting the players y in this situation?

# Answer
After going through the problem, it was clear that the standard intersect method provided by slick wouldn't do. Instead, I wrote a SAT collision detection method to detect collisions. But more importantly, the algorithm returned a correction vector to correctly place the player outside the colliding shape. This seems more natural than to adjust the players x/y buy some value.

Thanks to all other answers as they have all helped me in solving this issue.
> 0 votes

# Answer
I haven't spent a ton of time looking at your code, but just on brief inspection I would say you need to do more than just

```
player.getPosition().set(player.getPosition().x-3, player.getPosition().y);

```

You're assuming the player only needs to move back 3 units, which is probably incorrect. How incorrect it is depends on how much they've moved in your latest update. If they moved 10 units and you move them back 3, they are still 7 units into the block. You need to continue moving them back until there is no longer a collision.

Perhaps something like

```
while(shapePlatform.intersects(player.getCollisionShape())
{
    player.getPosition().set(player.getPosition().x-3, player.getPosition().y);
}

```

Not super performant but once you get it working you can work on how fast it runs.

I also notice you're not doing any corrections for y. The up/down of your boxes/player is just as collidable as the right/left, so you should definitely factor that in. If your player is falling say 10 units per update, and they fall into the block 10 units, you'll stop them from falling but you never correct their y position to get them back on top of the block. Now they are stuck 10 units into the block with no way out. You should do the same type of correction - while there is a collision, walk them back until the collision is resolved.
> 1 votes

# Answer
You might want to do the following things when you detect a collision:

1. Restore the previous position of your character. This means, you need to have a field in your Character class that stores the previous position. You update this value every time before the character's position changes.
2. Apply some kind of effect to the character, so that it doesn't get "stuck" in that position. This could be a rebound effect (reverse the direction of the character's velocity, and perhaps multiply it by an arbitrary value). Or you could show a small animation (the character looks like he just run into a wall, some dust falls etc.).
> 1 votes

# Answer
Before reacting to the collisions, first position your player so that he will not be stuck again. This can be achieved as follows.

```
public void collision(GObject other){
    if (other instanceof wall){
        // check velocities
        if (dx>0){
            // collision occurred on the left
            this.x = other.x - this.width;
        } else if (dx<0){
            // collision occurred on the right
            this.x = other.x + other.width;
        }
        if (dy>0){
            // collision occurred on the bottom
            this.y = other.y - this.height;
        } else if (dy<0){
            // collision occurred on the top
            this.y = other.y + other.y;
        }
    }
}

```

Note that snap only the y-axis for the floors. If you know the difference between the floor and horizontal objects.
> 1 votes

# Answer
I wrote a lil engine called TwoTryEngine with Slick.The only thing i want to say about the engine is that my engine is checking the new positions before the player is moving to the new positions.This also solves a problem with moving on top problems, but my engine still has to get much more fixes.So i dont gonna upload it if you are interessted.like other guy before said use dx and this stuff.
> -2 votes

---
Tags: java, collision-detection, slick
---


title: How to code UI / HUD in Entity System?

text:
# Question
Title: How to code UI / HUD in Entity System?
I think I already got the idea of the Entity System inspired by Adam Martin (t-machine). I want to start using this for my next project.

I already know the basic of Entity, Components, and Systems. My problem is how to handle UI / HUD. For example, a quest window, skill window, character info window, etc. How do you handle UI events (eg. pressing a button)? These are stuff that doesn't need to be processed every frame. Currently, I'm using MVC to code UI but I don't think that'll be compatible for Entity System.

I've read that Entity System is embedded on a larger OOP. I don't know if UI is outside of ES or not. How do I approach this one?

# Answer
Maybe you're thinking too much in entity systems. Entities are meant to scope objects in game, like characters, enemies, scripts, bullets, triggers, etc.

Maybe if you make your UI separated, it will be way better and easier. You don't have to make EVERYTHING inside the entities scope.
> 17 votes

# Answer
While I think an Entity/Component UI might work, it would be difficult to make it so. Additionally, it's far enough removed from the components and systems you'd have for processing your game entities, it would essentially just be *another* entity/component system within your game. I can't imagine there would be a lot of overlap between the two.

Entity systems are awesome and it can be tempting to use them everywhere. After all, when you get a really sweet hammer, you're tempted to treat all your problems like nails. However, the EC system is just another tool in your programming bag. For the problems it's used to solve it works really well, but you have better tools for problems like UI.

The inheritance structure works really well for GUIs. Not only for creating the UI components but for laying them out too. It's really nice to be able to have UI components be children of other components so they can inherit properties like position, scale and opacity. If you were to try to set that up with a EC system, you'd have to break some rules of the EC system.
> 3 votes

# Answer
You can make a new interface function that is called whenever UI/HUD is drawn and allow custom/scripted components to implement that function. This requires an IMGUI system (there are lots of tutorials on it in Google, this is just the original presentation) to be used. With that, you can make windows as entities inside which you'll have your own UI-building component and a window frame renderer component.

As for not processing all of this every frame, you can render all UI to a different buffer which you'll update only on all kinds of input / data events. That is, whenever an event is received, it changes some variable to indicate that the window needs to be repainted the next frame. If that variable is true, it is then set to false and UI interfaces are called after that. If you want animations, it's important that you use this exact order of operations so that UI itself could trigger a repaint for the next frame.
> 1 votes

---
Tags: architecture, entity-system
---


title: Moving camera in large view

text:
# Question
Title: Moving camera in large view
In my cocos2d app I was wondering how to make a CCSprite move on the screen but have the screen focused on the CCSprite, so when the sprite moves the view moves with the CCSprite. Is there a tutorial to do this?

Thanks

# Answer
> 1 votes
There's a `CCFollow` action in cocos2d for this purpose. Usage is simple:

```
[myLayer runAction: [CCFollow actionWithTarget: heroSprite]];

```

For more information, have a look at the API docs.

# Answer
> 0 votes
For making such games you need to create some layers and then move the layers. Just like in a 2D side scrolling game the background layer moves(or changes) and only the y coordinate of the character is changed so that the character appears to be moving.

For such game you can refer to this post ---

http://johnehartzog.com/2009/10/2d-scrolling-game-with-cocos2d-tilemap-with-zoom/

and to find additional codes for the same you can check out the code snippet and the end of this page.

http://www.cocos2d-iphone.org/forum/topic/5363

# Answer
> 0 votes
If, for some reason, you wanted to manually make a camera system, the way to do it would be to set a camera x and y based on the position of the sprite you're trying to follow, and then draw everything at its normal position minus the camera x and y values.

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


# Question
Title: Thread.SetProcessorAffinity() equivalent for Windows?
I want to be able to use multiple cores in my XNA game, but it seems that Thread.SetProcessorAffinity() is only usable on xbox. That being said, is there any way to run a small chunk of my code on another core, or failing that, share the load between all cores?

# Answer
> 3 votes
SetThreadAffinityMask

That being said I'm confused by the second part of your question. Windows threads by default are set to run on all processors/cores. The thread affinity mask exists to allow you to specify that it can only run on specific cores.

This is useful in some rare cases where system calls return differently depending on the core/processor that the thread is currently running on such as QueryPerformanceCounter

**Edit:** After researching XNA's Thread.SetProcesorAfffinity I think you might just be misunderstanding how multiprocessing works in Windows. Most windows applications do not call SetThreadAffinityMask but instead just create threads and let the OS choose what core/processor (remember some machines have more than one processor) to run the thread on. Windows has a complex scheduler that suspends and resumes threads based off of thread priority to allow more threads than there are physical processors or cores. If you want to learn more I recommend reading one of the Windows Internal books or one of the powerpoints floating around on the web that explain Win32 Kernel.

---
Tags: xna, windows, multithreading
---


title: 3D Studio Max biped restrictions?

text:
# Question
Title: 3D Studio Max biped restrictions?
I have a stock biped character in 3D studio max which has a jump animation.

The problem I have with the jump animation is that there is actual y offset happening inside it which makes it awkward to play while the character is jumping since it's not only jumping in the game world but the jump animation is adding its own height offset.

I'm tryuing to remove the jump animations height offset, so far I've found the root node and deleted all its key frames which has helped a bit.

The problem I'm having now is that the character still has some height offset and if I try to lower it it has a fake 'ground' that isn't at 0 and the limbs sort of bend on the imaginary floor, si there a way to remove this restriction just for the jump animation?

Here's what I mean: https://i.stack.imgur.com/cQzzJ.png

Any idea for a fix? I'm using Unity 3D if that opens any other possibilities...

# Answer
Try, not to remove offset of root in animation, but to reanimate all root animation part of jumping, so that every frame feet would be on the ground. And don't change anything while not in animating mode in 3ds MAX because that may ruin all animation.
> 1 votes

# Answer
I'd recommend simply offsetting the bottom of your character within your engine. Use a locator node in side of the model and animate it to always be at the location of the character's feet then use the location of that locator as the 'base' of the character for physics calculations.

This allows some pretty cool things such as jump height entirely being defined by the animation.
> 0 votes

---
Tags: unity, animation, 3dsmax, biped, jumping
---


title: Edge flicker when moving Camera (2D)

text:
# Question
Title: Edge flicker when moving Camera (2D)
I have a Orthographic camera. I have a fixed landscape texture and a texture for a moveable object. If the object moves to the right the camera will also move with the object.

When I also draw an score text that should have fixed position on the screen, that score text position will be update too if the camera's position gets updated so that it looks like that it is fixed on the screen. But if I do that, I have some edge flickering at the text object. I'am using SpriteBatch!

Is there another approach to implement a fixed positioned object on the screen?

# Answer
I only hat to set a filter for the texture.

Pseudo: texture.setFilter(Linera\_Filter, Linear\_Filter)
> 2 votes

---
Tags: opengl, java, libgdx, spritebatch
---


# Question
Title: Implementing a wheeled character controller
I'm trying to implement Boxycraft's character controller in XNA (with Velcro Physics), as Bryan Dysmas did (minus the jumping part, yet).

My current implementation seems to sometimes glitch in between two parallel planes, and fails to climb 45 degree slopes. (YouTube videos in links, plane glitch is subtle).

How can I fix it? From the textual description, I seem to be doing it right.

(Note: my coordinates system is top for positive Y).

Here is my implementation (it **seems** like a huge wall of text, but it's easy to read. I wish I could simplify and isolate the problem more, but I can't):

```
public Body TorsoBody { get; private set; }
public PolygonShape TorsoShape { get; private set; }
public Body LegsBody { get; private set; }
public Shape LegsShape { get; private set; }
public RevoluteJoint Hips { get; private set; }
public FixedAngleJoint FixedAngleJoint { get; private set; }
public AngleJoint AngleJoint { get; private set; }

```

...

```
this.TorsoBody = BodyFactory.CreateRectangle(this.World, 1, 1.5f, 1);
this.TorsoShape = new PolygonShape(1);
this.TorsoShape.SetAsBox(0.5f, 0.75f);
this.TorsoBody.CreateFixture(this.TorsoShape);
this.TorsoBody.IsStatic = false;

this.LegsBody = BodyFactory.CreateCircle(this.World, 0.5f, 1);
this.LegsShape = new CircleShape(0.5f, 1);
this.LegsBody.CreateFixture(this.LegsShape);
this.LegsBody.Position -= 0.75f * Vector2.UnitY;
this.LegsBody.IsStatic = false;

this.Hips = JointFactory.CreateRevoluteJoint(this.TorsoBody, this.LegsBody, Vector2.Zero);
this.Hips.MotorEnabled = true;
this.AngleJoint = new AngleJoint(this.TorsoBody, this.LegsBody);
this.FixedAngleJoint = new FixedAngleJoint(this.TorsoBody);

this.Hips.MaxMotorTorque = float.PositiveInfinity;
this.World.AddJoint(this.Hips);
this.World.AddJoint(this.AngleJoint);
this.World.AddJoint(this.FixedAngleJoint);

```

...

```
public void Move(float m) // -1, 0, +1
{
    this.Hips.MotorSpeed = 0.5f * m;
}

```

# Answer
I personally don't like the wheeled approach. I use three edges. An infinite inertia prevents it from being rotated (float.MaxValue) and a restitution of 0 prevents if from bouncing. Also the edges are friction-less I set the velocity values in the code. People find realistic physics counter intuitive because they have been trained on what to expect by games like Mario, SMB, and such.

Out side of being more intuitive I also find it easier to work with artistically. I have a wall pushing animation that is triggered if either outside edge is getting hit. I have a sliding animation for the same condition as ling as the middle edge isn't hitting anything.

Also I found most people picked up on the movement a lot faster when I lerped to a max value and then clamped it there. I also lerp back down to 0 speed except when the player is in the air I don't use friction to slow the player. This prevented people from complaining the character was "slidy". Air behavior and ground behavior is the same except air movement speed is capped to the speed when the jump occurred and there is no lerp back to 0 horizontal speed.
> 1 votes

---
Tags: xna, physics, box2d, farseer-physics-engine, velcro-physics-engine
---


# Question
Title: 2D SAT Collision Detection not working when using certain polygons (With example)
My SAT algorithm falsely reports that collision is occurring when using certain polygons. I believe this happens when using a polygon that does not contain a right angle. Here is a simple diagram of what is going wrong:

Here is the problematic code:

```
std::vector<vec2> axesB = polygonB->GetAxes();
//loop over axes B
for(int i = 0; i < axesB.size(); i++)
{
    float minA,minB,maxA,maxB;
    polygonA->Project(axesB[i],&minA,&maxA);
    polygonB->Project(axesB[i],&minB,&maxB);

    float intervalDistance = polygonA->GetIntervalDistance(minA, maxA, minB, maxB);
    if(intervalDistance >= 0) return false; //Collision not occurring
}

```

This function retrieves axes from the polygon:

```
std::vector<vec2> Polygon::GetAxes()
{
    std::vector<vec2> axes;
    for(int i = 0; i < verts.size(); i++)
    {
        vec2 a = verts[i];
        vec2 b = verts[(i+1)%verts.size()];
        vec2 edge = b-a;
        axes.push_back(vec2(-edge.y,edge.x).GetNormailzed());
    }
    return axes;
}

```

This function returns the normalized vector:

```
vec2 vec2::GetNormailzed()
{
    float mag = sqrt( x*x + y*y );
    return *this/mag;
}

```

This function projects a polygon onto an axis:

```
void Polygon::Project(vec2* axis, float* min, float* max)
{
    float d = axis->DotProduct(&verts[0]);
    float _min = d;
    float _max = d;
    for(int i = 1; i < verts.size(); i++)
    {
        d = axis->DotProduct(&verts[i]);
        _min = std::min(_min,d);
        _max = std::max(_max,d);
    }
    *min = _min;
    *max = _max;
}

```

This function returns the dot product of the vector with another vector.

```
float vec2::DotProduct(vec2* other)
{
    return (x*other->x + y*other->y);
}

```

Could anyone give me a pointer in the right direction to what could be causing this bug?

**Edit:** I forgot this function, which gives me the interval distance:

```
float Polygon::GetIntervalDistance(float minA, float maxA, float minB, float maxB)
{
    float intervalDistance;
    if (minA < minB)
    {
        intervalDistance = minB - maxA;
    }
    else
    {
        intervalDistance = minA - maxB;
    }
    return intervalDistance; //A positive value indicates this axis can be separated.
}

```

**Edit 2:** I have recreated the problem in HTML5/Javascript: Demo

# Answer
> 2 votes
Your code suggests you're not using the axes from polygonA. You need to use all the uniques axes from polygonA and polygonB.

In your first example, polygonB has an appropriate axis to prove there is separation.

In your second example, polygonB does not have an appropriate axis to prove there is a seperation, but polygonA does.

Assuming polygonA is the square, anyway.

---
Tags: c++, 2d, collision-detection, separating-axis-theorem
---


# Question
Title: How do I make a Java gave without a JFrame?
I am working on an arcade-like game, and so far, I have been using JFrame. All the action occurs in the JFrame basically.

However, I've noticed that a lot of games that you install on a computer don't have a frame. When you play them on Windows, the game covers the entire screen (the start bar disappears and you can't access any other application on your computer).

I'd like to do that for my game. Is it possible to do so with Java? If so, how would I do this?

# Answer
You can set JFrame to fullscreen with `GraphicsDevice.setFullScreenWindow(jframe);`. For example:

```
// Set fullscreen mode with specified resolution
GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
device.setFullScreenWindow(frame);
device.setDisplayMode(new DisplayMode(1280, 720, 32, 60)); // 1280x720 32bpp @ 60Hz

```

Alternatively when you are using OpenGL, both JOGL and LWJGL have their own native window implementations for rendering. With these you don't need JFrame at all.
> 2 votes

# Answer
You can use an engine like jmonkeyengine. It made with Java and OpenGL
> 0 votes

---
Tags: java, platformer
---


title: File Path Characters

text:
# Question
Title: File Path Characters
I have a simple question that I can't find a answer to:

With the .NET Framework what is the difference in saying `"folder1/folder2/file"` and `"folder1\\folder2\\file"` in a file directory? Is there even a difference?

Also what does the "@" character do? I'm not sure if this is XNA specific or .NET specific but here is an example: `ContentManager.Load<Texture2D>(@"SpriteSheets/Tile");`

Thanks.

# Answer
> 4 votes
Here is a resource on what `@""`-style string literals are.

Basically they turn off escaping. So, for example, you only need `@"\"`, instead of `"\\"` to get the `\` character.

Another example: `@"\t"` gives you `\t`, whereas `"\t"` (no at symbol) gives you a tab character.

---

Internally XNA handles the difference between path separator characters. You can use `\` or `/` (or some crazy combination of both) and it won't matter.

(I'm pretty sure Windows itself doesn't care which character you use either.)

---
Tags: xna, .net, character, file
---


# Question
Title: How could you model "scent trails" in a game?
Say you want to create a 3D game, and have either players, or mobiles, be able to tract other entity by following their scent trails. Is there any known data-structure that matches this use case?

If you have only few individuals going about, you can probably do something like a map of 3D coord to entity ID, but real scent works differently, because it fades over time, but slowly. And most of the time, you can only know approximately what went there, and approximately how many things of that type went there. And the approximation becomes worst with time, until it's gone.

I imagine it's kind of like starting with an exact number, and slowly loosing the least significant digits, until you loose the most significant digit too. But that doesn't really help me, because entity IDs aren't normally encoded to contain the entity type, in addition to it's individual ID.

# Answer
> 10 votes
There's a lot of variety in how you could do this; I'm going to suggest the “obvious to me” choices, but there are lots of variations that could be designed. Disclaimer: I haven't actually implemented anything like this.

First, you need a data structure that covers your world. If you are doing NPC movement in a 3D space, then you probably have, or will eventually need, such a structure for pathfinding purposes — say, a navigation mesh. So, let's assume we can add a field for scents to that.

So, what do we put in that field? I propose a list of records (*scent*, *strength*, *time*). This list is kept at or below a maximum length, and sorted by *strength* — so weak scents will be discarded. The *scent* could be either something explicitly defined for each entity or entity type, or it could simply be the entity type — depending on what you want to be able to track distinctly. The *time* is a timestamp of when this scent record was last updated.

When an entity passes through an area (e.g. a given triangle of the navigation mesh), it's time to update the scent list. First, decrease all the strengths according to the amount of time passed according to the *time* value vs. the current time — exponential decay is probably a reasonable choice here. Then add the current entity's scent to the list, perhaps with a strength dependent on the entity type. Then if the list just got too long, discard the lowest strength.

To obtain a tracking result, find the scent in the list for the current location, then do the same for all of its neighbors, and go in the direction of the strongest scent (that isn't the direction the tracker just came from).

For extra realism:

* Diffusion: periodically transfer a fraction of the scent in each location to its neighbors. This confuses trails, but also means that stationary things can be sniffed out (finding food, dead bodies, etc). (It's even a recognized sort of AI to base actions entirely on this type of information — the landscape provides information about which way to go to obtain a particular resource, etc. I forget the name of it.) The main disadvantage is the time spent calculating diffusion everywhere.
* Strong scents should prevent the detection of weak scents; divide the strength of the sought scent by the strength of the strongest scent, and fail if it is too small. This could allow deliberately confusing one's scent trail.

# Answer
> 10 votes
I would modify a technique called influence mapping to create a map for scents. It will dissipate and fade naturally, blend and contest with other scents, and probably more. This sounds like it will do exactly what you need it to, but it may be more elaborate than what you are looking to implement. At the very least it should give you some good ideas, and it is pretty simple to implement on top of whatever structure you are currently using.

A tutorial/explanation I found helpful.

---
Tags: ai
---


title: UDK ParticleSystem Problem

text:
# Question
Title: UDK ParticleSystem Problem
I use below code to create my particles ( in fact, I don't know any other way.)

```
spawnedParticleComponents = WorldInfo.MyEmitterPool.SpawnEmitter(ParticleSystem'ParticleName', Location, Rotator );
spawnedParticleComponents.setTranslation(newLocation);
...

```

And unfortunately, I spawn many particles in game.

When I play my game, after some time, I see `Exceeded max active pooled emitters!` Warning in console .

To solve the problem, first, I tried `spawnedParticleComponents.DeactivateSystem();`, But it doesn't help. Then I try `WorldInfo.MyEmitterPool.ClearPoolComponents(false);`, But it doesn't either . :(

How can I destroy many spawned particles and avoid this warning ?

# Answer
I solve it!

Just do as below when you don't need a ParticleSystemComponent anymore .

```
spawnedParticleComponents.SecondsBeforeInactive=0;
spawnedParticleComponents.DeactivateSystem();
spawnedParticleComponents.KillParticlesForced();

```
> 1 votes

---
Tags: udk, particles
---


title: Why are game engines written in C++?

text:
# Question
Title: Why are game engines written in C++?
> **Possible Duplicate:**
> Why has the industry switched from C to C++?

Since many organizations have demonstarated Object orientation in C and we all know its ABI compatibility that C++ lacks, why game engines are written in C++??

Is there any reason other than easy object orientation??

# Answer
> 0 votes
Certainly there are going to be strong and varied opinions on the matter. Surely you can implement object oriented principles in C. Yet having the features built into the language helps facilitate the issue and the template support you will find hugely pivotal not only in your own code but in utilizing the most popular libraries today.

Just because you are using a C++ compile does not mean that you are using the C++ language features either. Some games are mainly written in C but only utilizing the C++ compiler benefits.

---
Tags: c++, c, oop
---


# Question
Title: Techniques for displaying vehicle damage
I wonder how I can displaying vehicle damage. I am talking about a good way to show damage on screen. Which kind of models are common in games and what are the benefits of them? What is state of the art?

One way I can imagine is to save a set of textures (normal/color/lightmaps, etc.) to a state of the car (normal, damage, burnt out) and switch or blending them. But is this really good without changing the model?

Another way I was thinking about is preparing animations for different locations on my car, something like damage on the front, on the left side/right side or on the back, and start blending the specific animation. But is this working with good textures?

Whats about physics engines? Is it useful to use it for deforming vertex data? I think losing parts of my car (doors, sirens, weapons) can looks really nice.

My game is a kind of RTS in a top down view. vehicles are not the really most important units (its no racing game), but I have quite a lot in.

# Answer
you could start incrementally adding car scratches or dust by using the stored textures as you first mentioned. The advantage of this method is its good performance. Another advantage is that with bump mapping effects you can realisticly simulate small damage.

If all this works as you expected i would recommend to complement this with a physics engine library and handle all the collisions and parts that could fly off. Soft-body deformations may or not be supported by the physics engine.

I would discard premade animations or colision states, since most of the times they generate an unrealistic feeling.
> 5 votes

---
Tags: 3d, physics, graphics, software-engineering
---


# Question
Title: Combining multiple sprites vs separate sprites
I have a character which can hold ten types of weapons.

Should I:

1. Create ten sets of animations for the character with each weapon
2. Create animations for each weapon, and programmatically draw them on the character

Option 1 is simpler in general, but requires more work on the artist, and results in larger game size.

Option 2, to me, is a programming nightmare...

Whats the better practice in general? Thanks.

# Answer
> 5 votes
Unless you have a high frame rate and very low size requirements, the number of sprites you're talking about won't matter compared to, say, the audio files (especially music!). If game size was the only requirement, I'd say go with pre-baked animations.

As long as you only have ten weapons, either way will be roughly the same amount of work for the artist; I'm assuming she'll be reusing most of the character animations and only changing a bit for each weapon.

If you have combinations of items, then Option 2 becomes more appealing. If you have, say, 10 weapons and 4 armors that can be worn in combination, you suddenly have the choice between 40 animations or combining 14 programmatically. If you add 10 hats, it's 200 versus 24. Combinations of items is the most common reason I've seen that developers programmatically layer sprite animation.

**So I say you might as well go for Option 1 unless you're combining stuff.**

As an aside, though, the code for layering sprites shouldn't be too hard if you're using a decent library or framework. The fact that it seems intimidating may show a weakness in your development skills. It might be worth it to expand your programming knowledge by treating this as an exercise.

---
Tags: sprites, spritesheet
---


# Question
Title: Game engine like Unity 3D that allow me to use .NET code
I've been looking at Unity 3D for developing a 3D PC game and I really like the scene editor and how it simplifies the process of constructing 3D scenes, managing assets, animations, transitions etc. However, I don't want to restrict myself to using the Unity 3D scripts for handling every bit of game logic in the game.

E.g. If I want to construct a RPG dialogue system I don't want to do it with unity 3d scripts - I'd like to use C#/.net. Also, I might want to use e.g. windows azure and sql azure as backend, and use 3rd party .net libraries such as reactive-extensions etc.

Is there a .net engine out there that helps me with asset loading, animations, physics, transitions, etc. with a scene editor, but allow me to plug it into a visual studio .net project?

Thanks

# Answer
> 11 votes
The wording of your question suggests a misunderstanding of how Unity works (please correct me if I'm wrong), so I'm going to recommend you just try out Unity. "Unity3D scripts" are just .NET classes that inherit from `UnityEngine.MonoBehaviour` or `UnityEditor.EditorWindow`.

There's nothing stopping you from writing freestanding C# classes or pulling in .NET libraries (assuming they are compatible with Unity's version of Mono, which seems to cover the important parts of .NET 3.5). Whenever you create a dependency on something not included by default in a Unity release deployment (ie: `System.Xml`) Unity sees your `using` statement, sees what members of that namespace you use and automatically bundles in the correct assemblies from the standard Mono distribution that it includes (you can also drop in your own .NET DLLs).

So long as any third party .NET code works in the .NET 3.5 subset that Unity's version of Mono supports, you can use it. Be wary of libraries that provide too much abstraction, though, or at least use them sparingly. This is game development, not enterprise software.

We do some dynamic scene construction in our Unity project, and all of the data for that is handled in pure C#, no `UnityEngine` namespace references except for where it wouldn't make sense to re-implement a data type that Unity already has (ie: `Vector3`). We reference `System.Linq` and could use JSON.NET if we wanted (but that lib's a little fat, so we use LitJSON instead).

> Is there a .net engine out there that helps me with asset loading, animations, physics, transitions, etc. with a scene editor, but allow me to plug it into a visual studio .net project?

Do you want to plug into a VS project because you really like VS and want to manage the project entirely from there, or is it that you want to use standard .NET assemblies? If you want to contain your whole project inside of Visual Studio, then your main options are things like OpenTK, SlimDX, MonoGame, or XNA and other's engines built on top of those. You'll also have do some work to build your own scene editor or integrate someone else's into your game.

I think you'll find though, that having your code and other assets exist in separate worlds can make things much simpler, especially if you bring an artist in later into the project.

If you want to step debug inside of Visual Studio instead of MonoDevelop, you can look at UnityVS.

And however you implement your backend is completely independent of your game's client code. The only mutual dependency between them should be the communication protocol.

# Answer
> 2 votes
There is an open .NET implementation called Mono, which is used by Unity3D.

If you are OK with low-level access and you want to implement things by yourself, check OpenTK (for OpenGL) or SlimDX (for DirectX).

# Answer
> 1 votes
There aren't too many. As an ecosystem, game engines tend to be dominated by C++, and when the engine exposes other languages, it's usually via a custom scripting. Your more evolved options include:

* Leadwerks
* NeoAxis
* Visual3D Game Engine

Good luck.

---
Tags: unity, c#, .net
---


# Question
Title: How to create a simple side scroller game
> **Possible Duplicate:**
> How to create games with scrolling?

I'm still pretty new to game programming and any tutorial that I have worked with stuck to only games with the initial screen. I want to start creating my own games but there are a few things that I still need to learn. One of them is how to create a game that side-scrolls. For example; Mario... Or ANY type of game like that...

Can anyone give me a small example to create something like that. I'm not asking for any specific language because currently in school I am learning javascript but I know some c++/java/processing/objective-c as well. So any of those languages would be fine and I could probably implement it in any of the others...

I have been searching for some help with this for a while now but could never actually get any help on it.

Thanks in advance!

# Answer
To accomplish scrolling, have a camera x and y (or in your case, maybe just x) variable that you change based on the position of the player. Then draw everything (except for the player) at their normal x and y position minus the camera x and y positions.

For example:

```
if player.x < screen_width / 2 then
    camera.x = 0
elseif player.x > level_width - screen_width / 2 then
    camera.x = level_width - screen_width
else
    camera.x = player.x - screen_width / 2
end

draw_stuff(x - camera.x, y)

```
> 0 votes

---
Tags: c++, 2d, java, side-scroller
---


# Question
Title: Artifacts when draw particles with some alpha
I want to draw in my game some particles. But when I draw one particle above another particle, alpha channel from this above "clear" previous drawed particle. I set in OpenGL blend in this way:

```
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

```

My fragment shader for particle is very simple:

```
precision highp float;
precision highp int;
uniform sampler2D u_maps[2];
varying vec2 v_texture;
uniform float opaque;
uniform vec3 colorize;
void main()
{
    vec4 texColor = texture2D(u_maps[0], v_texture);
    gl_FragColor.rgb = texColor.rgb * colorize.rgb;

    gl_FragColor.a = texColor.a * opaque;
}

```

I attach screenshot from this:

Do you know what I made wrong ?

I use OpenGL ES 2.0.

# Answer
I think it has something to do with the z sorting.

Try not writing to the z-buffer when rendering your particles using :

```
glDepthMask(GL_FALSE);

```

And don't forget to reset it to GL\_TRUE after that.
> 3 votes

---
Tags: opengl, shaders, opengl-es, blending
---


# Question
Title: Will having many timers affect my game performance?
I'm making a game for android, and earlier today I was trying to add some cool stuff to my game. The problem is this thing needs like 5 timers. I build my timers like this:

```
timer += deltaTime;
if(timer >= 2.0f){
    doStuff;
    timer -= 2.0f;
} // this timers gets stuff done every 2 secs

```

Will having to many timers like this, getting checked every frame, screw up my games performance? The effect I wanted to add was a crosshair every 2 sec, then remove it after 2 sec and do a timed animation. So an array of crosshairs dependent on a bunch of timers to be exact. This caused my game to shut down when used, so thats why Im wondering if using that many timers causes my game to flip out.

# Answer
It's not the short timer code you posted, any number of those would be fine, it's what doStuff you do with each one.

One problem I can foresee is that if you have timers of different frequencies some of them will sometimes "beat" and trigger their doStuff code all at the same time. For example, if you have a timer for 2.0 and one for 3.0, then every 6.0th tick both actions will get called simultaneously and maybe cause your game to burp when that happens.

Pick timer frequencies that won't all gang up like that, problem solved before it happens.

The question of "too many timers like that" can only be answered by asking "what do those timers DO" and then profiling to find out how much work you can afford and keep running smoothly.
> 6 votes

# Answer
"Will X affect my game's performance" should always be answered by "profile it and find out". Anything else is just guessing.
> 1 votes

# Answer
The timer code itself shouldn't have any noticeable performance impact. It's just a few lines of code, after all.
> 0 votes

---
Tags: java, performance, timer
---


# Question
Title: SDL: How would I add tile layers with my area class as a singleton?
I´m trying to wrap my head around how to get this done, if at all possible. So basically I have a Area class, Map class and Tile class. My Area class is a singleton, and this is causing some confusion. I´m trying to draw like this: Background / Tiles / Entities / Overlay Tiles / UI.

```
void C_Application::OnRender()
{
    // Fill the screen black
    SDL_FillRect( Surf_Screen, &Surf_Screen->clip_rect, SDL_MapRGB( Surf_Screen->format, 0x00, 0x00, 0x00 ) );

    // Draw background

    // Draw tiles
    C_Area::AreaControl.OnRender(Surf_Screen, -C_Camera::CameraControl.GetX(), -C_Camera::CameraControl.GetY());

    // Draw entities
    for(unsigned int i = 0;i < C_Entity::EntityList.size();i++)
    {
        if( !C_Entity::EntityList[i] )
        {
            continue;
        }

        C_Entity::EntityList[i]->OnRender( Surf_Screen );
    }

    // Draw overlay tiles

    // Draw UI

    // Update the Surf_Screen surface
    SDL_Flip( Surf_Screen);
}

```

Would be nice if someone could give a little input. Thanks.

# Answer
Are you using the tutorials from SDLTutorials.com?

Assuming you're following the tutorials and don't want to modify things too heavily yet, you could create two rendering functions for **C\_Area: C\_Area::OnRender(...)** which would function exactly the same as it already does and **C\_Area::OnRenderOverlay(...)** which would be called after your entities are drawn:

```
// Draw tiles
C_Area::AreaControl.OnRender(Surf_Screen, -C_Camera::CameraControl.GetX(), -C_Camera::CameraControl.GetY());

// Draw entities
for(unsigned int i = 0;i < C_Entity::EntityList.size();i++)
{
    if( !C_Entity::EntityList[i] )
    {

        continue;

    }

C_Entity::EntityList[i]->OnRender( Surf_Screen );

}

// Draw overlay tiles
C_Area::AreaControl.OnRenderOverlay(Surf_Screen, -C_Camera::CameraControl.GetX(), -C_Camera::CameraControl.GetY());

```

In C\_Area's variables, you would then have to maintain another **std::vector\<CMap\>** that would be read in like the first map, except the data file you're reading would contain information about your overlay tiles. You would have to modify the OnLoad function to read it. **C\_Area::OnRenderOverlay(...)** would simply draw the data associated with this vector on top of everything else.

Alternatively... redefine C\_Area so it's not a singleton?
> 1 votes

---
Tags: c++, tiles, sdl
---


# Question
Title: How to implement custom texture formats in Android?
**What I know:** Android can load PNG, BMP, WEBP,... via BitmapFactory.

**What I want to achive:** Load my own 2D file format (e.g. 1-bit texture with a 1-bit alpha channel) and output a RGBA8888 texture.

**Question:** Is there any interface to achieve this?(or any other way)

**The resulting image is used as a texture for a 3D model.**

***Why would you do that?** Saving phone memory and download bandwidth while expanding the texture at runtime to RAM seems reasonable for very simple textures.*

# Answer
You can load texture with glTexImage2D You will pass texel format and pointer to texel array texel is textures pixels

```
glTexImage2D(
    GL_TEXTURE_2D, 0, GL_RGBA,
    TEXTURE_WIDTH, TEXTURE_HEIGHT,
    0, GL_RGBA, GL_UNSIGNED_BYTE, textureArray);

```
> 3 votes

---
Tags: android, textures, opengl-es2
---


title: Networking middleware

text:
# Question
Title: Networking middleware
I'm looking for a networking middleware that may be suitable for a medium-sized MMO.

I don't care in which language it's written, just that it's high-level, stable and has many of the features that can ease my development. I am making a 2D real-time action game.

Come to think of it... I'd be happy with "just" a high-level networking framework that has a few handy features to ease the development of a general networked game.

# Answer
You can check Zoidcom or Raknet, I've heard good things about both of them.
> 2 votes

---
Tags: networking
---


# Question
Title: Best way to distribute graphics, audio and levels with an SDL game?
I'm working on finishing up a game written in C++ with SDL I've been working on for awhile, and I'm starting to ponder how I'm going to distribute it. It has hundreds of images that are loaded and used throughout the game, as well as a couple dozen .wav files for audio effects.

What is the best way to distribute these? Should I just include the folders with all the files? Or is there a way I can package them into a single file, then open and extract them in my application?

What's the best way to go about this?

# Answer
> 2 votes
I don't know about encryption, but it's relatively easy to put things in ZIP files and have a tool like PhysicsFS handle dynamic decompression at run-time.

It even allows you to support mods easily.

# Answer
> 1 votes
Unless there is a reason not to just ship them as plain directories. Less complexity in your code and you can replace content without needing additional tools for packing and unpacking.

Using PhysFS isn't wrong however, having multiple search paths is a good practice, the other features, such as reading from zip files are just a nice addition.

---
Tags: sdl, distribution
---


# Question
Title: How would I be able to get a game over screen using the pause function?
I am having problems with my snake game, when the snake collides with itself it draws a "game over" image in the background, but only while it's colliding with itself. I want it to behave like the pause function, so that as soon as the snake collides with itself it draws an image on the screen and stops the game play. And then how would you be able to restart or to quit the game?

I just have this for the detection at the moment:

```
if (snakeHeadRectangle.Intersects(snakeBodyRectangleArray[bodyNumber]))
            {

              spriteBatch.Draw(textureGameOver, gameOverPosition, Color.White);
            }

```

Thanks

# Answer
> 4 votes
I had a boolean variable `isGameRunning` which is set to `true` if the game is on. Update the game only when this variable is true. After collision, you can set this to `false`.

For more functionality you can have more states like

```
enum GameStates
{ Running, Paused, Over, WaitingForKeystrokeToBegin }

```

instead of just `true` and `false`.

To restart the game, create an `Initialize()` function to reset the settings.

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


# Question
Title: How to fetch only the sprites in the player's range of motion for collision testing? (2D, axis aligned sprites)
I am working on a 2D sprite game for educational purposes. (In case you want to know, it uses WebGl and Javascript) I've implemented movement using the Euler method (and delta time) to keep things simple. Now I'm trying to tackle collisions.

The way I wrote things, my game only has rectangular sprites (axis aligned, never rotated) of various/variable sizes.

So I need to figure out what I hit and which side of the target sprite I hit (and I'm probably going to use these intersection tests). The old fashioned method seems to be to use tile based grids, to target only a few tiles at a time, but that sounds silly and impractical for my game. (Splitting the whole level into blocks, having each sprite's bounding box fit multiple blocks I might abide. But if the sprites change size and move around, you have to keep changing which tiles they belong to, every frame, it doesn't sound right.) In Flash you can test collision under one point, but it's not efficient to iterate through all the elements on stage each frame. (hence why people use the tile method).

Bottom line is, I'm trying to figure out how to test only the elements within the player's range of motion. (I know how to get the range of motion, I have a good idea of how to write a `collisionCheck(playerSprite, targetSprite)` function. But how do I know which sprites are currently in the player's vicinity to fetch only them?)

Please discuss. Cheers!

# Answer
There are a few things you can do. I would recommend you try them in turn and see if your performance is acceptable. You can also re-use the simpler method in the advanced method.

1. Generate a quick check to see if a sprite is close enough to the player and **check the player against each sprite**. This distance check could be something like:
    * Pythagorean theorem
    * Pythagorean theorem sans square root (checking against the square of your min distance)
    * See if their X tile location is +/- n spaces and their Y tile location is +/- n spaces
2. Use QuadTrees to limit the number of sprites you need to check against the player. There is a balance here between keeping the minimum quad size low and keeping the traversal short. Play around with it before deciding you want to try something more complex.

Also make sure your `collisionCheck` method has a quick abort. Just do a real quick bounding box overlap test and see if there is a collision and if it's worth finding the exact point of impact.
> 0 votes

# Answer
To check which sprites are in the vicinity, you can just use the distance formula.

```
distance = sqrt( (x1-x2)^2 + (y1-y2)^2 );

```

But if you want to check collision for only the sprites in the vicinity, then its not a good choice. Anyways, you'd have to calculate the distance for all the sprites; instead you can check collision itself.

To check the side from where your player has collided, its better you have a function as

```
checkCollision(playerBound, targetBound, playerVelocity)

```

We won't check if a collision has occurred. Instead, we will check if it is about to occur it the player makes its next move.

Lets have a `playerBound` to the player, the rectangle that determines the player position and size. Similarly for `targetBound`

`playerVelocity` would be velocity vector of the player per time span (method call).

We can have a function that checks if a rectangle collides with another

```
bool checkXCollision(bound1, bound2)
{
    if((bound1.left <= bound2.right && bound1.left >= bound2.left) || (bound1.right <= bound2.right && bound1.right >= bound2.left)) //Check for x-axis
        return true; //Collision is there
    return false;
}
bool checkYCollision(bound1, bound2)
{
    if((bound1.bottom <= bound2.top && bound1.bottom >= bound2.bottom) || (bound1.top <= bound2.top && bound1.top >= bound2.bottom)) //Check for y-axis
        return true; //Collision is there
    return false;
}
bool checkCollision(bound1, bound2)
{
    if(checkXCollision(bound1, bound2) && checkYCollision(bound1, bound2))
        return true;
    return false;
}

```

Notation for top, bottom, left and right

```
     top   __________
          |          |
          |          |
          |          |
          |     o    |
          |          |
          |          |
  bottom  |__________|
          left       right

```

**Case 1**: Colliding at y-axis

```
       __________
      |          |
      |          |
      |          |
      |          |
      |          |\   _________
      |          | \ |         |
      |__________|  \|         |
                     |         |
                     |_________|

```

If after one more step, they collide, then collision has occured from the left.

**Case 2**: Colliding at x-axis

```
       __________
      |          |
      |          |
      |          |
      |          |
      |          |
      |          |
      |__________|
               \
               _\______
              |        |
              |        |
              |        |
              |________|

```

If after one more step, they collide, then collision has occured from the top.

**Case 3**: Not colliding at any axis

```
       __________
      |          |
      |          |
      |          |
      |          |
      |          |
      |          |
      |__________|
               \
                \   ________
                 \ |        |
                  \|        |
                   |        |
                   |________|

```

But after making one step they will collide, so we are not sure whether its from left or right.

```
Direction checkCollision(playerBound, targetBound, playerVelocity)
{
    bool xCollided = false;
    bool yCollided = false;
    bool isCollided = false;
    if(checkXCollision(playerBound, targetBound))
        xCollided = true;
    else if(checkYCollision(playerBound, targetBound))
        yCollided = true;

    playerBound.x += playerVelocity.x;
    playerBound.y += playerVelocity.y;
    if(checkCollision(playerBound, targetBound))
        isCollided = true;

    if(isCollided)
    {
        if(xCollided)  //Case 1
            //Collision has occured either from left or right depending on playerVelocity.x
        else if(yCollided)  //Case 2
            //Collision has occured either from top or bottom depending on playerVelocity.y
    }
}

```

For case 3, we can increment the position of the player by small amount unless it collides at exactly 1 axis. Of if still it collides at both axis, we can say that their corners (not sides) are collided.

Alternatively, we can compare the slope of the line made by o-p and the velocity vector. From there, we can know whether its going more towards `x` or `y`.

```
       __________
      |          |
      |          |
      |          |
      |          |
      |     o____|__
      |     |    |  |
      |_____|____p  |
            |       |
            |_______|

```
> 1 votes

---
Tags: 2d, collision-detection, sprites, physics
---


title: OpenGL 3+ Range Picking

text:
# Question
Title: OpenGL 3+ Range Picking
How do I perform range picking in the latest OpenGL version? By range picking I mean selecting all objects which are picked using a selection rectangle, like in an RTS game.

For single object picking I'm using the ray picking method, which I guess can be used in this case as well, but I'm not sure how I should go about doing that.

Could you give me any pointers?

Thank you.

# Answer
Range picking is basically a set of intersection tests between objects and camera frustum (6 planes that together define a convex volume). If you have some frustum culling code, you can just fix it up to make it work. The easiest way is to generate point data from camera matrix (view\*projection), adjust the point data by means of coordinate transforms and interpolation (interpolate point data on near/far planes depending on the screen-space selection rectangle corner values) and generate planes from those points.
> 2 votes

---
Tags: opengl, raycasting, picking
---


# Question
Title: Negamax implementation doesn't appear to work with tic-tac-toe
I've implemented Negamax as it can be found on wikipedia, which includes alpha/beta pruning.

However, it seems to favor a losing move, which should be an invalid result.

The game is Tic-Tac-Toe, I've abstracted most of the game play so it should be rather easy to spot an error within the algorithm.

Here is the code, `nextMove`, `negamax` or `evaluate` are probably the functions that contain the fault:

```
#include <list>
#include <climits>
#include <iostream>

//#define DEBUG 1

using namespace std;

struct Move {
    int row, col;

    Move(int row, int col) : row(row), col(col) { }
    Move(const Move& m) { row = m.row; col = m.col; }
};

struct Board {
    char player;
    char opponent;
    char board[3][3];

    Board() { }

    void read(istream& stream) {
        stream >> player;
        opponent = player == 'X' ? 'O' : 'X';

        for(int row = 0; row < 3; row++) {
            for(int col = 0; col < 3; col++) {
                char playa;

                stream >> playa;
                board[row][col] = playa == '_' ? 0 : playa == player ? 1 : -1;
            }
        }
    }

    void print(ostream& stream) {
        for(int row = 0; row < 3; row++) {
            for(int col = 0; col < 3; col++) {
                switch(board[row][col]) {
                    case -1:
                        stream << opponent;
                        break;

                    case 0:
                        stream << '_';
                        break;

                    case 1:
                        stream << player;
                        break;

                }
            }
            stream << endl;
        }
    }

    void do_move(const Move& move, int player) {
        board[move.row][move.col] = player;
    }

    void undo_move(const Move& move) {
        board[move.row][move.col] = 0;
    }

    bool isWon() {
        if (board[0][0] != 0) {
            if (board[0][0] == board[0][1] &&
                    board[0][1] == board[0][2])
                return true;

            if (board[0][0] == board[1][0] &&
                    board[1][0] == board[2][0])
                return true;
        }

        if (board[2][2] != 0) {
            if (board[2][0] == board[2][1] &&
                    board[2][1] == board[2][2])
                return true;

            if (board[0][2] == board[1][2] &&
                    board[1][2] == board[2][2])
                return true;
        }

        if (board[1][1] != 0) {
            if (board[0][1] == board[1][1] &&
                    board[1][1] == board[2][1])
                return true;

            if (board[1][0] == board[1][1] &&
                    board[1][1] == board[1][2])
                return true;

            if (board[0][0] == board[1][1] &&
                    board[1][1] == board[2][2])
                return true;

            if (board[0][2] == board [1][1] &&
                    board[1][1] == board[2][0])
                return true;
        }

        return false;
    }

    list<Move> getMoves() {
        list<Move> moveList;

        for(int row = 0; row < 3; row++)
            for(int col = 0; col < 3; col++)
                if (board[row][col] == 0)
                    moveList.push_back(Move(row, col));

        return moveList;
    }
};

ostream& operator<< (ostream& stream, Board& board) {
    board.print(stream);
    return stream;
}

istream& operator>> (istream& stream, Board& board) {
    board.read(stream);
    return stream;
}

int evaluate(Board& board) {
    int score = board.isWon() ? 100 : 0;

    for(int row = 0; row < 3; row++)
        for(int col = 0; col < 3; col++)
            if (board.board[row][col] == 0)
                score += 1;

    return score;
}

int negamax(Board& board, int depth, int player, int alpha, int beta) {
    if (board.isWon() || depth <= 0) {
#if DEBUG > 1
        cout << "Found winner board at depth " << depth << endl;
        cout << board << endl;
#endif
        return player * evaluate(board);
    }

    list<Move> allMoves = board.getMoves();

    if (allMoves.size() == 0)
        return player * evaluate(board);

    for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) {
        board.do_move(*it, -player);
        int val = -negamax(board, depth - 1, -player, -beta, -alpha);
        board.undo_move(*it);

        if (val >= beta)
            return val;

        if (val > alpha)
            alpha = val;
    }

    return alpha;
}

void nextMove(Board& board) {
    list<Move> allMoves = board.getMoves();
    Move* bestMove = NULL;
    int bestScore = INT_MIN;

    for(list<Move>::iterator it = allMoves.begin(); it != allMoves.end(); it++) {
        board.do_move(*it, 1);
        int score = -negamax(board, 100, 1, INT_MIN + 1, INT_MAX);
        board.undo_move(*it);

#if DEBUG
        cout << it->row << ' ' << it->col << " = " << score << endl;
#endif

        if (score > bestScore) {
            bestMove = &*it;
            bestScore = score;
        }
    }

    if (!bestMove)
        return;

    cout << bestMove->row << ' ' << bestMove->col << endl;

#if DEBUG
    board.do_move(*bestMove, 1);
    cout << board;
#endif

}

int main() {
    Board board;

    cin >> board;
#if DEBUG
    cout << "Starting board:" << endl;
    cout << board;
#endif

    nextMove(board);
    return 0;
}

```

Giving this input:

```
O
X__
___
___

```

The algorithm chooses to place a piece at 0, 1, causing a guaranteed loss, do to this trap(nothing can be done to win or end in a draw):

```
XO_
X__
___

```

Perhaps it has something to do with the evaluation function? If so, how could I fix it?

# Answer
> 0 votes
The problem was solved!

The `evaluate` function did not evaluate the board from the player's perspective, but from a global perspective. Once I fixed this, the negamax algorithm worked like a charm!

---
Tags: c++, algorithm, ai
---


title: How should I go about learning XNA?

text:
# Question
Title: How should I go about learning XNA?
I want to start learning how to make games in XNA, but I have no idea where to start! If someone could advise me on what pieces of software I need and some good books or tutorials to look at, that would be most helpful.

As for my current coding knowledge, I have some good experience with Javascript (in conjunction with HTML5 canvas). I'm pretty sure I would also need to learn C# to code with XNA, so keep that in mind.

# Answer
> 12 votes
If you understand the general programming fundamentals work - datatypes, classes, functions, etc - I would say go for it.

When I started learning C#, I did have games in mind, but started with developing console apps that, while they looked very basic, incorporated some advanced C# techniques, in order to better my understanding of the language.

Once you have an understanding of how C# works, I'd go ahead and download the XNA studio from here - http://www.microsoft.com/download/en/details.aspx?id=23714

You will want to start with learning SpriteBatch. Some good tutorials can be found here...

From there you can start experimenting with pixel shaders (on SpriteBatch, http://msdn.microsoft.com/en-us/library/bb313868(v=xnagamestudio.31).aspx ), and also matrix transformations ( http://www.david-amador.com/2009/10/xna-camera-2d-with-zoom-and-rotation/ ).

Once you have a good grasp of that, you can finally move on to using the graphics device to draw primitives and models using BasicEffects and custom shaders.

Good luck!

# Answer
> 5 votes
A great resource that helped me learn XNA was the set of tutorials here.

# Answer
> 3 votes
Step one would be to download both the framework (XNA) and MS's Visual C# 2010 Express. I have found a couple of books. Learning XNA 4.0 published by O'rielly and XNA Game Studio 4.0 Programming...just plug those into Amazon. For C# I rather enjoyed the Head First series but you may need a more academic tome to supplement that.

Also XNA RPG tutorial thing has been enjoyable.

# Answer
> 2 votes
If you don't already have Visual Studio, the quickest way to get started would be to get Visual Studio C# Express and a copy of XNA. Both are free and downloadable from Microsoft.

Once you've done that, all you have to do is decide if you want to jump right in or play around with some tutorials first. If the latter, I highly recommend Riemer's tutorials. and I'm certain others can and will recommend other good resources.

# Answer
> 1 votes
MSDN has a lot of documentation for XNA : XNA on MSDN

# Answer
> 1 votes
Just learn XNA with the C#, the XBOX 360 is really only a particular profile from a programmer viewpoint.

there are a lot of tutorial on the internet but this is an official resource.

# Answer
> 1 votes
I recently got into basic game development with XNA as well. The Microsoft Dev Network has a great tutorial, that will take you through step by step in setting up a basic space shooter.

I would highly recommend going through the tutorial, as that will give you a good understanding of the rudiments behind game development. Don't worry about the amount of time you're putting into it (the tutorial claimed it would only take about 90 mins, but I took over a day going through all of the code), but understanding all of the concepts they're covering is vital!

# Answer
> 1 votes
I started the same thing over the summer and found that the official site to help a lot.

http://create.msdn.com/en-US/education/tutorial/2dgame/design

You can even just adapt a tutorial or two and get a pretty sweet game.

# Answer
> 1 votes
The starting point for XNA dev is create.msdn.com although that's now just a landing page to take you to the XBOX live indie games page.

The education catalog is pretty complete and lets you filter by dev area, it's actually a really good resource.

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


# Question
Title: use of undeclared identifier 'GL_TEXTURE_COORD_ARRAY'
Anyone please help me .i am working on sneakyjoystick class when i import these class some error are identified they are following :-

**use of undeclared identifier 'GL\_TEXTURE\_COORD\_ARRAY'**

**use of undeclared identifier 'GL\_COLOR\_ARRAY'**

# Answer
`GL_TEXTURE_COORD_ARRAY` and `GL_COLOR_ARRAY` are usually defined in `gl.h`

> **/usr/include/GL $** grep GL\_COLOR\_ARRAY gl.h -rn
>
> 209:#define GL\_COLOR\_ARRAY 0x8076

Are you including this header correctly?

If you paste a bit of your code we can probably give you a more detailed answer.
> 1 votes

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


# Question
Title: Should I use OpenGL or DX11 for my game?
I'm planning to write a game from scratch (a BIG Game, for commercial purpose). I'm aware that there are certain compute libraries like OpenCL, AMD APP SDK, C++ AMP as well as DirectCompute - both from MS (NOT interested in CUDA) are available in the market.

I'm planning to write the game from the scratch, which includes the following engines...

1. Physics Engine
2. AI Engine
3. Main Game Engine

(... and if anything is missed). I'm aware that, there are some free physics engine libraries in the market. Not sure about free AI engine libraries.

I'm bit confused in choosing between the OpenCL, AMD APP SDK, and C++ AMP libraries (as already mentioned i'm NOT interested in CUDA).

I want my game to be published in Windows/Android/Mac OSX. It means it should be a cross-platform game.

I will be having "one source code" that i'll compile for various platforms like Windows/Android/Mac OSX, and any others if i missed.

Note: Since I'm NOT a Java guy, kindly do NOT suggest me the Java Language.

For Graphics language should i use OpenGL or DirectX 11?

I have heard that OpenGL runs on a single core, and not sure of DirectX 11. Between OpenGL and DirectX which one should i follow?

or else, are there any other graphics language that i need to start with?

I want to make use of the parallelism in GPU as well as CPU.

# Answer
> 3 votes
From your description, it looks like you want to write an engine(s) and not a game.. ;). I'm not going to bring you down telling you about how enormous task you are putting yourself into, because I think having dreams and pursuing them is a good thing (and learning on own mistakes too).

**Answer to your question:**

Your requirements of begin cross platform ruled out DirectX. If you want Android (or other smartphones), OpenGL is the way to go.

**Bonus Answer:**

Don't think about writing everything from scratch. Pick an existing engine (free or not) which meets your cross platform criteria and use it to build your game - that alone is not an easy task.

---
Tags: opengl
---


# Question
Title: Can someone explain the (reasons for the) implications of colum vs row major in multiplication/concatenation?
I am trying to learn how to construct view and projection matrices, and keep reaching difficulties in my implementation owing to my confusion about the two standards for matrices.
I know *how* to multiply a matrix, and I can see that transposing before multiplication would completely change the result, hence the need to multiply in a different order.

**What I don't understand though is whats meant by only 'notational convention'** \- from the articles here and here the authors appear to assert that it makes no difference to how the matrix is stored, or transferred to the GPU, but on the second page that matrix is *clearly not* equivalent to how it would be laid out in memory for row-major; and if I look at a populated matrix in my program I see the translation components occupying the 4th, 8th and 12th elements.

Given that:

> "post-multiplying with column-major matrices produces the same result as pre-multiplying with row-major matrices. "

Why in the following snippet of code:

```
        Matrix4 r = t3 * t2 * t1;
        Matrix4 r2 = t1.Transpose() * t2.Transpose() * t3.Transpose();

```

**Does r != r2** and **why does pos3 != pos for**:

```
        Vector4 pos = wvpM * new Vector4(0f, 15f, 15f, 1);
        Vector4 pos3 = wvpM.Transpose() * new Vector4(0f, 15f, 15f, 1);

```

**Does the multiplication process change depending on whether the matrices are row or column major**, or is it just the order (for an equivalent effect?)

One thing that isn't helping this become any clearer, is that when provided to DirectX, my column major WVP matrix is used successfully to transform vertices with the HLSL call: mul(vector,matrix) which should result in the vector being treated as row-major, so how can the column major matrix provided by my math library work?

# Answer
> 14 votes
> if I look at a populated matrix in my program I see the translation components occupying the 4th, 8th and 12th elements.

Before I begin, it's important to understand: this means your matrices are **row major**. Therefore, you answer to this question:

> my column major WVP matrix is used successfully to transform vertices with the HLSL call: mul(vector,matrix) which should result in the vector being treated as row-major, so how can the column major matrix provided by my math library work?

is quite simple: your matrices are row-major.

So many people use row-major or transposed matrices, that they forget that matrices are not naturally oriented that way. So they see a translation matrix as this:

```
1 0 0 0
0 1 0 0
0 0 1 0
x y z 1

```

This is a **transposed translation matrix**. That is not what a normal translation matrix looks like. The translation goes in the 4th *column*, not the fourth row. Sometimes, you even see this in textbooks, which is utter garbage.

It's easy to know whether a matrix in an array is row or column-major. If it's row-major, then the translation is stored in the 3, 7, and 11th indices. If it's column-major, then the translation is stored in the 12, 13, and 14th indices. Zero-base indices of course.

Your confusion stems from believing that you're using column-major matrices when you're in fact using row-major ones.

The statement that row vs. column major is a notational convention only is entirely true. The mechanics of matrix multiplication and matrix/vector multiplication are the same regardless of the convention.

What changes is the meaning of the results.

A 4x4 matrix after all is just a 4x4 grid of numbers. It doesn't *have* to refer to a change of coordinate system. However, once you assign *meaning* to a particular matrix, you now need to know what is stored in it and how to use it.

Take the translation matrix I showed you above. That's a valid matrix. You could store that matrix in a `float[16]` in one of two ways:

```
float row_major_t[16] =    {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1};
float column_major_t[16] = {1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1};

```

However, I said that this translation matrix is wrong, because the translation is in the wrong place. I specifically said that it is transposed relative to the standard convention for how to build translation matrices, which ought to look like this:

```
1 0 0 x
0 1 0 y
0 0 1 z
0 0 0 1

```

Let's look at how these are stored:

```
float row_major[16] =    {1, 0, 0, x, 0, 1, 0, y, 0, 0, 1, z, 0, 0, 0, 1};
float column_major[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1};

```

Notice that `column_major` is *exactly the same* as `row_major_t`. So, if we take a *proper* translation matrix, and store it as column-major, it is the same as transposing that matrix and storing it as row-major.

That is what is meant by being only a notational convention. There are really two sets of conventions: memory storage and transposition. Memory storage is column vs row major, while transposition is normal vs. transposed.

If you have a matrix that was generated in row-major order, you can get the same effect by transposing the column-major equivalent of that matrix. And vice-versa.

Matrix multiplication can only be done one way: given two matrices, in a specific order, you multiply certain values together and store the results. Now, `A*B != B*A`, but the actual source code for `A*B` is the same as the code for `B*A`. They both run the same code to compute the output.

The matrix multiplication code does not care whether the matrices happen to be stored in column-major or row-major order.

The same *cannot* be said for vector/matrix multiplication. And here's why.

Vector/matrix multiplication is a falsehood; it cannot be done. However, you *can* multiply a matrix by another matrix. So if you pretend a vector is a matrix, then you can effectively do vector/matrix multiplication, simply by doing matrix/matrix multiplication.

A 4D vector can be considered a column-vector or a row-vector. That is, a 4D vector can be thought of as a 4x1 matrix (remember: in matrix notation, the row count comes first) or a 1x4 matrix.

But here's the thing: Given two matrices A and B, `A*B` is only defined if the number of columns of A is the same as the number of rows of B. Therefore, if A is our 4x4 matrix, B must be a matrix with 4 rows in it. Therefore, you cannot perform `A*x`, where x is a *row-vector*. Similarly, you cannot perform `x*A` where x is a column-vector.

Because of this, most matrix math libraries make this assumption: if you multiply a vector times a matrix, you really mean to do the multiplication that actually *works*, not the one that makes no sense.

Let us define, for any 4D vector x, the following. `C` shall be the column-vector *matrix* form of `x`, and `R` shall be the row-vector *matrix* form of `x`. Given this, for any 4x4 matrix A, `A*C` represents matrix multiplying A by the column-vector `x`. And `R*A` represents matrix multiplying the row-vector `x` by A.

But if we look at this using strict matrix math, we see that these are *not equivalent*. `R*A` *cannot* be the same as `A*C`. This is because a row-vector is not the same thing as a column-vector. They're not the same matrix, so they do not produce the same results.

However, they are related in one way. It is true that `R != C`. However, it is also true that `R = C<sup>T</sup>`, where T is the transpose operation. The two matrices are transposes of each other.

Here's a funny fact. Since vectors are treated as matrices, they too have a column vs. row-major storage question. The problem is that they both *look the same*. The array of floats is the same, so you can't tell the difference between R and C just by looking at the data. The *only* way to tell the difference is by how they are used.

If you have any two matrices A and B, and A is stored as row-major and B as column-major, multiplying them is **completely meaningless**. You get nonsense as a result. Well, not really. Mathematically, what you get is the equivalent of doing `A<sup>T</sup>*B`. Or `A*B<sup>T</sup>`; they're mathematically identical.

Therefore, matrix multiplication only makes sense if the two matrices (and remember: vector/matrix multiplication is just matrix multiplication) are stored in the same major ordering.

So, is a vector column-major or row-major? It is both and neither, as stated before. It is column major only when it is used as a column matrix, and it is row major when it is used as a row matrix.

Therefore, if you have a matrix A which is column major, `x*A` means... nothing. Well, again, it means `x*A<sup>T</sup>`, but that's not what you really wanted. Similarly, `A*x` does transposed multiplication if `A` is row-major.

Therefore, the order of vector/matrix multiplication *does* change, depending on your major ordering of the data (and whether you're using transposed matrices).

> Why in the following snippet of code does r != r2

Because your code is broken and buggy. Mathematically, `A * (B * C) == (C<sup>T</sup> * B<sup>T</sup>) * A<sup>T</sup>`. If you do not get this result, then either your equality test is wrong (floating-point precision issues) or your matrix multiplication code is broken.

> why does pos3 != pos for

Because that doesn't make sense. The only way for `A * t == A<sup>T</sup> * t` to be true would be if `A == A<sup>T</sup>`. And that is only true of symmetric matrices.

# Answer
> 3 votes
There's two different choices of convention at work here. One is whether you use row vectors or column vectors, and the matrices for these conventions are transposes of each other.

The other is whether you store the matrices *in memory* in row-major order or column-major order. Note that "row-major" and "column-major" are *not* the correct terms for discussing the row-vector / column-vector convention...even though many people misuse them as such. The row-major and column-major *memory layouts* differ by a transpose, too.

OpenGL uses a column vector convention and column-major storage order, and D3D uses a row vector convention and row-major storage order (well - at least D3DX, the math library, does), so the two transposes cancel out and it turns out the same memory layout works for both OpenGL and D3D. That is, the same list of 16 floats stored sequentially in memory will work the same way in both APIs.

This may be what's meant by people saying that "it makes no difference to how the matrix is stored, or transferred to the GPU".

As for your code snippets, r != r2 because the rule for transpose of a product is (ABC)^T = C^T B^T A^T. Transposition distributes over multiplication with a reveral of order. So in your case you should get r.Transpose() == r2, not r == r2.

Likewise, pos != pos3 because you transposed but didn't reverse the multiplication order. You should get wpvM * localPos == localPos * wvpM.Tranpose(). The vector is automatically being interpreted as a row vector when multiplied on the left side of a matrix, and as a column vector when multiplied on the right side of a matrix. Other than that, there is no change in how multiplication is carried out.

Finally, re: "my column major WVP matrix is used successfully to transform vertices with the HLSL call: mul(vector,matrix)," I'm uncertain about this, but maybe confusion / a bug has caused the matrix to come out from the math library already transposed.

# Answer
> 1 votes
In 3d graphics you use matrix to transform both vector and points. Considering the fact that you are talking about translation matrix, I'll speak only about points (you can't translate a vector with a matrix, or , saying it better, you can but you will obtain the same vector).

In matrix multiplication the number of column of the first matrix should be equal to the number of row of the second one (you can multiply a n x m matrix for an m x k).

A point (or a vector) is represented by 3 components (x,y,z) and can be considered both like a row or a column:

> colum (dimension 3 X 1):
>
> |x|
>
> |y|
>
> |z|

or

> row (dimension 1 X 3):
>
> |x,y,z|

You can choose the preferred convention, it's just a convention. Let's call it T the translation matrix. If you choose the first convention, in order to multiply a point p for a matrix you need to use a post multiplication:

> T * v (dimension 3x3 * 3x1)

otherwise:

> v * T (dimension 1x3 * 3x3)
>
> the authors appear to assert that it makes no difference to how the matrix is stored, or transferred to the GPU

If you use always the same convention it makes no difference. It doesn't mean that matrix of different convention will have the same memory representation, but that transforming a point with the 2 different conventions you will obtain the same transformed point:

> p2 = B * A * p1; //first convention
>
> p3 = p1 * A * B; //second convention
>
> p2 == p3;

# Answer
> 1 votes
**I see the translation components occupying the 4th, 8th and 12th elements** means your matrices are "wrong".

The translation components are *always* specified as entries *#13, #14 and #15* of the transformation matrix (*counting the very first element of the array as element #1*).

### A row major transformation matrix looks like this:

```
[ 2 2 2 1 ]  ┌ R00 R01 R02 0 ┐
             │ R10 R11 R12 0 │
             │ R20 R21 R22 0 │
             └ t.x t.y t.z 1 ┘

```

### A column major transformation matrix looks like this:

```
┌ R00 R01 R02 t.x ┐ ┌ 2 ┐
│ R10 R11 R12 t.y │ │ 2 │
│ R20 R21 R22 t.z │ │ 2 │
└  0   0   0   1  ┘ └ 1 ┘

```

## Row major matrices are **specified going down the rows**.

Declaring the row major matrix above as a linear array, I would write:

```
ROW_MAJOR = { R00, R01, R02, 0,  // row 1 // very intuitive
              R10, R11, R12, 0,  // row 2
              R20, R21, R22, 0,  // row 3
              t.x, t.y, t.z, 1 } ; // row 4

```

That seems very natural. Because notice, English is written "row-major" -- the matrix appears in the text above exactly as it will be in math.

And here's the point of confusion.

## **Column major matrices are specified going down the columns**

That means to specify the column major transformation matrix as a linear array in code, you'd have to write:

```
    **COLUMN_MAJOR = { R00, R10, R20, 0,** // COLUMN #1 // very counter-intuitive
                     R01, R11, R21, 0,
                     R02, R12, R22, 0,
                     t.x, t.y, t.z, 1  } ;

```

**Note this is completely counter-intuitive!!** A column major matrix has its entries specified **down the columns** when initializing a linear array, so the first line

```
COLUMN_MAJOR = { R00, R10, R20, 0,

```

Specifies the ***first column*** of the matrix:

```
┌ R00
│ R10
│ R20
└  0

```

**and not the first row**, as the simple layout of the text would have you believe. You have to mentally transpose a column major matrix when you see it in code, because the first 4 elements specified actually describe the first column. I suppose this is why a lot of people prefer row-major matrices in code (GO DIRECT3D!! cough.)

So, the translation components ***are always*** at linear array indices *#13, #14, and #15* (where first element is #1), regardless if you're using row major or column major matrices.

### What happened with your code and why does it work?

What's happening in your code is, you have a column major-matrix yes, but you put the translation components in the wrong spot. When you transpose the matrix, entry #4 goes to entry #13, entry #8 to #13, and entry #12 to #15. And there you have it.

# Answer
> 0 votes
Put simply, the reason for the difference is that matrix multiplication is not commutative. With regular multiplication of numbers, if A * B = C then it follows that B * A also = C. This is not the case with matrixes. That's why choosing either row-major or column-major matters.

Why it *doesn't* matter is that, in a modern API (and I'm specifically talking shaders here), you can choose your own convention and multiply your matrixes in the correct order for that convention in your own shader code. The API no longer enforces one or the other on you.

---
Tags: mathematics, matrix
---