# Question
Title: Trying to make a game with C++, using lists to store bullets and enemies, but they are not erased
I've been trying to make a pretty simple space shooter game with C++, and I have been having a lot of trouble trying to use lists to store enemies and bullets.

Basically I followed the post here almost exactly to store my bullets:

SDL Bullet Movement

I've done something similar to store my enemies.

However, when I call bullets.erase(it++), for some reason the bullet is not erased.

When the bullet movement is run for the next frame, it tries to re delete the bullet and segfaults the program. When I comment out the erase line, it runs fine, but the bullets are then never erased from the list...

Is there any reason why the elements of the list aren't being deleted? I also set it up to print the number of elements in the list for every iteration, and it does not go down after deleting.

Thanks!

EDIT:

Here's the specific code I'm using to store my enemies and having them act:

```
std::list<Grunt*> doGrunts(std::list<Grunt*> grunts)
{
  for(std::list<Grunt*>::iterator it = grunts.begin(); it != grunts.end();)
    {

      if((*it)->getHull() == 0)
        {
          delete * it;
          grunts.erase(it++);
        }
      else
        {

          (**it).doUnit(grunts, it);
          ++it;
        }
     }
  }

```

Grunt is my enemy class, and the list grunts is a global variable. Is that my problem? When I pass the global into the function it becomes local? I assumed lists would be a reference type so thought this wouldn't be a problem.

Sorry if this was a dumb question, I'm very new to C++, this is the first major thing I'm working on.

# Answer
container.erase calls the `destructor` of the contained object if it has one. `pointers` like `Grunt*` do not have destructors. You must manually `delete` the pointer THEN call `erase`.

You also have to be careful of invalidation of iterators, incrementing an invalidated pointer will cause a BLOCK\_HEAD failure.

pseudo-code:

```
for each iterator "it" in container //(DO NOT increment iterator in for loop block statement!)
    if it->position is off_screen {
        delete *it;
        *it = NULL; //Prevents seg fault due to double-delete.
        container.erase(it++);
    } else {
        ++it;
    }

```

*SUPER EDIT*

In light of the code you posted:

1) Yes, a copy of grunts is created because the list is being passed by value. It is also being `shadowed` because you named the local variable the same as the global one. 2) Why are you passing a GLOBAL variable around? Either A) just use it, or B) make it non-global and pass by reference.
> 2 votes

# Answer
You need to use resource-managing classes. Deleting your own memory is *extremely* error-prone. The only viable solution in the long term is to use classes like `std::shared_ptr`, `std::unique_ptr`, or simply storing your bullets by value. Why on earth would you use a linked list of *pointers*? That's quite unnecessary.
> 2 votes

# Answer
If `it` is an iterator for the `std::list<Bullet*>` bullets, calling `bullets.erase(*it)` should be invalid since `*it` is a `Bullet*` not an `std::list<Bullet*>::iterator` and erase requires an iterator. If you want to remove elements by referring to their value you could try the remove function.

EDIT: Also, with an std::list you do not have to worry about invalidating iterators using list::erase. I am not sure if the same guarantee is given for list::remove.
> 1 votes

# Answer
There are two things that I can see in that code that could cause problems.

First, you aren't checking for NULL Grunt pointers. You dereference (\*it)-\>GetHull, and if (\*it) in this case is NULL you'll get your segfault.

Second, when you call erase, you could be moving memory about in the list. It's not really safe to use an iterator (i.e. a pointer into the list structure) after the list is modified. But specifically in this case, you should NOT be incrementing it, as that will skip an element. Like this

(G1)-\>(G2)-\>it-\>end -\> erase (it) -\> (G1)-\>(G2)-\>\[it\]end (maybe) -\> it++ -\> ??? the iterator's already at the end!

I can't say for sure if that's happening, but you shouldn't do it anyway, as you'll skip over elements of the list.
> 0 votes

# Answer
For the record, the **std::list::erase()** method returns the next iterator in the list, making incrementing a counter redundant, and in my opinion, a safer method for erasing container elements.

Assuming `grunts` is a `std::list<Grunt*>`:

```
auto iter = grunts.begin();
while(iter != grunts.end())
{
  delete *iter; // No need to set NULL here, if you're going to remove from list.
  iter = grunts.erase(iter);
}

```

Furthermore, you should start collecting a nice set of helper macros for stuff like deleting pointers. This will save you some headaches later.

```
#define SAFE_DELETE(x) if(x){delete x; x=NULL;} // Keep in a common header somewhere..
Grunt* pGrunt = new Grunt();
Grunt* pBadGrunt = NULL;
SAFE_DELETE(pGrunt); // pGrunt is now free'd and NULL
SAFE_DELETE(pBadGrunt); // Nothing happens, pointer is still NULL

```
> 0 votes

---
Tags: c++, sdl, projectile-physics
---


title: Skyrim Creation Kit with Xbox 360

text:
# Question
Title: Skyrim Creation Kit with Xbox 360
I posted this on stackoverflow but was advised to post here (here is a link to the stackoverflow question). I'm hoping for constructive feedback on its plausibility.

**Update on progress:** It looks like there *are* ways to stuff files back onto the console (horizon, modio, xplorer360, etc) and they *do* require some form of signing.

As of now, though, I've had no luck. I was hoping I could get away with just placing the ".esp" into the directory containing marketplace downloads for Skyrim, along with the signed ".bsa" file (basically a zipped up file containing any extra content the .esp will need to refer that doesn't exist in the basic game).

This doesn't work, at least not in the ways I've tried, so next I'm going to try install the entire game to my flash drive (if possible) and attempt to traverse through the game's directory (this is probably unlikely).

If anyone else has suggestions or luck or wants more detail on my failures comment/answer away.

Here is the question:

> I'm thinking about buying the PC version of Skyrim to get the Creation Kit (I already own a copy for the Xbox). I have read the faq and scoured plenty of forums to see if there was some way to mod Skyrim for a console (Xbox 360, in particular), but they are generally coming up negative.
>
> I realize the CreationKit is on the PC, but I was wondering if there was a way to set up the '.esp' (hopefully I'm interpreting this correctly) files to be placed on the Xbox 360 file system in a similar manner to how game add-ons are downloaded from the Xbox Live Marketplace.
>
> I believe it is possible to transfer saves between the console and the PC (e.g. google: 'skyrim mod xbox360'), but these are referencing items that already exist in the game (e.g. a console command for maximum carry weight does not require reference to new animations or models).
>
> It would probably be easier if one could navigate through the xbox's file system to see where the games' files are placed, but with the current setup, the file system is abstracted away.
>
> Any help or insight on the matter would be much appreciated. I would love to work on a project that would make it possible to let console gamers experience and enjoy all the great mods available to the PC community.

# Answer
The answer is that it is probably possible with a great amount of reverse-engineering effort (but what isn't?). There was an interview with Todd Howard on this topic and he said that identical content could run on PC/Xbox 360/PS3.

The problem is that there isn't a means by which you can get the modded content back onto the console. This has nothing to do with running signed vs unsigned code, this has to do with modifying the data files and stuffing them back into the game. There simply isn't a way to do this on the console.

You could try installing the full game on the 360 hard disk and then grab some linux FUSE drivers for the 360 filesystem (http://code.google.com/p/x360/). This would at least give you filesystem access, from there caveats are sure to abound.
> 5 votes

# Answer
On a possibly related note, there is an Archive.exe tool located in your Skyrim folder that comes along with the Creation Kit when you download it. It has an option to create an Xbox 360 archive - not sure what the difference is but might provide a way to package up a BSA with new resources correctly.
> 1 votes

# Answer
If you dont have a modded box you have a long road ahead of you. Many of us even with modded boxes are having trouble modding the game with anything more than simple .esp files. This is what I would do. Remove your hard drive if you have one installed. Format a usb pendrive on the xbox. This will allow you to install the game to the pen drive as well as install DLC and a new profile. One this is done bring your pen drive to your computer and use a program called horizon to modify and change your settings. Downlaod and install the latest TU7 on the pen drive. Basicly select inject new file from horizon menu. IT will inject and sign any file you want. Now to install custom mods start with only .esps! Its simpler. Download a .esp file and use a program called Le Fluffie to create a dlc file. This is one area you went wrong the xbox cant handle a .esp file alone it has to be inside a container like. Then follow the same steps as for the title update to inject it into your profile. Now this is a quick and dirty answer. My suggestion is to look up info on Horizon and Le Fluffie as how to use them. My self I have over 40 mods running on mine as well as some custom textures but thats another whole story.
> 1 votes

---
Tags: xbox360, modding, skyrim-modding
---


# Question
Title: Adjust sprite bounds of the visible part of texture
Is there any way to adjust the boundaries of the visible part of the sprite? To make it easier to understand: I have a texture, such as shown at figure 1. Then I break it into pieces and fill the resulting fragments using PRKit (wood texture on figure 2 and 3). But the resulting fragments have the transparent (green color on figure 2 and 3) and when creating a sprite from the fragments they have the size of the initial texture. Is there a way to get rid of this transparency and to adjust the size of the visible part (wood texture), openGL or cocos2d-x means?

Maybe it help - draw() method from PRKit:

```
void PRFilledPolygon::draw() {

//CCNode::draw();

glDisableClientState(GL_COLOR_ARRAY);

// we have a pointer to vertex points so enable client state
glBindTexture(GL_TEXTURE_2D, texture->getName());

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ONE_MINUS_SRC_ALPHA);
glVertexPointer(2, GL_FLOAT, 0, areaTrianglePoints);
glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates);

glDrawArrays(GL_TRIANGLES, 0, areaTrianglePointCount);

glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

//Restore texture matrix and switch back to modelview matrix
glEnableClientState(GL_COLOR_ARRAY);}

```

# Answer
Ok, i did this. First, i create texture from PRFilledPolygon(PRKit), use for that CCRenderTexture, after this i applied the resulting texture for new CCSprite and then i created a bounding box, using data from sites of PRKit and applied it to a sprite using setTextureRect().
> 0 votes

---
Tags: opengl, opengl-es, cocos2d, cocos2d-x
---


title: Libraries for multi threading

text:
# Question
Title: Libraries for multi threading
When multithreading a game what do i need to think about when picking the Libraries when developing for pc? I have been looking at process.h and was wondering if there are any big downsides (like speed or stability) whit this library and if i should look at something else?

# Answer
The only decent C++ multithreading libraries are TBB and Microsoft's PPL. Picking anything else is begging for trouble.
> 1 votes

# Answer
Your question is a bit vague ("a game"... any game?) but I doubt you will have trouble with a "library" so much as your actual engine design. The harder/est part is to code your engine in such a way is that multi-threading is implemented correctly; picking a library (probably more appropriately, a language) that handles this well is almost trivial.
> 0 votes

---
Tags: multithreading
---


# Question
Title: Game Editor - When screen is clicked, how do you identify which object that is clicked?
I'm trying to create a Game Editor, currently just placing different types of Shapes and such. I'm doing this in Windows Forms while drawing the 3D with XNA. So, if I have a couple of Shapes on the screen and I click the screen I want to be able to identify "which" of these objects you clicked.

What is the best method for this? Since having two objects one behind the other, it should be able to recognize the one in front and not the one behind it and also if I rotate the camera and click on the one behind it - it should identify it and not the first one.

Are there any smart ways to go about this?

# Answer
In this video I show how do it with code...the projection/view is isometric, but all calcs are done in 3D...

http://www.youtube.com/watch?v=axHp1f3RlHM

When I calculate the mouse ray, I check for collision against a plane... but the procedure is analog to check against a list of boundingspheres associated with your objects.

The algorithm should be similar to this:

```
1. Calculate mouse ray
2. for every object
3.     check if ray intersecs with it
4.         if does then save the object and the distance in a sorted list by distance
5. choose from sorted list the nearest object.

```
> 1 votes

# Answer
The first thing you need to have a good grasp of is transforming 3D points to 2D screen coordinates and back again. Here are a couple of answers I gave about that subject; Understanding 3D to Screen, 3D to 2D.

Now, to go from your mouse coordinate in 2D to 3D you need to do a 3D to 2D transformation backwards. This is fairly simple.

An object/local coordinate is transformed to screen space by multiplying it with the world matrix (get the world coordinate), then by the view matrix (make the world coordinate relative to the camera) and then the projection matrix (get the screen coordinate).

Doing this backwards is easy. Invert all the matrices. Then multiply by the inverted projection, then the inverted view matrix. Now, you won't have a 3D coordinate for your mouse. The reason is because you were missing a dimension of data. So what you have is a ray instead. But that's good. The ray will have a defining coordinate and will be pointed in the same direction as the camera look at vector. You may also notice you don't need to invert the world matrix for any object. That's just because you don't really want the ray in object/local space, there's no point, you probably have your collision volumes defined in world space too.

Now all you have to do is circle/box/poly ray intersection testing to work out if the ray intersects with an object.

Find all of the objects that are intersected and keep a list. Then work out the distance of each object from the camera. The one closest to the camera is the one the user wanted to pick.

Here's the code you would need to do this in XNA. This solution should also work for other kinds of projects (as long as you convert it first). If you are only rendering 2D sprites then you're probably not using a projection matrix, so just hand the function the Matrix.Identity.

```
using System;
using Microsoft.Xna.Framework;

namespace FluxPrototype
{
    /// <summary>
    /// Contains functions useful in working with XNA Vectors.
    /// </summary>
    static class VectorHelper
    {
        /// <summary>
        /// Converts a Vector2 position into a 3D ray.
        /// </summary>
        /// <param name="Position">The 2D position.</param>
        /// <param name="View">The view matrix for the camera.</param>
        /// <param name="Projection">The projection matrix for the camera.</param>
        /// <param name="Point">The returned point defining part of the 3D ray.</param>
        /// <param name="Direction">The direction of the 3D ray.</param>
        public static void Unproject(Vector2 Position, Matrix View, Matrix Projection, out Vector3 Point, out Vector3 Direction)
        {
            if (Position == null)
                Position = Vector2.Zero;

            // Create two 3D points from the position. The first one we will return.
            Point = new Vector3(Position, 0);
            Vector3 Point2 = new Vector3(Position, 1);

            // Transform the points.
            Matrix InvertedProjection = Matrix.Invert(Projection);
            Point = Vector3.Transform(Point, InvertedProjection);
            Point2 = Vector3.Transform(Point2, InvertedProjection);

            Matrix InvertedView = Matrix.Invert(View);
            Point = Vector3.Transform(Point, InvertedView);
            Point2 = Vector3.Transform(Point2, InvertedView);

            // Use the difference between the points to define the ray direction.
            // This will only be the camera direction if the view frustum is orthographic.
            Direction = (Point2 - Point);
            Direction.Normalize();
        }
    }
}

```
> 8 votes

# Answer
Typically, I'll just create a bounding volume out of my mouse. The origin being where I clicked. Then, complete an intersection test by looping all objects. Then, sort the list you get back based on the criteria you want and select element 0.
> 2 votes

# Answer
An idea I have considered but not yet tried:

Draw an offscreen image the same as the real image but no textures etc. Simply draw your objects, each object in a different "color" where the "color" is really just an object number. To figure out what's under the mouse you simply look at the color of the pixel on the alternate image.

Of course this is doing a lot of wasted work but it's the GPU doing it rather than the CPU and it's sure to resolve things by exactly the same rules.
> 1 votes

---
Tags: xna, c#, editors, map-editor, windows-forms
---


title: Any faster method?

text:
# Question
Title: Any faster method?
Manhattan distance is used to the center in chess code that uses an 0x88 board .

0x88 board is 128 square.

```
public static final byte DISTANCE[] = {
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 7, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 7, 6, 7, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 7, 6, 5, 6,
        7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 7, 6, 5, 4, 5, 6, 7, 0, 0,
        0, 0, 0, 0, 0, 0, 7, 6, 5, 4,
        3, 4, 5, 6, 7, 0, 0, 0, 0, 0,
        0, 7, 6, 5, 4, 3, 2, 3, 4, 5,
        6, 7, 0, 0, 0, 0, 7, 6, 5, 4,
        3, 2, 1, 2, 3, 4, 5, 6, 7, 0,
        0, 7, 6, 5, 4, 3, 2, 1, 0, 1,
        2, 3, 4, 5, 6, 7, 0, 0, 7, 6,
        5, 4, 3, 2, 1, 2, 3, 4, 5, 6,
        7, 0, 0, 0, 0, 7, 6, 5, 4, 3,
        2, 3, 4, 5, 6, 7, 0, 0, 0, 0,
        0, 0, 7, 6, 5, 4, 3, 4, 5, 6,
        7, 0, 0, 0, 0, 0, 0, 0, 0, 7,
        6, 5, 4, 5, 6, 7, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 7, 6, 5, 6,
        7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 7, 6, 7, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0
    };

```

Is there any other faster method instead of 0x88 to find distance?

# Answer
> 2 votes
### To make sure you know how Manhattan Distance works

Manhattan distance is the sum of the total difference along each axis. In regular geometry you use Pythagoras' theorem:

where ***a*** and ***b*** are the difference along the ***x*** and ***y*** axes, and ***c*** is the total distance between the points.

In Taxicab geometry you don't need to square it. It's extremely simple. The distance between one point and another is just the sum of the distance along each axis. In 2D:

***x difference*** \+ ***y difference*** = ***Manhattan distance***

### The fast method to calculate this

Create a function which takes two points and calculates the above. If you don't know how to do that, you need to go find a tutorial and start learning your programming language through it.

---
Tags: chess
---


# Question
Title: How to generate seamless hexagonal textures
I'm doing a tactical game (X-Com / Fallout style) for fun. I've decided to use a hexagonal map, but I'm having a graphic problem.

My current map display is HUD-like, with only the border of the map cells displayed, without any texture. It's simple and allows for display of different types of information by varying the color of the border. For example, the "danger view mode" displays the borders with a color going from green (no damage possible) to red (prob of damage \> 90%).

Now, it's a bit hard to differentiate the kind of tile the player is on. I could put a plain color (green is grass, pale blue is water...), but this is going to limit the possibilities. Thus, I would like to display a texture on my tiles. Since the maps are generated, I can not use a picture for the whole map with the HUD over.

So, my question is: does anyone know how can I generate the seamless hexagonal textures (algo or plugin)?

# Answer
> 1 votes
Can't you just do a planar projection of a regular tiling texture onto your tiles and just have hard edges where your tile types switch? So on your hexes that are "grass" just map their UVs in "map space" to a repeating grass texture.

# Answer
> 1 votes
Take an ordinary texture and chop it up to make your hexagonal tiles.

To clarify: Take a seamless texture that's square. Use appropriate bits of it to make your hexagons. If you select your pieces appropriately you get a seamless texture on your hexagons. Note that each hexagon gets a different piece of the underlying texture up until the point the pattern repeats.

---
Tags: textures, graphics, tiles, hexagonal-grid
---


title: How many UDP ports for an MMOFPS

text:
# Question
Title: How many UDP ports for an MMOFPS
I'm designing an MMOFPS. I'm not sure whether to use one UDP port for all clients or one UDP port per client. Or is there another alternative?

Currently UDP is only being used for position data (X,Y,Z, heading, and pitch).

# Answer
> 4 votes
Having one UDP port per client seems complicated an inefficent. The client would need to start by sending a **open-port-request** so the server opens a new port for that client. Also, the performance for checking ports for available data might degrade with the number of sockets.

As long as the received datagram is handled quickly so the thread can continue receiving new data I don't think you'll have a bottleneck here. A solution would be to have one thread receiving UDP datagrams and just putting them on a queue. Use a pool of worker threads that pop data from queue and perform the actual work. The number of worker threads could be chosen to match the number of cores available on the machine.

---
Tags: architecture, mmo, client-server, first-person-shooter, udp
---


title: Syncing properties across a game server

text:
# Question
Title: Syncing properties across a game server
I'm beginning to implement a simple scripting system into my networked server, and I've hit a snag. Before, I've been wrapping my calls into functions on objects that manipulate objects, but lately I've been finding this to be a pain for simple things. For example, if I set 'player.HP = 1'.. this works server-side. But the player side never sees this change unless I explicitly send a packet to inform the client.

For many things like map swapping that require more complicated changes, like change X, Y, Map and do this.. I have a function. That's fine. But what about these small properties I want to sync?

# Answer
> if I set 'player.HP = 1'.. this works server-side. But the player side never sees this change unless I explicitly send a packet to inform the client.

So... explicitly send a packet to inform the client. Not from within the script, from the code that manages the property changes.

On a very basic level, you can send an update message whenever you change a property. Just make sure your property changing mechanism stores the changes, and send out those changes when appropriate.

Another way is to give these properties dirty flags. Set the flag when you change a property, and periodically you check all the properties to see if any are dirty. Copy the new values of the dirty properties into a message, send that message to the client, then clear the dirty flag.
> 0 votes

---
Tags: c#, networking, scripting, online
---


# Question
Title: Keeping player aligned to grid in Pacman
I am making a Pacman game using XNA. The game is tile based, with each tile being 32 pixels. As the player moves, I need to know whenever it is perfectly on a tile (ie position of 32, 64, etc...) so that I can check to see if the next tile is free. I am using the following logic to test this.

```
if (position.X % 32 == 0 && position.Y %32 == 0)
{
    onTile = true;
}

```

I figure that I need to make the player's speed evenly divide 32. Everything works fine if I make the player's speed an integer such as 4 or 8. But if I make the speed something like 6.4, I end up with positions such as 64.00001, and my if statement no longer works correctly.

How can I keep the player aligned with the grid, while allowing a wider range of player speeds than 1, 2, 4, 8, 16, and 32? Or is there some better way to go about this?

Thanks

# Answer
> 2 votes
I've used the modulus operator method before while I was trying to emulate the movement in classic JRPG games, and also ran into the same limitation as you did. In order to be able to use any speed value, you need to approach the problem in a very different way.

The method I suggest is to treat movement as if you were following a path, moving your character between each node in the path at whatever speed you want, *but* making sure to **keep the path nodes aligned to the grid**. Because if all of the end points of your movement are aligned to the grid, then your character will also remain aligned, no matter what speed he's moving at.

For this answer I'll just give an example of how it can be implemented, although there are many other ways to do it. I've based the implementation for this answer on another answer I've given before, which I suggest you to check if you have any questions about the method below:

The core of that answer is the following method which moves the `position` towards a `goal`, snaps to the `goal` if the movement happens to overshoot, and lets the user know when the movement has finished:

```
private bool MoveTowardsPoint(Vector2 goal, float elapsed)
{
    // If we're already at the goal return immediatly
    if (_position == goal) return true;

    // Find direction from current position to goal
    Vector2 direction = Vector2.Normalize(goal - _position);

    // Move in that direction
    _position += direction * Speed * elapsed;

    // If we moved PAST the goal, move it back to the goal
    if (Math.Abs(Vector2.Dot(direction, Vector2.Normalize(goal - _position)) + 1) < 0.1f)
        _position = goal;

    // Return whether we've reached the goal or not
    return _position == goal;
}

```

Using this method, it's pretty simple to move your character around. But unlike the other answer, this time instead of using a list of positions as the path for the character to follow, I decided to only record what the *next* target is, and compute a new target whenever the old one is reached.

I created these variables for the pacman, that specify its position, speed, direction, and a *nullable* Vector2 to store the next target in its path:

```
private Vector2 _position = new Vector2(32, 32);
private const float Speed = 156;
private Vector2 _direction = new Vector2(0, 1);
private Vector2? _target;

```

And here's the bulk of the `Update` method:

```
// Detect user input and set direction
if (Keyboard.GetState().IsKeyDown(Keys.Down)) _direction = new Vector2(0, 1);
if (Keyboard.GetState().IsKeyDown(Keys.Right)) _direction = new Vector2(1, 0);
if (Keyboard.GetState().IsKeyDown(Keys.Up)) _direction = new Vector2(0, -1);
if (Keyboard.GetState().IsKeyDown(Keys.Left)) _direction = new Vector2(-1, 0);

// If there's no target and we can move in the chosen direction, set new target to be the next tile
if (_target == null)
    if (CanMoveInDirection(_position, _direction))
        _target = _position + _direction * 32;

// If there's a target, then move pacman towards that location, and clear target when destination is reached
if (_target != null)
    if (MoveTowardsPoint(_target.Value, (float) gameTime.ElapsedGameTime.TotalSeconds))
        _target = null;

```

The comments should be self explanatory, but I suggest you to try the sample below and see for yourself how it works. Just copy the code into a new XNA project, it does not require any assets to run.

*PS: I know some parts of the movement are not behaving exactly like pacman, such as stopping when changing direction towards a wall. The point of this answer is really just the grid aligned movement.*

# Answer
> 2 votes
I would keep the position in units of tiles, not pixels, in an integer. Then I'd Hold the direction the player is moving, it could take values like, NORTH, SOUTH, EAST, etc. Then I would have two offsets as floats. On each update, I would then use the direction to figure out which offset to add to. If I was moving NORTH, I would subtract speed variable from the yOffset. If I was going SOUTH, I would add speed to yOffset. If I was going WEST, I would subtract speed from xOffset. And so on. Finally I would check to see if the yOffset is greater than the tile size and if it is, I'd add 1 to it's yPosition. If it's less, I'd subtract. I would do the same for the x. When rendering I would always do xPosition + xOffset. Which I'd do for the y too.

# Answer
> 1 votes
What I've done is previous projects is not match the player *exactly* to a particular tile but more like if they are mostly overlapping a tile.

```
Vector2 tilePosition = new Vector2(position.X % 32, position.Y % 32);
if(tilePosition.X >= 16)
    tilePosition.X = position.X + 32 - tilePosition.X;
else
    tilePosition.X = position.X - tilePosition.X;

... repeat for Y ...

```

Obviously there are cleaner ways of writing that but the idea is that if half of the player is overlapping the next tile, assume they are on said tile. And since you are checking if they can intersect the next tile before hand you can always assume that they are never half on an open tile and half on a collidable tile.

**EDIT:** The idea behind this approach is that unless you use exact multiple of your tile size as your movement speed then you can never assume that the player *exactly* occupies a single tile.

Instead, when a player is colliding with at least 50% of a tile, consider them to be occupying that tile.

In the image above, we would consider the player to be occupying the green tile instead of the blue tile.

---
Tags: tiles, grid
---


# Question
Title: Finding if a point is inside of a mesh (Point-in-polyhedron)
How can I find if a point (Vector3) is inside of a mesh? Would this work for both concave and convex objects? I read somewhere that if you raycast in both directions of every axis (X, -X, Y, -Y, Z, -Z), take the count of the hits, and if it is even it is outside, if it is odd it is inside. I tried this and it didn't work.

# Answer
> 6 votes
Figured it out.

What you have to do is raycast from your point in any direction you want. Then, count how many times the raycast intersects with your mesh. If the count is an odd number, it is inside of the mesh. If it is even it is outside of it.

Since unity doesn't raycast on inside sides, you have to flip the faces in your 3d authoring tool. Then you have to raycast in the opposite direction to make up for the other side. (I haven't figured out how to get the count of hits from the raycast yet. But I am using a cube right now, which only has 2 perpendicular faces, so it works)

Unity C# code:

```
bool checkIfInside(Vector3 point) {

    Vector3 direction = new Vector3(0, 1, 0);

    if(Physics.Raycast(point.position, direction, Mathf.Infinity) &&
        Physics.Raycast(point.position, -direction, Mathf.Infinity)) {
            return true;
    }

    else return false;
}

```

---
Tags: collision-detection, unity, 3d-meshes, raycasting
---


# Question
Title: AABB Sweeping, algorithm to solve "stacking box" problem
I'm currently working on a simple AABB collision system and after some fiddling the sweeping of a single box vs. another and the calculation of the response velocity needed to push them apart works flawlessly.

Now on to the new problem, imagine I'm having a stack of boxes which are falling towards a ground box which isn't moving:

Each of these boxes has a `vertical velocity` for the "gravity" value, let's say this velocity is `5`.

Now, the result is that they all fall into each other:

The reason is obvious, since all the boxes have a downward velocity of `5`, this results in no collisions when calculating the relative velocity between the boxes during sweeping.

> Note: The red ground box here is static (always 0 velocity, can utilize spatial partitioning ), and all dynamic \> static collisions are resolved first, thus the fact that the boxes stop correctly at this ground box.

So, this seems to be simply an issue with the order the boxes are sweept against each other.

I imagine that sorting the boxes based on their `x` and `y` velocities and then sweeping these groups correctly against each other may resolve this issues.

So, I'm looking for algorithms / examples on how to implement such a system.

The code can be found here: https://github.com/BonsaiDen/aabb

The two files which are of interest are box/Dynamic.lua and box/Manager.lua.

The project is using Love2D in case you want to run it.

# Answer
> 2 votes
I'm not sure if this is how other systems solve this problem but here is an idea:

1. first move all objects like you normally do.
2. resolve all static vs dynamic collisions.
3. resolve all dynamic vs dynamic collision.
4. for every dynamic object which had a collision resolve all collision.
5. repeat step 4 until either there is no collisions left or you reach a limit of some kind (for example you reach more than 10 iterations)

also as I previously mentioned reducing time step will surly help fixing that bug.

---
Tags: collision-detection, algorithm, aabb
---


title: Periodic updates of an object in Unity

text:
# Question
Title: Periodic updates of an object in Unity
I'm trying to make a collider appear every 1 second. But I can't get the code right. I tried enabling the collider in the Update function and putting a yield to make it update every second or so. But it's not working (it gives me an error: ***Update() cannot be a coroutine.***)

How would I fix this? Would I need a timer system to toggle the collider?

```
var waitTime    : float = 1;
var trigger     : boolean = false;

function Update () {

        if(!trigger){
            collider.enabled = false;
            yield WaitForSeconds(waitTime);
        }
        if(trigger){
            collider.enabled = true;
            yield WaitForSeconds(waitTime);
        }
    }

}

```

# Answer
> 2 votes
That should be rather simple. Just have an accumulator where you add the elapsed time each frame. As soon as the accumulator is greater or equal to your "waitTime", toggle the collider.

Example:

```
var accumulator:float = 0.0;
var waitTime:float = 1.0;

function Update(){
    accumulator += Time.deltaTime;
    if(accumulator >= waitTime){
        // change enabled from true to false and vice-versa.
        collider.enabled = !collider.enabled;
        accumulator -= waitTime;
    }
}

```

---
Tags: unity, timer
---


title: What is wrong with my Dot Product?

text:
# Question
Title: What is wrong with my Dot Product?
I am trying to make a pong game but I wanted to use dot products to do the collisions with the paddles, however whenever I make a dot product objects it never changes much from .9 this is my code to make vectors

```
vector = {
    make:function(object){
        return [object.x + object.width/2,object.y + object.height/2]
    },
    normalize:function(v){
        var length = Math.sqrt(v[0] * v[0] + v[1] * v[1])
        v[0] = v[0]/length
        v[1] = v[1]/length
        return v
    },
    dot:function(v1,v2){
        return v1[0] * v2[0] + v1[1] * v2[1]
    }
}

```

and this is where I am calculating the dot in my code

```
vector1 = vector.normalize(vector.make(ball))
vector2 = vector.normalize(vector.make(object))
dot = vector.dot(vector1,vector2)

```

Here is a JsFiddle of my code currently the paddles don't move.

Any help would be greatly appreciated

# Answer
> 1 votes
Your make() is creating a directional vector from an object's current position and constant physical attribute? `object.x + object.width/2` Of course that's always going to not change very much and isn't what you really need.

What you want to do is make the directional vector for the moving ball to use in the dot product from the ball's current position - last position to get a sense of what direction it is travelling.

The directional vector for the paddle will always be the same, based on the facing and nothing to do with current position and constants like width. Example would be a paddle on the left edge, the 2D vector would be \[1,0\] and on the right edge \[-1,0\].

Even with that all fixed up all you're going to be able to tell with a dot product is which side of the paddle the ball is on and not whether it hit.

I may be missing something, what purpose did you envision for dot products here?

---
Tags: javascript, physics
---


# Question
Title: Would someone please explain Octree Collisions to me?
I've been reading everything I can find on the subject and I feel like the pieces are just about to fall into place, but I just can't quite get it.

I'm making a space game, where collisions will occur between planets, ships, asteroids, and the sun. Each of these objects can be subdivided into 'chunks', which I have implemented to speed up rendering (the vertices can and will change often at runtime, so I've separated the buffers). These subdivisions also have bounding primitives to test for collision. All of these objects are made of blocks (yeah, it's that kind of game). Blocks can also be tested for rough collisions, though they do not have individual bounding primitives for memory reasons. I think the rough testing seems to be sufficient, though.

So, collision needs to be fairly precise; at block resolution. Some functions rely on two blocks colliding. And, of course, attacking specific blocks is important.

Now what I am struggling with is filtering my collision pairs. As I said, I've read a lot about Octrees, but I'm having trouble applying it to my situation as many tutorials are vague with very little code.

My main issues are:

1. Are Octrees recalculated each frame, or are they stored in memory and objects are shuffled into different divisions as they move? Despite all my reading I still am not clear on this... the vagueness of it all has been frustrating.
2. How far do Octrees subdivide? Planets in my game are quite large, while asteroids are smaller. Do I subdivide to the size of the planet, or asteroid (where planet is in multiple divisions)? Or is the limit something else entirely, like number of elements in the division?
3. Should I load objects into the octrees as 'chunks' or in the whole, then break into chunks later? This could be specific to my implementation, I suppose.

I was going to ask about how big my root needed to be, but I did manage to find this question, and the second answer seems sufficient for me. I'm afraid I don't really get what he means by adding new nodes and doing subdivisions upon adding new objects, probably because I'm confused about whether the tree is maintained in memory or recalculated per-frame.

# Answer
> 2 votes
If you know the maximum size of your world, I would make your root node that size. It keeps things simple with no resizing.

Recalculating the tree each frame is much simpler than moving things around, but it also would be much more expensive. I suspect prohibitively so. Moving objects within the tree may be more performant, but it still may be very expensive depending on how often your objects move across subdivision boundaries. You may have to completely rebuild subtrees in the worst case if too many objects move into the same subdivision. Personally, I would not use an octree for collision detection between moving objects. Perhaps a simpler space partitioning scheme, or an alternative algorithm would be better, but you should benchmark it as you may not have any performance problems.

For the octrees I have seen, there are two parameters: `maxDepth` and `maxElements`. If your current depth is equal to `maxDepth` or the number of elements left to be inserted is less than or equal to `maxElements` then you do not subdivide any farther. For an example of octree building code look here. You would have to modify it to use bounding boxes instead of points, which can cause some complications like an object which straddles two (or more) subdivisions.

There is a trade off with `maxDepth` allowing you to control how much time is spent traversing the tree, and `maxElements` allowing you to control how many objects you will be processing once you find the appropriate leaf in the tree. If processing an element is cheap you may have a large `maxElements` and low `maxDepth` because traversing the tree is more expensive than just processing some extra elements and saves you memory. Conversely, if processing an element is expensive, a high `maxDepth` and a low `maxElements` will mean you spend more time traversing the tree and take up more memory but it is worth it because it cuts down on the expensive element processing.

However, with massive differences in size between objects, you may find that having a small `maxElements` will cause problems in that you may have a very large object beside many small ones. Unless you can split the large object into smaller pieces and insert them separately, you won't be able to split the node into 8 pieces and still have the large object fit into one of the subdivisions.

As to what you should insert into the octree, you need to think about what you will be doing once you get to the leaf in the octree. You will have a list of these things, and you will have to do something to find if/where a collision happens. The octree will help make this list shorter, but you will need to do the actual collision detection with these objects.

---
Tags: collision-detection, octree, space-partitioning
---


# Question
Title: Resources for 2D rendering using OpenGL?
I noticed that there is quite some difference between 3D and 2D rendering using OpenGL, the techniques are different - pixel-perfect placing is a lot more desirable, among other things.

Are there any good (complete) references on using OpenGL for rendering 2D graphics? There are quite a few "tutorials" around on the net that help you open a window, set up a half-decent environment and draw a sprite, but no real good information on rotation, blending, lightning, drawing order, using the z-buffer, particles, "complex" primitives (circles, stars, cross symbols), ensuring pixel-perfect rendering, instancing and many other staple 2D effects/techniques.

Any books, great blogs, anything? Any particular awesome libraries to read?

# Answer
OpenGL 2D and 3D rendering is almost same except few things:

* **Orthographic** projection instead of perspective projection. There is no problem pixel-perfect placing if your ortho has same width,height as your window have.
* Usage of 2D vertices, unless you aren't drawing 3D things in 2D projection
* 2D rendering is a lot of simpler 3D

Everything else is same - pipeline, shaders, texturing, buffers.

Resources you would probably like:

* GPWiki - category OpenGL \- basics about OpenGL, window creation, input,...
* NeHe Productions \- good step-by-step tutorials about OpenGL, almost everything is presented using 3D objects, but a lot of is applicable in 2D rendering
* Lighthouse3D.com - GLSL \- tutorials about OpenGL Shading Language. Like in NeHe, they are presented using 3D objects, but GLSL is usable for 2D, too. It's very easy to create nice effects with it.
> 4 votes

# Answer
Have you read the OpenGL red book? Check out chapter 2 and 8.
> 0 votes

---
Tags: opengl, 2d, rendering
---


# Question
Title: Acceptable sound quality: stereo needed for an Android game?
I have various simple short sound effects (damage sound, dying sound, thunderbolt, fanfare, breaking) for a game that is developed for Android currently.

I use OGG files: 96kbps VBR, 44.1KHz, 2 channels (that means stereo, right?).

I read the other stackexchange topics about "acceptable sound quality", but they're too general, address too many things. My experience is that even with 80kbps, my effects sound OK. But I tested it on a limited number of Android devices (including a Sony Ericsson Xperia Neo and a HTC Desire HD). My questions:

1. For mobile phones and tablets, generally, what parameters are recommended? Won't my 80kbps sounds be bad on a newer device (such as a modern tablet)?
2. I don't hear any difference between stereo and mono (2 channels vs. 1 channel, right?), **is there any noticeable difference at all for mobile phones / tablets?** (in terms of the player experience) May it worth it at all? I assume that stereo sounds take much more in memory (when they're decoded to PCM), despite of the fact that the compressed OGG size is practically the same.

---

Reacting to Roy T.'s great comment:

1. Actually, I couldn't measure the PCM size (Android decodes OGG internally), but I thought that stereo will take more space than mono when uncompressed
2. After throwing out one of the WAV channels in Audacity, and re-exporting it:

* The new WAV file size is half than before
    * The OGG file size is practically the same as before
3. The sound effects and game music was recorded by my friend who is an experienced hobby musician/composer, but he knows little about computers & software so he just gave me some high-quality WAV files generated via his hardware.These were stereo, **but if I check them in Audacity**, both channels **appear to be exactly the same**.Can I consider them the same (=\> moving to mono), or might there be some unnoticeable differences to the human eye?

# Answer
> 2 votes
It's a balancing act. If you're trying to save memory, package size or processing time, lower quality mono sound is better. And of course, the acceptable quality is entirely up to you to decide if it's acceptable enough.

However, I believe you might be missing some use cases. Keep in mind that people can attach their mobiles and tablets to:

* Headphones (very common for public places)
* External powered speakers
* Even their home entertainment system via HDMI.

So there is a reason for strive for higher quality sound than can be appreciated through the tiny speakers on many mobile devices. Stereo sound would be important for any listed situations and the lower on the list you go the higher quality the sound needs to be for optimal appreciation.

To address #3:

You can check to see if they are the same. Split the channels, invert one and subtract it from the other. If there's nothing left afterward, then you know they were the same. See here for steps on how to do that.

# Answer
> 3 votes
If it is background music, then I suggest keep it stereo.

If they are sound effects (like jumping, shooting, etc) then keep them mono. It doesn't make sense keeping shooting sound stereo. Instead mono sound should be mixed to stereo depending where on screen does your character currently is located. For example, if it is at right screen edge - then the shooting sound should come from right speaker.

Also - I would say 44.1 kHz is unnecessary for game sounds. Keep them 22.5. It will reduce size twice. And will be 2x as fast for audio mixing (this depends on what library/API you are using for sound mixing/playback),

---
Tags: android, mobile, sound-effects, ogg-vorbis
---


# Question
Title: Resources to learn XNA for a professional c# developer
I'm a .net consultant (mainly c#) for my job, but for a while now, I've been interested in making a game in XNA (as a hobby project).

I've had a "beginner" course in XNA when I was still a student, but I've lost most of the information (plus, it was VERY beginner, not enough to get you really started).

So my question, which resources would be useful for me to learn XNA (books, blogs, websites, tutorials, resource websites - like textures, audio files, etc..)?

I know this is a very open question, but I'm thankful for any information.

# Answer
I was in the same situation as you in the sense that I was already very familiar with C# and .NET and just wanted to learn the XNA API as quickly as possible. I'll just describe the resources I've used in the beginning.

In that situation (and although it's a bit outdated now because the API changed a bit in version 4.0) I found Riemers (check his website too) book "**XNA 3.0 Game Programming Recipes A Problem-Solution Approach**" to be really useful:

The reason for that is that the book is divided into small sections, or *recipes*, about 3 or 4 pages each, and each recipe is focused on a different problem, a different portion of the API. At the start of the book he also recommends many different orders to read the book depending on your goals.

So I read through the recommended recipes to get up to speed with 2D and 3D rendering, content loading and input handling, which took less than a day, and afterwards, any time I picked the book I would just look at the table of contents, pick a recipe that interested me at random and read it.

But what I was particularly surprised with was the breadth of topics covered, because after all of the basic beginner recipes, there are also a lot of recipes on advanced topics that I really didn't expect to see in the same book, such as:

* vertex and pixel shaders
* ocean shader (complete with waves, refraction, reflection, and fresnel term)
* particle system
* bloom post processing
* shadow mapping
* bump mapping
* a procedural race track with catmull-rom
* height-map terrain
* octree
* deferred shading
* picking
> 0 votes

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


title: Flixel: doesn't light tile up

text:
# Question
Title: Flixel: doesn't light tile up
i'm creating a game with flixel, and I want to have a effect when you mouse over a tile, I tried implementing it, and this is what it gives:

```
    public class GameState extends FlxState
{
    private var block:EmptyBlock;
    public function GameState()
    {

    }

    override public function create():void {
        for (var i:Number = 0; i < 30; i++) {
            block = new EmptyBlock(i, 20);
            block.create();
        }
    }

    override public function update():void {
            block.update();
            super.update();
    }
}

}

```

GameState class

and here is the EmptyBlock class:

```
public class EmptyBlock
    {

    private var x:int;
    private var y:int;
    private var row:FlxRect
    public function EmptyBlock(x:int, y:int )
    {
        this.x = x;
        this.y = y;
    }

    public function create():void {
         row = new FlxRect(x, y, 32, 32);
        trace ("Created block at" + x + y);
    }

    public function update():void {
        if (FlxG.mouse.screenX == row.x) {
            if (FlxG.mouse.screenY == row.y) {
                var outline:FlxSprite = new FlxSprite(row.x, row.y).makeGraphic(row.width, row.height, 0x002525);
            }
        }
    }

}

}

```

UPDATE:

The problem is still not solved.

I tried what you recommended, this is the new code:

```
  public class EmptyBlock extends FlxSprite {
       private var outline:FlxSprite;
       [Embed(source = 'freetile.png', mimeType="image/png")] private var    freeTile:Class;
    public function EmptyBlock(x:int, y:int) {
        this.x = x * 32;
        this.y = y;
        width = 32;
        height = 32;

        // Note: this is a block, rather than an outline.
        // Create an outline image, then use loadGraphic()
        // instead of makeGraphic() if you want an outline.
        outline = new FlxSprite(this.x, this.y);
        outline.loadGraphic(freeTile, false, false, 32, 32, false);
    }

    override public function draw():void {
        super.draw();
        if (overlapsPoint(FlxG.mouse.getScreenPosition()))
            outline.draw();
    }
}
}

```

And I call it here:

```
        public function  createMap():void {
        var block:EmptyBlock = new EmptyBlock(0, 0);
        block.draw();

    }

```

Do you see what i'm doing wrong?

Thanks!

# Answer
> 4 votes
Your GameState creates a number of (overlapping) objects. However, you never store these anywhere or add them to the display list; you assign them to one variable, which means you're throwing away all but the last.

In your update loop, you update this ONE block explicitly. You never draw it explicitly.

Normally in Flixel, you'd create objects like this by deriving from FlxSprite, which is a type of FlxBasic. This object can be added to a FlxGroup; your GameState happens to be a FlxGroup you can add objects to. When an object derived from FlxBasic is added to a FlxGroup, the group automatically updates and draws it each frame for you.

In other words, by not deriving your type from FlxSprite, you're bypassing Flixel and saying "I'll update and draw this myself". But since you discard all but one object, and fail to draw this object, you see nothing.

Inside EmptyBlock, you attempt to check to see if the mouse is overlapping in your update function. You then create a FlxSprite, and assign it to a variable which is discarded and never used. In order to update and draw this object, you would want to add it to a FlxGroup such as your GameState, or to another FlxGroup which belongs to your GameState.

So, to fix this: first, change your GameState to add() the object after creating it, instead of assigning it to block. This will fail, because EmptyBlock isn't a type derived from FlxBasic; so change EmptyBlock to derive from FlxSprite. This will fail, because FlxSprite has x and y variables built-in, as well as an update function. So remove your own x and y, and change the update function to override. Besides having its own x and y variables, FlxSprite also has width and height. So instead of making a FlxRect, let's use those to store the object position and size.

Now that your object is a FlxSprite, and now that it's added to the group, it'll be updated and drawn every frame automatically. So remove the explicit call to update in your GameState. That leaves you with an update() that only calls super.update(), so you can remove it if you like.

You can also get rid of the "deferred constructor" pattern you used in EmptyBlock. The reason GameState uses a create() function instead of putting everything in the constructor is so that creating a new GameState can be deferred until the beginning of the next frame, because you're likely to be in the middle of a frame when you decide to change states. You don't need to do that for EmptyBlock, unless you have a reason you haven't expressed here.

I also assume you don't want the blocks to overlap, so you can multiply the x coordinate by the width when you create them. If you want them to overlap, of course, don't do this.

Your overlap check is flawed, by the way, since you check for exact equality, which is only true when the mouse is at the upper-left-most pixel of the square, so you'll need to change this check to a pair of inequalities on both axes. Flixel has a function to check overlap for you, though, so you don't actually have to write out all four compares--just call overlapsAt().

What about the actual creation of a border and display? Well, as I said, you create a FlxSprite in your update() function, then discard it without ever drawing it. A more logical approach would be to create a border once, then draw it when the mouse is overlapping.

Note that the graphic you make is a filled rectangle, and not an outline. It's also an invisible rectangle, because its alpha component is zero.

Also note that you can use FlxG.log() instead of trace(), when using Flixel.

Here is the resulting code. First, GameState.as:

```
package {
    import org.flixel.*;

    public class GameState extends FlxState {
        override public function create():void {
            for (var i:Number = 0; i < 30; i++) {
                var block:EmptyBlock = new EmptyBlock(i, 20);
                add(block);
            }
        }
    }
}

```

And now EmptyBlock.as:

```
package {
    import org.flixel.*;

    public class EmptyBlock extends FlxSprite {
        private var outline:FlxSprite;

        public function EmptyBlock(x:int, y:int) {
            this.x = x * 32;
            this.y = y;
            width = 32;
            height = 32;

            // Note: this is a block, rather than an outline.
            // Create an outline image, then use loadGraphic()
            // instead of makeGraphic() if you want an outline.
            outline = new FlxSprite(this.x, this.y);
            outline.makeGraphic(width, height, 0xFFFFFFFF);
        }

        override public function draw():void {
            super.draw();
            if (overlapsPoint(FlxG.mouse.getScreenPosition()))
                outline.draw();
        }
    }
}

```

Note that I haven't created an outline. I'll leave that to you. (You can draw it with AS3, but it'd be much easier and more Flixely to make a PNG and load it with loadGraphic().)

Also note that although it's named emptyBlock, it currently shows the default Flixel graphic, which is the Flixel logo. You can remove the call to super.draw() if you don't want it to draw.

If your game scrolls, this code will break, because you're comparing screen coordinates; you can fix this by setting scrollFactor, or by comparing world coordinates instead.

I know this is an awful lot of explanation, but I hope it helps!

# Answer
> 0 votes
It's been a while since I've used Flixel, so just a stab in the dark.

But the code reads like your checking if the mouse position is at an exact point instead of an area (unless I'm misunderstanding Flixels internal functions).

Maybe try something like:

```
public function update():void {
    if (FlxG.mouse.screenX >= row.x && FlxG.mouse.screenX <= row.x+row.width ) {
        if (FlxG.mouse.screenY >= row.y && FlxG.mouse.screenY <= row.y+row.height) {
            var outline:FlxSprite = new FlxSprite(row.x, row.y).makeGraphic(row.width, row.height, 0x002525);
        }
    }
}

```

see if that changes anything

---
Tags: flash, flixel
---


title: Causes of screen tearing and vsync

text:
# Question
Title: Causes of screen tearing and vsync
Is there an explanation of whats going on from the software down to the hardware that explains tearing? One would think that the graphics card would just tell the LCD display to change whenever it wants to. Why do LCD displays have refresh rates at all?

# Answer
Even if there's no electron beam, you're still sending the information to the monitor in the same order, over time. How often you send an entire screen's worth of information is, more or less, the refresh rate.

Consider that LCD pixels take time to change from one value to another. Even if your hardware used a *lot* of bandwidth to send a very high number of frames to the monitor each second, you'd still have to use pixels which could change fast enough to make that meaningful. So although there is no electron beam, there are practical limits to how fast an LCD can refresh.

And if you tell the video card to change what you're sending halfway through a frame, it will do so. Hence, tearing.
> 0 votes

# Answer
Sometimes your video card is faster at drawing than your monitor can possibly refresh, due to its hardware. It will have drawn out a full frame and then started work on the next frame (filling up the buffer with this new data) but it only gets 25% into it before the monitor comes along and grabs the buffer to draw the screen. The buffer it has grabbed is then a frame some fraction completed, but it renders anyway.

If you're moving really fast the difference between the two frames might be pretty dramatic, which looks like a 'tear'. If you're not whipping around it might not be noticeable at all. Vsync instructs the video card to only send up whole frames to the monitor accessible buffers, so the monitor is never in a position to grab a partially written to frame.

It does this by instructing the video card to only write **one frame** to the buffer and only to do so *after* the monitor has grabbed the previous frame. This effectively limits your FPS to your monitor's refresh rate.

On why monitors have refresh rates: It's the hardware involved. High end TVs have very high refresh rates (~500+) but you probably don't want to spend the money on a monitor when you're not even going to be able to tell.
> 0 votes

---
Tags: vsync
---


# Question
Title: Node.js MMO - process and/or map division
I am in the phase of designing a mmo browser based game (certainly not massive, but all connected players are in the same universe), and I am struggling with finding a good solution to the problem of distributing players across processes.
I'm using node.js with socket.io.
I have read this helpful article, but I would like some advice since I am also concerned with different processes.

**Solution 1:**
Tie a process to a map location (like a map-cell), connect players to the process corresponding to their location. When a player performs an action, transmit it to all other players in this process. When a player moves away, he will eventually have to connect to another process (automatically).
**Pros**:

* Easier to implement

**Cons**:

* Must divide map into zones
* Player reconnection when moving into a different zone is probably annoying
* If one zone/process is always busy (has players in it), it doesn't really load-balance, unless I split the zone which may not be always viable
* There shouldn't be any visible borders

**Solution 1b:** Same as 1, but connect processes of bordering cells, so that players on the other side of the border are visible and such. Maybe even let them interact.

**Solution 2:**
Spawn processes on demand, unrelated to a location. Have one special process to keep track of all connected player handles, their location, and the process they're connected to. Then when a player performs an action, the process finds all other nearby players (from the special player-process-location tracking node), and instructs their matching processes to relay the action.
**Pros**:

* Easy load balancing: spawn more processes
* Avoids player reconnecting / borders between zones

**Cons**:

* Harder to implement and test
* Additional steps of finding players, and relaying event/action to another process
* If the player-location-process tracking process fails, all other fail too

I would like to hear if I'm missing something, or completely off track.

# Answer
This is a very vague question, but I'll mention the things you haven't really mentioned and need to consider:

* If processes are unrelated to location, that could mean a lot of internal network traffic for pretty much every action your game handles. Ideally a process should have some sort of internal coherence so that it can minimise network traffic; another way of doing this is to have different processes handle different types of activity, so that information private to that activity never has to hit the network.
* You need to consider how to process events that involve more than one person. Can one player trade with a player on another server?
* When reconnecting to a new process, you don't necessarily have to have disconnected from the old process. (You are allowed more than one network connection, after all.)
* If you have to query other processes to collect information about them as the result of an action, what does the first process do while it waits for responses? What if new information arrives while you're waiting for the responses, and can it invalidate one or more of the responses?
* When you need to save important values to disk, which process is responsible for that? And if it is variable, how do you decide?
* You are assuming the 'load' falls on these back-end servers - but what about the central server in Solution 2? If every player and every action goes through that server then it may not matter how many back-end servers you have.
> 1 votes

# Answer
I don't understand the idea of splitting players across different processes. It sounds like a very premature optimisation which isn't needed.

Surely it's best to have a single server process which everybody connects to, which has enough capacity to handle all the players at once (you plan for \< 10k concurrent players, right?)

There is probably still a need to avoid sending irrelevant updates to all players, but that's still quite feasible.

Personally, I'd suggest that you make it work, test it with 10k players, then attempt to optimise it as needed, rather than having some ludicrously-complicated optimisation built-in to the design before it even works for 2 players!
> 0 votes

---
Tags: mmo, maps, browser-based-games, node.js, process
---


# Question
Title: Should I refer to browser-based games as HTML5 games or Javascript games?
*First of all, I know that there are alternatives to both HTML5 and Javascript, but I worded the question so generally ("browser-based") because if I had said "HTML5" or "Javascript" games that would already imply an answer to the question.*

When writing wiki posts or discussing, I usually call these games "HTML5/Javascript" games. They are written in Javascript, using the new HTML5 technology. What is the proper way to call them: HTML5 or Javascript games? I see that most people opt for HTML5, why?

# Answer
> 9 votes
People opt for HTML 5 because it's new and flashy. As you mention in your question "...using the new HTML5 technology." It's desirable to be producing something that's using the latest technology, and it's desirable for people to play games that are on the cutting edge. HTML5 fulfills those desires.

I would use HTML5 or simply "web games" "browser games".

# Answer
> 3 votes
HTML5 is a buzzword.

A game written in javascript is a javascript game.

# Answer
> 3 votes
While you can ask the question "what makes sense technically?", it might make more sense to ask the question "what communicates what I'm trying to say effectively?" With that in mind, I think I'd just say HTML5.

# Answer
> 2 votes
The canvas element is part of HTML5.

If you make a game in C# with XNA, you say 'developed in XNA', do not mention the language.

# Answer
> 2 votes
*edit* Just to remove Java/Unity/Flash/Whatever from the cycle I've changed it a bit...

What's wrong with just calling them "browser based games", or "Native browser based games" to remove anything requiring a plugin from the mix? That's essentially the phrase you used in your question to identify what you were talking about, and it made it immediately clear.

RE: HTML5 vs JavaScript. Consider for a second that one could technically write a browser based game driven entirely by CSS - no JavaScript. Which might help. And one could write a game using HTML, JavaScript, etc. that wasn't technically "HTML5" - meaning neither of them necessarily technically fit.

Plus consider that sooner or later people will be talking about "HTML6" (or whatever is next).

But in the end, if you say "Browser based game" they know just what you mean. And say "Native browser based games" if you want to not include Flash or other plugin-based implementations of games.

# Answer
> 2 votes
Just be accurate. If you are using an HTML5 technology like canvas or websockets, then sure, tell them it's JS + HTML5. Otherwise, just say it's a JS browser-based game.

I foresee that the HTML5 "tag" will, in time, become less important as it normalises, and then we'll just refer to them as JS games (once again).

---
Tags: javascript, html5, browser-based-games, terminology
---


# Question
Title: What is the role of "systems" in a component-based entity architecture?
I've been reading a lot about entity components and systems and have thought that the idea of an entity just being an ID is quite interesting.

However I don't know how this completely works with the components aspect or the systems aspect. A component is just a data object managed by some relevant system. A collision system uses some BoundsComponent together with a spatial data structure to determine if collisions have happened.

All good so far, but what if multiple systems need access to the same component? Where should the data live? An input system could modify an entities BoundsComponent, but the physics system(s) need access to the same component as does some rendering system.

Also, how are entities constructed? One of the advantages I've read so much about is flexibility in entity construction. Are systems intrinsically tied to a component? If I want to introduce some new component, do I also have to introduce a new system or modify an existing one?

Another thing that I've read often is that the 'type' of an entity is inferred by what components it has. If my entity is just an id how can I know that my robot entity needs to be moved or rendered and thus modified by some system?

Sorry for the long post (or at least it seems so from my phone screen)!

# Answer
There are a multitude of ways to represent and implement entity component systems, but here is an explanation of one way. Keep in mind there is no concrete definition of entity/component/system architectures, so this is just one implementation.

I'm going to introduce an analogy for entity/component/system architectures that might help. Let's think of an entity like a key.

## The Entity

Keys also have teeth (dark blue). The teeth of our entity key is the components that make it up. You can tell entities apart by their ID, even if they have the same teeth. So what do keys fit into? Locks. Locks are our systems. For example, a movement system.

## The System

The lock only works if our key has teeth for both position and velocity. This system only processes entities that have a position and a velocity. There are multiple ways to set up how these systems recognize which entities to process, but one way is to use a `long`. Each bit is reserved for a component type. For our example lets assume a 4 bit type instead of a 64 bit long. Our example entity would have all available components. So it's key would be `1111`. Then, the system is looking for any entity that has a `11--`. (The `-` represent don't care, because movement doesn't care if there's a sprite or health). It can check an entity with a simple `AND` operation. So our entity matches if `((1111 & 1100) == 1100)`. If I lost you there check out some more about bitwise operations.

As you can see, systems have access to outside resources. They can access the time, graphics, sound and so on. They are simply little processors that take one key at a time, and process data. You see that the movement system takes the velocity, delta time and position; then does some calculations and stores the result back into position.

The entity keys are really easy to generate. You can add or remove them at will. The entity doesn't care, it's just a way to group and hold the components. The components have no interdependence. The closest the components get to interacting with each other is when a system operates on them and uses data from one to update another, like our movement example.

Lets take a look at another system to help solidify the idea:

This is our drawing system. It looks for components that match `1-1-`. This entity matches because: `((1111 & 1010) == 1010)` Additionally, you can see that this system outputs information to the screen, by drawing the entity sprite at its position.

OK, one more. Let's look at another entity and see how it might fit into our example so far.

As you can see, this entity has fewer components attached to it. By looking at the components it does have, it looks like it could be a static item like a rock. It just has a position and a sprite. It's not going to move and it's not going to be affected by any health changes. This entity would produce a key of 1010. So what systems operate on this entity? Lets check:

Against our movement system: `((1010 & 1100) != 1100)` Nope. Looks like the movement system doesn't care about this entity, because it doesn't have the components required.

Against our drawing system: `((1010 & 1010) == 1010)` Hey, that's a match. This entity will be operated on by the drawing system. The drawing system will draw the sprite at the position defined.

---

Hopefully you can see how easy it would be to now add another system that would take our components and operate on them. Let me ensure I've addressed your questions:

> What if multiple systems need access to the same component? Where should the data live?

Typically, systems operate one after the other. They process all the entities that match their requirements, then the next system does the same and so on. The data lives with the entity. There shouldn't be anything stored in the system, it's just a lock that gets turned, the key is where the information stays and moves from lock to lock.

> How are entities constructed? Are systems intrinsically tied to a component? If I want to introduce some new component, do I also have to introduce a new system or modify an existing one?

Entities are just bags of components. They have a unique ID and a list of components. Systems are only tied to components in the way described above. You can have components without systems that operate on them, but that's pretty pointless. Similarly you can have systems that are looking for components that no entities have. That's less pointless, because they may just be waiting for an entity to be created that matches their lock. So, yes, if you introduce a new component, you'd want to make a system that utilizes that component. Otherwise you're just adding teeth to your key for a lock that doesn't exist.

> If my entity is just an id how can I know that my robot entity needs to be moved or rendered and thus modified by some system?

I think I answer this with the idea of a `long` key that defines the components contained in an entity. You know because the key fits the lock.

Phew! That was a long post! (Or at least it seems so from my large monitor.)
> 354 votes

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


# Question
Title: Why does multiplying texture coordinates scale the texture?
I'm having trouble visualizing this geometrically - why is it that multiplying the U,V coordinates of a texture coordinate has the effect of scaling that texture by that factor?

eg if you scaled the texture coordinates by a factor of 3 ..then doesn't this mean that if you had texture coordinates 0,1 and 0,2 ...you'd be sampling 0,3 and 0,6 in the U,V texture space of 0..1? How does that make it bigger

eg HLSL: tex2D(textureSampler, TexCoords\*3)

Integers make it smaller, decimals make it bigger

I mean I understand intuitively if you added to the U,V coordinates, as that is simply an offset into the sampling range, but what's the case with multiplication?

I have a feeling when someone explains this to me I'm going to be feeling mighty stupid

# Answer
> 4 votes
A quad with the texture coordinates 0,0 on the one corner and 2,2 on the other corner, means the texture is tiled 4 times, 2 times in each direction.

Now if you have the same quad with 4,4 on the other corner instead you have the texture tiled 16 times, 4 times in each direction.

If you increase the texture coordinates without increasing the size of the quad you are drawing a larger portion of the texture on the same surface, thus making the texture itself look smaller. For drawing a 200x200 texture on a 100x100 quad you need to scale it down, for drawing a 50x50 texture on a 100x100 quad you need to scale it up.

---
Tags: mathematics, textures, uv-mapping
---


# Question
Title: Calculate travel time on road map with semaphores
I have a road map with intersections. At intersections there are semaphores. For each semaphore I generate a red light time and green light time which are represented with syntax \[R:T1, G:T2\], for example:

```
    119                   185                 250
A ------- B: [R:6, G:4] ------ C: [R:5, G:5] ------ D

```

I want to calculate a car travel time from A - D. Now I do this with this pseudo code:

```
function get_travel_time(semaphores_configuration)
{
    time = 0;
    for( i=1; i<path.length;i++)
    {
        prev_node = path[i-1];
        next_node = path[i]);
        cost = cost_between(prev_node, next_node)
        time += (cost/movement_speed) // movement_speed = 50px per second
        light_times = get_light_times(path[i], semaphore_configurations)
        lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4]
        lights_sum = light_times.green_time+light_times.red_light; // Lights cycle time
        light = lights_cycle[cost%lights_sum];

        if( light == "R" )
        {
            time += light_times.red_light;
        }
    }
    return time;
}

```

So for distance 119 between A and B travel time is, 119/50 = 2.38s ( exactly mesaured time is between 2.5s and 2.6s), then we add time if we came at a red light when at B. If we came at a red light is calculated with lines:

```
lights_cycle = get_lights_cycle(light_times) // Eg: [R,R,R,G,G,G,G], where [R:3, G:4]
lights_sum = light_times.green_time+light_times.red_light
light = lights_cycle[cost%lights_sum];
if( light == "R" )
{
    time += light_times.red_light;
}

```

This pseudo code doesn't calculate exactly the same times as they are mesaured, but the calculations are very close to them.

Any idea how I would calculate this?

# Answer
> 0 votes
You have three measurements here:

* Distance between lights (meters)
* Time between red and green (seconds)
* Speed of car (meters per second)

However, it looks like this problem is a lot more complex than what it appears to be at face value.

* Cars don't move at linear velocity. Even in a simplified model, they should speed up and slow down.
* Lights turn off and on at regular intervals. If a car travels faster or slower it will be stuck longer or shorter at red lights.

So what I would do in this case is to just pick a value for the car speed and calculate the outcome. Assume all lights start at the red position, the distances between the lights is in meters and that the car travels at a constant 10/ms (36 km/h or 22.3 mph).

The car will reach the first intersection in 119 / 10 = 11.9 seconds. 11.9 - 6 (seconds of red) = 5.9. 5.9 - 4 (seconds of green) = 1.9. The car will have to wait for (6 - 1.9) = 4.1 seconds. Our total so far is 11.9 + 4.1 = 16 seconds.

The next intersection is reached in 185 / 10 = 18.5 seconds. Our running total is 16 + 18.5 = 34.5 seconds. 34.5 - 5 - 5 - 5 - 5 - 5 - 5 = 4.5 seconds into the red state of the light, so the car has to wait 5.0 - 4.5 seconds. Our running total is now 35.0 seconds.

Finally, the last stretch of road is done in 185 / 10 = 18.5 seconds, which makes our total 53 seconds.

So, how do we put this into a formula? It seems to me that the best way to do this is to keep a running total of the car's time traveled. For every intersection, calculate the time the car will take to reach it (perhaps recursively up a tree?), modulo with the total light time, modulo with the red light time and add that to the running total. Do this for every light and you should get an accurate estimated arrival time. But only for this simple model.

**EDIT:**

Your car has a formula to calculate a position at time `t`. We can use this to see where the car will be in the future. We know that the distance between `A` and `B` is 119 meters, and we know that the car travels at 10 meters per second. In a formula:

```
next_intersection = start + speed * time;

```

So if we solve that for time:

```
start + speed * time = next_intersection;
        speed * time = next_intersection - start;
                time = (next_intersection - start) / speed;

```

So if we plug in our values:

```
time = (119 - 0) / 10;
time = 11.9 seconds

```

However, the lights continue to blink on and off while the car is traveling. So how do we know whether the light is green or red when the car arrives? We divide by the interval, keep what's left over and see if it's greater than the red time:

```
light_time = (time % light_interval);
light_is_red = (light_time < light_interval_red) ? true : false;

```

So if the light is red, we have to add a waiting time.

```
if (light_is_red)
{
    time += (light_time - light_interval_red);
}

```

And then we can travel to the next light, which is at `C`.

What you need most of all is a way to calculate the car's position at a time in the future, without animating it. Determine how you are moving the car and see if you can make a formula out of that that can calculate the car's position at any time in the future or past.

---
Tags: javascript, ai, html5
---


# Question
Title: What OpenGL version(s) to learn and/or use?
So, I'm new to OpenGL... I have general knowledge of game programming but little practical experience.

I've been looking into various articles and books and trying to dive into OpenGL, but I've found the various versions and old vs new way of doing things confusing.

I guess my first questions is does anyone know some figures about percentages of gamers that can run each version of OpenGL. What's the market share like? 2.x, 3.x, 4.x...

I looked into the requirements for Half Life 2 since I know Valve updated it with OpenGL to run on Mac and I know they usually try to hit a very wide user-base, and they say a minimum of GeForce 8 Series. I looked at the 8800 GT on Nvidia's website and it listed support for OpenGL 2.1. Which, maybe I'm wrong, sounds ancient to me since there's already 4.x. I looked up a driver for 8800GT and it says it supports 4.2! A bit of a discrepancy there, lol.

I've also read things like XP only supports up to a certain version, or OS X only supports 3.2, or all kinds of other things. Overall, I'm just confused as to how much support there is for various versions and what version to learn/use.

I'm also looking for learning resources. My search results thus far have pointed me to the OpenGL SuperBible. The 4th edition has great reviews on Amazon, but it teaches 2.1. The 5th edition teaches 3.3 and there are a couple things in the reviews that mention the 4th edition is better and that the 5th edition doesn't properly teach the new features or something? Basically, even within learning material I'm seeing discrepancies and I just don't even know where to start.

From what I understand, 3.x started a whole new way of doing things and I've read from various articles and reviews that you want to "stay away from deprecated features like glBegin(), glEnd()" yet a lot of books and tutorials I've seen use that method. I've seen people saying that, basically, the new way of doing stuff is more complicated yet the old way is bad \>.\>

Just a side note, personally, I know I still have a lot to learn beforehand, but I'm interested in tessellation; so I guess that factors into it as well, because, as far as I understand that's only in 4.x?

\[just btw, my desktop supports 4.2\]

# Answer
If you're wondering about OpenGL coverage, a good place to start is the Steam Hardware Survey.

http://store.steampowered.com/hwsurvey?platform=pc

Unfortunately, it seems to be broken right now and it doesn't display any stats for videocards. :\

> I've also read things like XP only supports up to a certain version

DirectX 9 is comparable to OpenGL 2.1, DirectX 10 to OpenGL 3.0 and DirectX 11 to OpenGL 4.0. This is where the confusion stems from.

XP supports all versions of OpenGL, but it does not support DirectX 10 or up. This is how Microsoft wanted to force people to upgrade to Vista, but it didn't work out very well. OpenGL is an open standard, so as long as videocard manufacturers are willing to produce drivers for XP, it will support newer versions of OpenGL.

> From what I understand, 3.x started a whole new way of doing things and I've read from various articles and reviews that you want to "stay away from deprecated features like glBegin(), glEnd()" yet a lot of books and tutorials I've seen use that method. I've seen people saying that, basically, the new way of doing stuff is more complicated yet the old way is bad \>.\>

This is a very big problem for OpenGL. Basically, in the olden days, you'd send stuff to the videocard by using "immediate mode". Start with `glBegin`, do some stuff, end with `glEnd`. However, video card drivers do not like this *at all*. How can they know how much stuff you're going to send? Is it going to be 4 vertices for a textured quad or 100,000 for a skinned model? This is why they introduced vertex buffer objects (VBO's). While immediate mode is a linked list, a VBO is a static array. The developer knows how big it is, the driver knows how big it is. Everybody's happy. So the OpenGL standards board (Khronos Group) decided to deprecate immediate mode for OpenGL 3.0 and up. However, this is problematic, as I'll show with a simple example.

Let's say you want to display a textured quad, starting from scratch.

In OpenGL 2.1:

* Set up the projection matrix and put it in `GL_PROJECTION`.
* Set up the modelview matrix and put it in `GL_MODELVIEW`.
* Load an image and put it in a `GL_TEXTURE_2D` handle.
* Define the positions, texture coordinates and colors for your vertices.
* Bind the texture.
* `glBegin` ... `glVertex2f` ... `glTexCoord2f` ... `glEnd`.

In OpenGL 3.0:

* Build a matrix for projection and modelview.
* Load an image and put it in a `GL_TEXTURE_2D` handle.
* Define the positions, texture coordinates and colors for your vertices and put them in VBO's.
* Create a vertex array object (VAO's) and attach your VBO's.
* Write a shader to output a textured quad and put it in a shader program.
* Attach the matrices to the shader program using uniforms.
* Bind the texture.
* Attach the texture to the shader program.
* `glDrawArrays`.

So what could go wrong in the first version?

* Your positions are incorrect.
* Your vertex winding is the wrong way around.
* Your texture doesn't load properly.
* Your texture doesn't bind properly.
* Your projection matrix is wrong.
* Your modelview matrix is wrong.
* You're not sending the right vertices.

And in the second version, you can have problems with the above *and*:

* Your VBO's are wrong.
* Your VAO is wrong.
* Your shader is wrong.
* Your texture binding to the shader is wrong.

Without proper debug tools, this becomes a serious problem. This is why people say you should stick to immediate mode. Luckily, we now have the free and excellent gDEBugger now, but it's not a magic bullet.

To answer your question: it depends on your game. If you want to reach a wide audience (for instance a casual game or a 2D platformer), you should target 2.1. If you're making an epic space game that isn't going to run on six-year old hardware anyway, target 3.3. And if you *need* the latest and greatest for future-compatibility, target 4.0.
> 25 votes

# Answer
For some statistics about hardware compatibility you could look at Steam survey: http://store.steampowered.com/hwsurvey/ Although it lists DX10 and DX11, the hardware compatibility is the same as OpenGL 3 and OpenGL 4 respectively. Though note that OpenGL driver installation state on people is usually worse than DX.

Windows XP doesn't support DX10 or DX11, but OpenGL 3 and 4 should be fine, provided the drivers are ok. OSX supports OpenGL 3 (at maximum), on Linux you get OpenGL 4 with ATI/NVIDIA vendor drivers (of course only if the hardware supports it).

Then there is also the mobile ES versions of OpenGL. In fact I'd suggest looking into OpenGL ES 2.0, because it's smaller, so easier to learn, but you also need to use modern practises, i.e. shaders and VBOs. It's also what's used on most mobile devices (so you coul d go into making mobile games) and also WebGL is basically the same, so you could actually do all of your learning in the web browser with it's rapid development advantages. OpenGL ES 3.0 is due this summer.

Tessellation is a OpenGL 4.0 feature. You should first learn the other kinds of shaders, let alone all the basics, but I agree it's interesting - in fact I've written a little test with it: http://blog.tapiov.net/post/15189341463/playing-with-opengl-4-tessellation
> 10 votes

---
Tags: opengl, vbo, tessellation
---


# Question
Title: In Maya how do I convert trans, rot, scale data to a 4 x 4 transformation matrix?
I have been given the following Maya camera data:

trans X: 1.542
trans y: 3.319
trans z: -1.821

rot X: 117.882
rot Y: 2.189
rot Z: 154.074

scale X: 1
scale Y: 1
scale Z: 1

What is the formula for converting this to a 4 x 4 transformation matrix?

# Answer
The matrix I'm using is a row-major matrix used by OpenGL. Here's what it looks like:

```
[ X1 Y1 Z1 WX ]
[ X2 Y2 Z2 WY ]
[ X3 Y3 Z3 WZ ]
[ TX TY TZ CZ ]

```

What you have is actually three matrices: a rotation matrix, a scale matrix and a translate matrix. This is because virtually any 4x4 matrix can be broken down to two or more matrices that together form the original matrix. A matrix concatenation looks like this:

```
mat4x4 m0, m1, m2

m2[X1] = (m1[X1] * m0[X1]) + (m1[Y1] * m0[X2]) + (m1[Z1] * m0[X3]) + (m1[WX] * m0[TX]);
m2[Y1] = (m1[X1] * m0[Y1]) + (m1[Y1] * m0[Y2]) + (m1[Z1] * m0[Y3]) + (m1[WX] * m0[TY]);
m2[Z1] = (m1[X1] * m0[Z1]) + (m1[Y1] * m0[Z2]) + (m1[Z1] * m0[Z3]) + (m1[WX] * m0[TZ]);
m2[WX] = (m1[X1] * m0[WX]) + (m1[Y1] * m0[WY]) + (m1[Z1] * m0[WZ]) + (m1[WX] * m0[CZ]);

m2[X2] = (m1[X2] * m0[X1]) + (m1[Y2] * m0[X2]) + (m1[Z2] * m0[X3]) + (m1[WY] * m0[TX]);
m2[Y2] = (m1[X2] * m0[Y1]) + (m1[Y2] * m0[Y2]) + (m1[Z2] * m0[Y3]) + (m1[WY] * m0[TY]);
m2[Z2] = (m1[X2] * m0[Z1]) + (m1[Y2] * m0[Z2]) + (m1[Z2] * m0[Z3]) + (m1[WY] * m0[TZ]);
m2[WY] = (m1[X2] * m0[WX]) + (m1[Y2] * m0[WY]) + (m1[Z2] * m0[WZ]) + (m1[WY] * m0[CZ]);

m2[X3] = (m1[X3] * m0[X1]) + (m1[Y3] * m0[X2]) + (m1[Z3] * m0[X3]) + (m1[WZ] * m0[TX]);
m2[Y3] = (m1[X3] * m0[Y1]) + (m1[Y3] * m0[Y2]) + (m1[Z3] * m0[Y3]) + (m1[WZ] * m0[TY]);
m2[Z3] = (m1[X3] * m0[Z1]) + (m1[Y3] * m0[Z2]) + (m1[Z3] * m0[Z3]) + (m1[WZ] * m0[TZ]);
m2[WZ] = (m1[X3] * m0[WX]) + (m1[Y3] * m0[WY]) + (m1[Z3] * m0[WZ]) + (m1[WZ] * m0[CZ]);

m2[TX] = (m1[TX] * m0[X1]) + (m1[TY] * m0[X2]) + (m1[TZ] * m0[X3]) + (m1[CZ] * m0[TX]);
m2[TY] = (m1[TX] * m0[Y1]) + (m1[TY] * m0[Y2]) + (m1[TZ] * m0[Y3]) + (m1[CZ] * m0[TY]);
m2[TZ] = (m1[TX] * m0[Z1]) + (m1[TY] * m0[Z2]) + (m1[TZ] * m0[Z3]) + (m1[CZ] * m0[TZ]);
m2[CZ] = (m1[TX] * m0[WX]) + (m1[TY] * m0[WY]) + (m1[TZ] * m0[WZ]) + (m1[CZ] * m0[CZ]);

```

So let's get down to business. First, we have the scale matrix:

```
sx = 1.0
sy = 1.0
sz = 1.0

mat4x4 mat_scale =
    [  sx, 0.0, 0.0, 0.0 ]
    [ 0.0,  sy, 0.0, 0.0 ]
    [ 0.0, 0.0,  sz, 0.0 ]
    [ 0.0, 0.0, 0.0, 1.0 ]

```

The rotational matrix can be further broken down to a matrix on the x-, y- and z-axis.

Rotation over x-axis:

```
cx = cos(deg_to_rad(117.882))
sx = sin(deg_to_rad(117.882))

mat4x4 mat_x =
    [ 1.0, 0.0, 0.0, 0.0 ]
    [ 0.0,  cx,  sx, 0.0 ]
    [ 0.0, -sx,  cx, 0.0 ]
    [ 0.0, 0.0, 0.0, 1.0 ]

```

Rotation over y-axis:

```
cy = cos(deg_to_rad(2.189))
sy = sin(deg_to_rad(2.189))

mat4x4 mat_y =
    [  cy, 0.0, -sy, 0.0 ]
    [ 0.0, 1.0, 0.0, 0.0 ]
    [  sy, 0.0,  cy, 0.0 ]
    [ 0.0, 0.0, 0.0, 1.0 ]

```

Rotation over z-axis:

```
cz = cos(deg_to_rad(154.074))
sz = sin(deg_to_rad(154.074))

mat4x4 mat_z =
    [  cz, -sz, 0.0, 0.0 ]
    [  sz,  cz, 0.0, 0.0 ]
    [ 0.0, 0.0, 1.0, 0.0 ]
    [ 0.0, 0.0, 0.0, 1.0 ]

```

So our final rotation matrix becomes:

```
mat4x4 mat_rotation = mat_x * mat_y * mat_z;

```

Finally, the translation matrix:

```
tx = 1.542
ty = 3.319
tz = -1.821

mat4x4 mat_translation =
    [ 1.0, 0.0, 0.0, 0.0 ]
    [ 0.0, 1.0, 0.0, 0.0 ]
    [ 0.0, 0.0, 1.0, 0.0 ]
    [  tx,  ty,  tz, 1.0 ]

```

Putting it all together:

```
mat4x4 mat_transform = mat_scale * mat_rotation * mat_translation;

```

If you want, you can write out all the concatenations and get a valid matrix. But I believe it's easier to keep it in either separate matrices like I've done or in matrix operations (`AddRotationX`, `Scale`, etc.)
> 3 votes

# Answer
Assuming you know how to construct the individual matrices, I believe the correct order of transformations - going from a node's coordinates to its parent's coordinates - is scale, then rotation in X, Y, Z order, then translation.

Depending on whether your system uses row vectors or column vectors, that will be S * Rx * Ry * Rz * T, or T * Rz * Ry * Rx * S, respectively.

A note on rotation order: Maya doesn't have a concept of "roll", "pitch", or "yaw". It deals with rotations just in terms of axes, and assumes that rotations are always applied in X, Y, Z order. So the natural interpretation would be X = roll, Y = pitch, and Z = yaw.
> 1 votes

# Answer
I don't have time currently to give a complete answer here, because it's fairly in-depth and I'm short on time, but the information I do have time to give is too much to fit in a comment, so I'll give what I can, for whatever it's worth.

First of all, it appears that Rot X, Y, and Z are in euler angles (degrees rotated around an axis). It would depend on which way that rotation goes (clockwise or counterclockwise). And it depends if Maya represents the degrees between 0 and 360, or -180 and 180, if it's -180 to 180 then just add 180 to whatever output Maya gives.

You'll need to convert degrees to radians for each of them by multiplying them by PI / 360. Then convert the radians to an euler angle to determine the rotation's fwd, up, and right vector's. The forward will be represented by Z in most coordinate systems, right represented by X, and up represented by Y, although if you're exporting for a different coordinate system this may differ.

Once rotation is represented by three vectors, it becomes the first three columns (or rows in some systems) or your 4x4 matrix.

The 4th column is the position/translation vector.

Depending on the system using the matrix, I believe the entire matrix's diagonal can be used for scale, or sometimes just the Translation's W coordinate.

An identity matrix would look something like below, giving a rotation in which an object's forward is along Z, its right is along X, and its up is along Y, and it's at position (0, 0, 0).

```
      Rot Rgt   Rot Up    Rot Fwd   Translation

X     1         0         0         0

Y     0         1         0         0

Z     0         0         1         0

W     0         0         0         1

```
> 0 votes

---
Tags: maya, transformation
---