# Question
Title: Help figuring out how to build for the iOS Unit3D
So currently I'm exporting my game strictly for testing to the iOS (iPad.)

I don't own a Mac, so I'm having my client make a build from his Mac, but that means I need very specific instructions for him as he isn't very tech-savvy. I've looked online and can't find much at all about what all you need to export from Unity and make a file for the iOS, then sync it to your iPad. Could anyone provide a video or and help at all for this?

Thanks,

Tim.

# Answer
> 1 votes
As you do not own a Mac I can't see how you could manage to do that. Anyway the steps are basically these:

* You (or your client) should enroll for the Apple Development Program
* after that you have to follow the instruction on how to create a certificate with your credential (i.e. private key, etc.)
* then (in the Apple developer page) you have to create an App id for your app
* then (in the Apple developer page) you have to register the ID of your device (i.e. the IPAD, etc.). You can register up to 100 (as far as I remember)
* then you have to create a provisioning for your app (it associate the app Id, to your identity, to your devices).
* then you have to compile the App with XCode, and with the provisioning you have created.

This last step actually requires a MAC

---
Tags: iphone, unity, ios
---


title: Raymarching artifacts

text:
# Question
Title: Raymarching artifacts
I was playing with raymarching using distance fields in GLSL sandbox and got stuck with a strange problem with artifacts.

Click here and take a look at the spheres generated in corners, they have strange artifacts plus they "flicker".

Is the `mod` operator, for domain repetition the culprit here?

# Answer
I do not think that `mod` operator is the source of artifacts, at least in the general case. Recently I also experimented with raymarching of distance fields and all worked pretty fine. Check my screens lower. My trusty guide in this stuff are tutorials and papers of Iñigo Quílez. If you don\`t know about this guy, taste his strawberry. More concretely: iterative shapes, distance functions and raymarching distance fields.
> 1 votes

---
Tags: opengl, glsl, raycasting
---


title: How do I render using VBOs?

text:
# Question
Title: How do I render using VBOs?
I'm trying to render a hemisphere in OpenGL, the problem that the hemisphere isn't rendered at all, only part of it. I initialize it, then at each frame I draw it using the following code. I'm trying to use a VBO for drawing it.

```
void Jellyfish::Init_HemiSphere(const float radius, const int segments )
{

    m_iSegements = segments;
    m_fVerts= new float[(segments+1)*2*3];
    m_fNormals= new float[(segments+1)*2*3];
    m_fTexCoords = new float[(segments+1)*2*2];

    for( int j = 0; j < segments / 2; j++ )
    {
        float theta1 = j * 2 * 3.14159f / segments - ( 3.14159f );
        float theta2 = (j + 1) * 2 * 3.14159f / segments - ( 3.14159f );

        for( int i = 0; i <= segments; i++ )
        {
            Vec3f e, p;
            float theta3 = i * 2 * 3.14159f / segments;

            e.x = math<float>::cos( theta1 ) * math<float>::cos( theta3 );
            e.y = math<float>::sin( theta1 );
            e.z = math<float>::cos( theta1 ) * math<float>::sin( theta3 );
            p = e * radius;
            m_fNormals[i*3*2+0] = e.x; m_fNormals[i*3*2+1] = e.y; m_fNormals[i*3*2+2] = e.z;
            m_fTexCoords[i*2*2+0] = 0.999f - i / (float)segments; m_fTexCoords[i*2*2+1] = 0.999f - 2 * j / (float)segments;
            m_fVerts[i*3*2+0] = p.x; m_fVerts[i*3*2+1] = p.y; m_fVerts[i*3*2+2] = p.z;

            e.x = math<float>::cos( theta2 ) * math<float>::cos( theta3 );
            e.y = math<float>::sin( theta2 );
            e.z = math<float>::cos( theta2 ) * math<float>::sin( theta3 );
            p = e * radius;
            m_fNormals[i*3*2+3] = e.x; m_fNormals[i*3*2+4] = e.y; m_fNormals[i*3*2+5] = e.z;
            m_fTexCoords[i*2*2+2] = 0.999f - i / (float)segments; m_fTexCoords[i*2*2+3] = 0.999f - 2 * ( j + 1 ) / (float)segments;
            m_fVerts[i*3*2+3] = p.x; m_fVerts[i*3*2+4] = p.y; m_fVerts[i*3*2+5] = p.z;
        }

    }

    glGenBuffers(3,&SVboId[0]);
    //Vertex
    glBindBuffer(GL_ARRAY_BUFFER,SVboId[0]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(*m_fVerts)*(m_iSegements+1)*2*3,
        m_fVerts,GL_DYNAMIC_DRAW);
    // Normals
    glBindBuffer(GL_ARRAY_BUFFER,SVboId[1]);
    glBufferData(GL_ARRAY_BUFFER,sizeof(*m_fNormals)*(m_iSegements+1)*2*3,
        m_fNormals,GL_DYNAMIC_DRAW);

}

void Jellyfish::drawHemiSphere( )
{

    /*glEnableClientState( GL_VERTEX_ARRAY );
    glVertexPointer( 3, GL_FLOAT, sizeof(*m_fVerts)*(m_iSegements+1)*2*3, m_fVerts );*/

    glEnableClientState( GL_VERTEX_ARRAY );
    glBindBuffer(GL_ARRAY_BUFFER,SVboId[0]);
    glVertexPointer( 3, GL_FLOAT, 0, 0 );

    glEnableClientState( GL_NORMAL_ARRAY );
    glBindBuffer(GL_NORMAL_ARRAY,SVboId[1]);
    glNormalPointer( GL_FLOAT, 0,0 );

    /*glEnableClientState( GL_TEXTURE_COORD_ARRAY );
    glTexCoordPointer( 2, GL_FLOAT,  sizeof(*m_fTexCoords)*(m_iSegements+1)*2*3, m_fTexCoords );
    glEnableClientState( GL_NORMAL_ARRAY );
    glNormalPointer( GL_FLOAT, sizeof(*m_fNormals)*(m_iSegements+1)*2*2, m_fNormals );*/
    for( int j = 0; j < m_iSegements / 2; j++ ) {

        for( int i = 0; i <= m_iSegements; i++ )
        {

        }

        glDrawArrays( GL_TRIANGLES, 0,   (m_iSegements + 1)*2   );
    }

    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_TEXTURE_COORD_ARRAY );
    glDisableClientState( GL_NORMAL_ARRAY );

}

```

# Answer
> 1 votes
Your use of `sizeof` is invalid. It only works like this on fixed-size arrays. Instead of:

```
sizeof(m_fVerts)

```

Use:

```
sizeof(*m_fVerts) * (segments+1)*2*3;

```

---
Tags: opengl
---


title: How to make a top down shooter?

text:
# Question
Title: How to make a top down shooter?
I want to know is with XNA 4.0 (and C#) How do I exactly make a top down shooter? I have been looking for ages, but have been unable to find out how.

If someone could tell me how to get started with it or possibly link me to a good easy to understand tutorial that would be fantastic!

# Answer
There are plenty of examples on the XNA creators club on how to get started with making games. In fact I remember them giving you the link while you are downloading XNA to the samples: rendering this question quite lazy indeed.

The XNA community project on CodePlex also has a slew of examples.
> 1 votes

---
Tags: c#, xna, 2d, shooter
---


# Question
Title: Skewed: a rotating camera in a simple CPU-based voxel raycaster/raytracer
TL;DR — in my first simple software voxel raycaster, I cannot get camera rotations to work, seemingly correct matrices notwithstanding. The result is skewed: like a flat rendering, correctly rotated, however distorted and without depth. (While axis-aligned ie. unrotated, depth and parallax are as expected.)

I'm trying to write a simple voxel raycaster as a learning exercise. This is purely CPU based for now until I figure out how things work exactly — fow now, OpenGL is just (ab)used to blit the generated bitmap to the screen as often as possible.

Now I have gotten to the point where a perspective-projection camera can move through the world and I can render (mostly, minus some artifacts that need investigation) perspective-correct 3-dimensional views of the "world", which is basically empty but contains a voxel cube of the Stanford Bunny.

So I have a camera that I can move up and down, strafe left and right and "walk forward/backward" — all axis-aligned so far, no camera rotations. Herein lies my problem.

Screenshot #1: correct depth when the camera is still strictly axis-aligned, ie. un-rotated.

Now I have for a few days been trying to get rotation to work. The basic logic and theory behind matrices and 3D rotations, in theory, is very clear to me. Yet I have only ever achieved a "2.5 rendering" when the camera rotates... fish-eyey, bit like in Google Streetview: even though I have a volumetric world representation, it seems —no matter what I try— like I would first create a rendering from the "front view", then rotate that flat rendering according to camera rotation. Needless to say, I'm by now aware that rotating rays is not particularly necessary and error-prone.

Still, in my most recent setup, with the most simplified raycast ray-position-and-direction algorithm possible, my rotation still produces the same fish-eyey flat-render-rotated style looks:

Screenshot #2: camera "rotated to the right by 39 degrees" — note how the blue-shaded left-hand side of the cube from screen #2 is not visible in this rotation, yet by now "it really should"!

Now of course I'm aware of this: in a simple axis-aligned-no-rotation-setup like I had in the beginning, the ray simply traverses in small steps the positive z-direction, diverging to the left or right and top or bottom only depending on pixel position and projection matrix. As I "rotate the camera to the right or left" — ie I rotate it around the Y-axis — those very steps should be simply transformed by the proper rotation matrix, right? So for forward-traversal the Z-step gets a bit smaller the more the cam rotates, offset by an "increase" in the X-step. Yet for the pixel-position-based horizontal+vertical-divergence, increasing fractions of the x-step need to be "added" to the z-step. Somehow, none of my many matrices that I experimented with, nor my experiments with matrix-less hardcoded verbose sin/cos calculations really get this part right.

Here's my basic per-ray pre-traversal algorithm — syntax in Go, but take it as pseudocode:

* **fx** and **fy**: pixel positions x and y
* **rayPos**: vec3 for the ray starting position in world-space (calculated as below)
* **rayDir**: vec3 for the xyz-steps to be added to rayPos in each step during ray traversal
* **rayStep**: a temporary vec3
* **camPos**: vec3 for the camera position in world space
* **camRad**: vec3 for camera rotation in radians
* **pmat**: typical perspective projection matrix

The algorithm / pseudocode:

```
// 1: rayPos is for now "this pixel, as a vector on the view plane in 3d, at The Origin"
rayPos.X, rayPos.Y, rayPos.Z = ((fx / width) - 0.5), ((fy / height) - 0.5), 0

// 2: rotate around Y axis depending on cam rotation. No prob since view plane still at Origin 0,0,0
rayPos.MultMat(num.NewDmat4RotationY(camRad.Y))

// 3: a temp vec3. planeDist is -0.15 or some such — fov-based dist of view plane from eye and also the non-normalized, "in axis-aligned world" traversal step size "forward into the screen"
rayStep.X, rayStep.Y, rayStep.Z = 0, 0, planeDist

// 4: rotate this too — 0,zstep should become some meaningful xzstep,xzstep
rayStep.MultMat(num.NewDmat4RotationY(CamRad.Y))

// set up direction vector from still-origin-based-ray-position-off-rotated-view-plane plus rotated-zstep-vector
rayDir.X, rayDir.Y, rayDir.Z = -rayPos.X - me.rayStep.X, -rayPos.Y, rayPos.Z + rayStep.Z

// perspective projection
rayDir.Normalize()
rayDir.MultMat(pmat)

// before traversal, the ray starting position has to be transformed from origin-relative to campos-relative
rayPos.Add(camPos)

```

I'm skipping the traversal and sampling parts — as per screenshot #1, those are "basically mostly correct" (though not pretty) — when axis-aligned / unrotated.

# Answer
> 2 votes
Your pseudo-code in *Go* language is a big mystery to me, so I\`ll try to describe my approach :)

First of all you do not need any perspective-projective matrix. All you need to construct current view ray is:

* camera position
* camera up vector
* camera look at vector
* current pixel on the screen

Let\`s assume that our free camera works right. Now we take our vectors and perform Gram–Schmidt process. This gives us orthogonal camera basis. In *GLSL* this step looks something like this:

```
vec3 cameraW = normalize(cameraPosition - cameraLookAt);
vec3 cameraU = normalize(cross(cameraUp, cameraW));
vec3 cameraV = cross(cameraW, cameraU);

```

Ok, we have basis. This basis is common for all pixels on the screen. Even more it\`s invariant until we move or rotate camera. To compute view ray for current pixel one must do:

```
vec3 rayOrigin = cameraPosition;
vec3 rayDirection = normalize(p.x * cameraU + p.y * cameraV - cameraViewPlaneDistance * cameraW);

```

where `p` — is coord of your current pixel.

After this you have view ray. It\`s a high time to do some raytracing or raymarching stuff.

Let\`s go back to the free camera. To move forward or backward we simply shift camera position in the direction of target vector. To move left or right we extract right vector from camera rotation matrix and add it to the target and position vectors.

To rotate camera we use camera rotation matrix. First camera rotation matrix is identity matrix. We have three floats: yaw, pitch and roll. When user moves mouse this floats accumulates rotation angles. On update we must apply this rotations to our camera rotation matrix. Let\`s take yaw which corresponds to rotations around up axis. First we extract up vector from rotation matrix and then construct new rotation matrix. After all we multiply camera rotation matrix and the new one. Here some *C++* code that uses *glm* library:

```
vec3 up(cameraRotation[0][1], cameraRotation[1][1], cameraRotation[2][1]);
cameraRotation *= glm::rotate(mat4(1.0), yaw, up);

```

Hope this helps..

---
Tags: voxels, raycasting, go
---


# Question
Title: How to Translate and Position at the same time?
Hi I'm having problem Translating and Positioning at the same time e.g take example of retro spacecraft shooting games in which your spaceship moved in x-axis automatically and you just needed to control position on y-axis. I'm using `transform.Translate(new Vector3(0f,Time.deltaTime * speed,0f),Space.World);` to translate and then `transform.position = new Vector3(Input.mousePosition.x,0f,0f);` to position using mouse but it doesn't seem to work. Help !

# Answer
> 0 votes
Actually what you will find is that the spacecraft does not move at all in retro space shooters; but rather all of the level objects move in the opposite direction instead. i.e. To make it look like the player is moving right; you should make all of the level objects (including the background) move to the left.

So really you shouldn't need to be translating the player on the X axis at all. You should be translating the level objects in the opposite direction on the X-axis instead. This will also make positioning the player, using the mouse position, a lot easier as you can work using absolute screen co-ordinates, without having to worry about the player's world co-ordinates.

EDIT: If you really must move the player's position physically in the world, then I would suggest that you grab the position of the mouse on the screen, then add it to the offset of the view, to set the player's world position correctly, combining them into a single transformation such as:

```
transform.position = new Vector3(Input.mousePosition.x, _ScreenPosition.Y, 0f);

```

# Answer
> 0 votes
Both `transform.Translate` and `transform.position` affect the same variable. So calling both in the same frame the way you are isn't going to work.

What you want to do is change your mouse input code to take into account the current y and z values of your position.

So do the translate part, and then for setting the x value, do something like this:

```
transform.position = new Vector3( Input.mousePosition.x, transform.position.y, transform.position.z );

```

Keep in mind that it's very likely that `Input.mousePosition` is *not* what you want. That is in screen coordinate space, not 3D space, so unless your camera is set up to be 1 unit is one pixel, you're likely going to set the X value to something weird. What you might want to do is keep track of the mouse delta, scale it by some appropriate value relative to your world scale, and then just pass that in to the X value for your first `transform.Translate`.

---
Tags: c#, unity
---


# Question
Title: Why set the position of both b2Body and Box2DSprite?
In a game, we add a body for each sprite, the method is:

```
createBodyAtLocation:(CGPoint) forSprite:(Box2DSprite*)sprite

```

In which we create the body and we attach it to the sprite in parameter: `sprite.body = body;`

Then we set the position of the body, but later on in the code, in the `update` method, we also set the position of the sprite to the same position as the body. I was wondering: **Why are we doing it twice?** As we already set the position of the body in the world, and we made a link between the two with `sprite.body`?

# Answer
> 1 votes
The sprite is the graphical representation and the body is the physical representation. They don't need to have the same position, even though they often will. This is likely the reason you can or need to set the positions separately.

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


# Question
Title: Storing Player Location/Data in an Online Game
I know this question has been asked and answered in some threads, but I'd like a more beginner dumbed down explanation.

So player information, specifically direction and position, need to be updated constantly, for tons of players at the same time.

Let's just say 10 players in the same room move an inch in some direction. All of the other players need to see that instantly, obviously. I realize that saving the location to the database, and getting the location for everyone to see is a horrible idea.

So I guess my question is... how does this work? What happens if a player alt-f4's or kills the game process without saving or doing a "normal" exit? How often should I save the location to the database?

Thanks

# Answer
This is handled by what some networking APIs call "ghosting". When a player's position changes it marks a flag (boolean or bit) dirty, and periodically (every 300-500ms or so) the networking system will grab all information that has been marked dirty and send it to every player that is in range of the player whose information is dirty. Additionally, whenever a player comes in range of another player, both of those players are sent the entirety of each others information (only the info that they need to know about each other, such as position, or rotation).

Here's some more information I've written about ghosting: http://nic-gamedev.blogspot.com/2011/11/mmo-architecture-creating-ghosting.html

An example of this. Let's imaging there are 2 players in range of each other (Players #1 and #2), and a 3rd player just out of range (Player #3).

1. Player #1 moves around a bit. This marks his position as being dirty, the networking system records this change.
2. Sometime in the next few hundred milliseconds, the networking system goes through all dirty flags it finds, and finds that Player #1's position is marked dirty. It then adds that information, and any other information about player #1 to a packet and sends a copy of that packet to any player in range.
3. Player #2 receives the packet and updates the information that it has for player #1. Generally prediction algorithms come into play here so that player #1 doesn't just teleport to the new known position, but rather interpolates towards it over time.
4. Player #3 walks into range of player #1 and player #2.
5. The networking system sees that player #1 and #2 are new to player #3, and player #3 is new to player #1 and #2, so it sends player #3 all of the necessary information from player #1 and #2, and sends them player #3's information as well.

Any player that leaves range results in a message to other players that had the player in range, so that they may remove them from their client. Generally the client will keep information about a player leaving range around for about 30 seconds in the case that the player continues to enter and leave range, so the server doesn't have to continuously send down all of that player's information every time the player re-enters range.
> 1 votes

# Answer
In simple terms the Server is running a master copy of the game and each player's Client is merely acting like a playback of what the Server tells it is happening. This leads to more pieces directly related to your question.

First piece is that the client sends commands to the server like "I want to move over here(xy)" and the server is what actually moves the player. The player's client then receives an update with his move. In this way no matter what the client says the server is in control. Because this raw data is jumpy you will see terms like "client side prediction" which is used to smooth out these updates.

Second piece is that the fastest parts of the game on the server are kept in memory and only occasionally saved out to a database, this is called "persistence," or "persisting the game world;" someone who kills their game stops sending commands to the server and whatever their last info was is what gets stored into the database and restored when that player logs back in again.

That's really all there is to it, without all the complex technique names and details getting in the way.
> 0 votes

---
Tags: databases, online
---


# Question
Title: World Location issues with camera and particle
I have a bit of a strange question, I am adapting the existing code base including the tile engine as per the book: XNA 4.0 Game Development by example by Kurt Jaegers, particularly the aspect that I am working on is the part about the 2D platformer in the last couple of chapters.

I am creating a platformer which has a scrolling screen (similar to an old school screen chase), I originally did not have any problems with this aspect as it is simply a case of updating the camera position on the X axis with game time, however I have since added a particle system to allow the players to fire weapons. This particle shot is updated via the world position, I have translated everything correctly in terms of the world position when the collisions are checked.

The crux of the problem is that the collisions only work once the screen is static, whilst the camera is moving to follow the player, the collisions are offset and are hitting blocks that are no longer there.

My collision for particles is as follows (There are two vertical and horizontal):

```
    protected override Vector2 horizontalCollisionTest(Vector2 moveAmount)
    {
        if (moveAmount.X == 0)
            return moveAmount;

        Rectangle afterMoveRect = CollisionRectangle;
        afterMoveRect.Offset((int)moveAmount.X, 0);
        Vector2 corner1, corner2;

        // new particle world alignment code.
        afterMoveRect = Camera.ScreenToWorld(afterMoveRect);
        // end.

        if (moveAmount.X < 0)
        {
            corner1 = new Vector2(afterMoveRect.Left,
                                  afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Left,
                                  afterMoveRect.Bottom - 1);
        }
        else
        {
            corner1 = new Vector2(afterMoveRect.Right,
                                  afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Right,
                                  afterMoveRect.Bottom - 1);
        }

        Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
        Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);

        if (!TileMap.CellIsPassable(mapCell1) ||
            !TileMap.CellIsPassable(mapCell2))
        {
            moveAmount.X = 0;
            velocity.X = 0;
        }

        return moveAmount;
    }

```

And the camera is pretty much the same as the one in the book... with this added (as an early test).

```
    public static void Update(GameTime gameTime)
    {
        position.X += 1;
    }

```

# Answer
> 1 votes
You mentioned in your original post that particle positions are already in world position, and I'll assume that `CollisionRectangle` is also in world position. If that's true, then why `afterMoveRect = Camera.ScreenToWorld(afterMoveRect);`? Collision detection doesn't need the screen coordinates of anything, so if it does, you would be better served to refactor the code so that it doesn't. Your collision detection code will be much easier to debug, maintain, and extend in the future.

Try removing that call to translate the coordinates and see if that fixes your problem. The particle's position only needs to be translated to screen coords by the rendering logic. I haven't read the book you mentioned, but I'll also assume that camera translations are being passed as a matrix as part of a call to `SpriteBatch.Begin(...)`.

Another possible cause of your issue is that the camera position could be getting updated before the collision detection code runs, but after rendering has completed. Try looking at the order of updates and see if there's an issue there.

To avoid issues of this type in the future, you could implement the side-scrolling functionality by adding (if not already present) a `Velocity` and/or `Acceleration` property to your `Camera` class (it goes without saying that it would have a `Position` property). Create a method or set of methods as needed that will allow you to impart an initial velocity to your camera - in your case, it looks like `1` is a good place to start. In Update, you'll just do standard kinematics calculations to calculate the position of the camera each frame.

---
Tags: xna, camera, platformer, particles
---


title: Public Static vs. Instanced Classes

text:
# Question
Title: Public Static vs. Instanced Classes
I've seen a lot of rhetoric over the year about not using a Public Static class to store global variables or methods that are used across an application.

I understand the philosophy about code maintenance issues that this might present in business software with a number of developers but is there any real performance issues this introduces?

Specifically if the items that have been made public static are used from most classes in the game and prevent multiple instances of a given class from being created. e.g. collision detection, playing audio samples etc.

# Answer
Tabs vs Spaces, Static vs Singleton.

**Yes**, make sure you have maintainable code
**Don't** worry about optimization of method calls right now
**Sometimes** it is OK to have static properties and methods
**Othertimes** it isn't
At the end of the day, **did you ship a game?**

Now That I am done trying to dodge your question, and have surely guaranteed at leas 1 downvote, I'll try to answer it as best as I can.

I see you have the XNA tag, so I will answer according to that. XNA provides a nifty feature that lets you create an instance of a class and pass it around to whatever needs it. `Game.Services` is what you want to look at. This is great for keeping a reference to a component that needs to be shared.

I like to avoid Singletons, but that is just me. Sometime they are what is best used. Static classes shouldn't be shunned either. Just look at the MediaPlayer class. I can't think of others, but my gut tells me there are a few others that are static.

Take, for example, a collision detection component. If it is expensive to create a new one and it can be shared without problems, perhaps you make it static/singleton. Maybe you store it in Game.Service and access it that way. **BUT** I would wager that it is very cheap to `new` one up, and you really only need to have 1 per scene/level. What would be wrong with just creating a new one for each level? Unless your levels change at the rate of a couple a minute you won't really be accumulating that much garbage. Most likely you will only need to new one up every few minutes or so.

I think the last two paragraphs from the article I linked at the top are very fitting

> Simplicity is beautiful. Simple doesn’t mean hard-coding, it doesn’t mean cutting corners or being sloppy – it means building what you’ve been asked to build, not a rocket to Saturn and most of the time it’s a skateboard to the corner store.
>
> Not every application needs to be stitched together from Codebetter posts and Twitter rants. Focus on what’s important – the experience, not what’s under the hood. You’ll change that quite a few times no matter what you think :).
> 2 votes

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


# Question
Title: Unit selection - logic & screen communication
I'm building a game using SFML, with disconnected logic & screen systems that run on different threads and communicate through synchronised buffers. Now, this system worked perfectly well when I only ran independent AI units, but now comes the time to handle player input, and I'm not sure what's the best way to handle it.

Currently, when a player clicks the screen, the input manager creates a `MouseClick` event, which goes to the logic buffer. The logic manager checks if that spot contains a controllable entity, and if it does, creates a `SelectUnit` event with the relevant information in the display buffer. When the display manager reads that event it updates the screen with the relevant piece of GUI, and any click on the GUI again sends an update to the logic component. The two problems I see are that the `SelectUnit` event will need to contain a lot of logic info which might harm the info decoupling, or just make it useless, and that I fear (still not tested) that since the communication will bounce several times between the two threads, some might be lost.

Now, I wonder if this system could be handled better, with less transferred information.

Note about the tech: SFML creates a `RenderWindow` object which handles input and display. I'm still not sure what library to use for GUI (probably GWEN.net), so I can't currently name tech limitations on it.

EDIT: this is supposed to be a RTS multiplayer game. So far, it seems to me there'll have to be a central logic unit (on the host computer?) that'll receive all the inputs from all players, and send the responses accordingly. This, obviously, makes this system even more complex. Again, suggestions are welcome.

# Answer
> 2 votes
You have separated your runtime in two threads, one for the game updates ("logic"), and another one for the rendering ("screen"). Your concern is how to exchange information between them.

A usual way of doing this is to keep **two separate buffers** describing your scene, one per thread. The rendering just needs the info relevant for rendering in its own buffer: matrices, meshes, textures... Whenever the scene changes, the update thread fills a **command queue** with delta changes (e.g. object A was moved, object B was deleted, etc.). When the rendering thread is ready to process a frame, it consumes those commands and adapts its own scene.

Easier to write but less memory-efficient: have **three buffers**, one that the update thread modifies, another one that waits for the rendering thread to pick up (a glorified command queue), and a last one that the rendering thread works on.

A few related links:

**Now to your specific problems:**

> The two problems I see are that the `SelectUnit` event will need to contain a lot of logic info which might harm the info decoupling, or just make it useless...

Exactly, this is way too high level for you rendering thread. You should process it in your update thread, and send something more generic to your rendering thread:

* Add Mesh\_Selection to the scene, attached to Unit\_X
* Add GUI\_Object\_Foo with Texture\_Bar at screen location x,y

That's the general idea, but what to send exactly is up to you. The more high level you go, the more you off-load your update thread, but the more complicated your commands will be.

> ...and that I fear (still not tested) that since the communication will bounce several times between the two threads, some might be lost.

There's no reason why you rendering thread should send anything back. All the updates are processed by the update thread, the rendering thread just renders what it's fed with, top-down.

**NB:** That's one way to do multithreading in game engines, but it's definitely not the only way. You'll need to do a bit of research to find if that's really what you need: it's common on current-gen consoles, but it's a bit outdated on modern PC hardware. And it's definitely overkill on single-core systems. Here are a few links to start with:

---
Tags: architecture, design-patterns, events, sfml
---


title: Collision Detection Efficiency

text:
# Question
Title: Collision Detection Efficiency
I've just written my first successful collision detection code, and it works great for a small scene of actors (player + 4-5 obstacles).

However, I realize that since it checks every possible collision for each actor in the scene, it checks each possible collision in the scene twice (Does A collide with B? Does B collide with A?).

With a small number of objects that may be colliding, this is not a problem, but it seems to me that it could slow things down in a very busy scene if every collision is checked twice.

Should I go ahead and rewrite it to check each collision once, or would that be a premature optimization?

# Answer
First of all, ***try it***. If your game makes use of a large number of objects in the scene and you find that the game is slowing down because of it, that's when you need to worry about it.

To answer the question though, games tend to optimize this by using *spatial partitioning* (Graphics tends to use techniques to cull objects from rendering, and the same techniques can be used to aid with collision detection).

Havok physics, for example, makes use of two phases in their collision detection. A broadphase and a narrow phase.

The broadphase check is usually a much less computationally expensive test to determine whether two objects are near each other. The narrowphase check then checks the objects that pass the broadphase for actual collisions.

Quadtrees (or octrees) are a good and simple to understand data structure for carrying this out. The broadphase check would determine whether two objects in your list of objects are in the same quadrant. If not, then we can safely ignore collisions between them, otherwise carry out the more expensive check between the two to see whether they are colliding.

There are a number of other data structures you could look into (cell space partitioning, BSP trees, etc), but my first suggestion would be to actually try it out.

Hope that helps!
> 6 votes

---
Tags: collision-detection, optimization
---


title: Bubble shooter falling algorithm

text:
# Question
Title: Bubble shooter falling algorithm
To complete this question about the same color search algorithm, I would like to know if someone knows which is the best implementation for making other bubbles fall when they are no longer attached. More precisely, how can I detect *islands* of isolated bubbles.

My data structure is a NxM matrix.

# Answer
Every bubble that isn't floating must have some path going back to a top bubble (are we assuming the side walls aren't "glue"?). Apply a flood fill algorithm for *every* bubble found in the top row. Doing this for every top bubble is essential because it'll work flawlessly in any case, in particular if there are several columns of bubbles hanging from the top but not touching each other.

Flag all "filled" bubbles for each iteration of the algorithm, and skip any already filled bubbles in the top row to save time.

When all top bubbles are filled, drop the bubbles that haven't been flagged.
> 2 votes

# Answer
One simple method would be to write a function that starts at a bubble touching the top wall and runs through all it's neighbors (and recursively their neighbors with a method to prevent going to ones that have already been visited) then check to see any that didn't get visited by the function call. Any that didn't aren't attached to anything and therefor should fall.

Another method would be to take into account the fact that any falling bubbles must have been attached to the bubbles that were just removed. Rather than make a function to walk every bubble, have a function walk from a particular bubble and try to reach the top. Preference for going up will make this faster per call, and once you've verified a bubble is connected to the top, all it's neighbors can immediately tell that they are as well. If you run out of bubbles to try and you haven't reached the top then you (and all the bubbles you ran through) need to fall as they are no longer attached to the top.
> 2 votes

# Answer
Search the non-ceiling edges for non-bubbles, and then check for non-bubble paths between these nodes.

Example:

```
------------
005163215101
205143122500
100064131001
215061356132

```

In this case, there is a path from the top-left corner (non-bubble touching the non-ceiling left wall) to the 4th spot on the bottom edge consisting entirely of non-bubbles. This means that everything along the edge between them (down the left side, across the bottom) is disconnected and should fall (along with everything attached to those). Simply grab the first bubble along the outer page (the 2 at the start of the second row), and drop it and every bubble connected to it.

There is no path from any of the outer non-bubbles to the non-bubble on the right edge, so we don't drop anything over there.
> 1 votes

---
Tags: algorithm, game-mechanics, search
---


# Question
Title: Opengl drawing a section of a texture stretched over a quad
**Current Situation**

I have a spritesheet loaded in for a texture when drawing the specific portions of the sheet that I'd like to have on my quads I do some simple math to get their location on the sheet and normalize it.

My texture is setup like this:

```
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

```

**The Problem**

Where I'm facing the problem is that because I'm using a "chunk" of the total texture I can't take advantage of using 1.0 for the mapping of values to `glTexCoordPointer` to cause the texture to stretch over the entire face.

*Looked Into*

I've looked for a `glTexParameterf` option for scaling options but I failed to find anything.

*Question*

Is it possible with my current methods to stretch the texture over the face of the quad without having to load a separate image for every "sprite" of the texture? Or am I just doing everything completely wrong?

Picture that hopefully sort of clarifies:

Thanks for any help.

**edit** The problem was another issue all together: Turns out it was another issue all together, I thought this didn't make sense cause it was mapping it to the vertices so it should stretch regardless and infact it does work right I was assigning the wrong the width and height values to the drawing routines calculations. And now I feel really stupid, thanks for the help Byte56. Sorry for taking up your time. The GL\_CLAMP solution would be the correct answer if I hadn't made a huge fail.

# Answer
> 2 votes
It looks like your assigning the textures to the vertices correctly. I don't see how you're getting the results you're getting with what you've shown us. But you may want to try this:

```
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

```

---
Tags: opengl, textures, sprites, spritesheet
---


# Question
Title: How would I create Dynamic LOD with Quad Trees
I would like to be able to create something like the following http://www.youtube.com/watch?v=LxZhWrSmrOY&feature=player\_embedded how would I create something like it? I understand I will have to use quad trees and cube to sphere projection, but I don't even know how I will structure the program or even create the sphere.

1. I would like to know how I would structure the program (an interface of the members I would need particularly in the quad-tree class, and the class which holds the quad-treesm etc)
2. How do I make it so dynamic like that?
3. How would I create the quad tree structure and how would it work (and interact with other objects)?
4. Any other information/things you can provide me with :3
5. How to create the sphere, etc.

Eventually I would like to be able to create something like this: http://www.youtube.com/watch?v=rL8zDgTlXso but I guess creating this (the first thing mentioned) is a part of it?

Anything would be appreciated.

**Edit:**

I found the source code for the first project at https://github.com/unconed/NFSpace the only problem is, is that it is in C++ and Orge, and I don't really understand any of it, help please! :)

# Answer
> 3 votes
Here are a few links you may find useful; General Linking Page, Hugues Hoppe

These should provide you with a huge amount of information so hopefully you can find something in there to get you going.

Quad-trees and oct-trees are references to particular methods of spatially partitioning the world into smaller and easier to handle chunks. Because terrain tends to be just a skin, then it makes sense to break it up into quad trees (which are useful in 2D applications) but you could also use other trees, such as the oct-tree or a bsp.

Quad trees are fairly simple. Start with one huge square which encompasses everything and call it the root node. Then divide it into 4 equal sized pieces, and those 4 pieces into 4 more and those 4 into... Do this until either you think you've gone far enough or each square encompasses a maximum of n polygons/items.

Now what you have is a set of data grouped in a box, and it's easier to deal with that one box than all of those pieces of data. From here on it stays pretty simple. Check if a box is visible (see if it's within the view frustum). If it is, check to see if the 4 boxes it contains are visible and, for each one that is, check the 4 ... again a bit of recursion here. Ignore any box and all of it's child boxes if its not visible. Now you've dropped a whole bunch of data by quite simply culling data so you only have roughly what fits inside the view frustum (visible area).

Now, there's a detail I missed earlier. Once you've made the smallest boxes you want to have and put data in them, try averaging that data out and bubbling it up to the parent box. So, for example, a box at the bottom of the tree might have 2 polygons to make a square, find the point furthest from the parents center and bubble it up. repeat this for each child box. The parent will then get one point from each child box and 4 points gives you another quad, but one which should be the same area as the 4 more detailed quads in the child nodes. In other words you get one quad which covers the 4 in the child boxes. Again, repeat this and eventually what you'll have is a tree in which every layer contains more polygon data.

So now, when your checking if a box is visible, if it is, then check how far away it is. If it's quite far away, maybe you don't want to bother checking the child boxes of that node and just use the less detailed data it contains. So you don't go any further down that part of the tree.

Now you have culled loads of data and your also cutting down the detail for far away boxes. But there is one last issue which is quite difficult. When a box of low detail sits next to a box of higher detail, the polygons don't match. There are various ways to fix this, but you'll find that in the articles in the links posted at the top of this answer.

---
Tags: xna, c#, quadtree, dynamic-mesh, planet
---


title: Java OpenGl Rotating Cube Problem!

text:
# Question
Title: Java OpenGl Rotating Cube Problem!
OK, so I successfully learned how to bind textures to quads and display this cool looking crate. However, when I rotate the cube something goes wrong. During rotation the back-face of the cube overlays the front-face and appears in front of the front-face. This is also the case with the right and left faces. They overlay each other giving a weird perception. I'm not sure why this happens. Here is the code where I draw only four face of the quad (front, back right, left).

```
gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);      // clear the screen and depth buffers
gl.glLoadIdentity();                            // reset the current modelview matrix

    // draw quad
    gl.glTranslatef(0.0f, 0.0f, -6.0f);                 // translate to the left and into the screen
    gl.glRotatef(rotateAngle, 0.0f, 1.0f, 0.0f);        // rotate triangle around the y-axis
    gl.glBindTexture(GL2.GL_TEXTURE_2D, textures[2]);   // bind the texture you want to use to gl_texture_2d
    gl.glBegin(GL2.GL_QUADS);

        // front face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, 1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);

        // right face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, -1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(1.0f, 1.0f, 1.0f);

        // left face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(-1.0f, -1.0f, 1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(-1.0f, 1.0f, 1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);

        // back face
        gl.glTexCoord2f(0.0f, 1.0f);                // bottom left
        gl.glVertex3f(-1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 1.0f);                // bottom right
        gl.glVertex3f(1.0f, -1.0f, -1.0f);
        gl.glTexCoord2f(1.0f, 0.0f);                // top right
        gl.glVertex3f(1.0f, 1.0f, -1.0f);
        gl.glTexCoord2f(0.0f, 0.0f);                // top left
        gl.glVertex3f(-1.0f, 1.0f, -1.0f);

    gl.glEnd();

```

Moreover, the way I draw textures and then vertices is not yet clear to me. According to what I've read the bottom-left corner (0, 0) is where the textures start drawing, so I should also start drawing my quad from bottom-left accordingly. I tried that but it didn't work. The texture was drawn, but up side down. So I had to go through some trial and error till I got the texture drawn correctly. I wish I could attach a picture to this post so I can show you how the back face of the cube overlays the front one during rotation, but I think this facility isn't provided in stack exchange. Thanks.

# Answer
> 3 votes
I figured the problem out! at first I thought it was a driver problem because i'm using mac os x like this http://forum.jogamp.org/Depth-buffer-not-working-on-Win7-64b-td1737435.html but then i tried it on 64-bit windows and the same problem occurred. Finally, I found out that it was a code problem due to gluProspective(). I didn't set zNear correctly I should have glu.gluPerspective(45.0f, (float) width / height, 1.0f, 100.0f) instead of glu.gluPerspective(45.0f, (float) width / height, 0.0f, 100.0f). Because opengl expects zNear to always be positive. Hope this will help other beginners who face the same problem.

# Answer
> 0 votes
Is depth test enabled and preserved? You need the following code somewhere at initialisation:

```
gl.glClearDepth(1.0f);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glDepthFunc(GL.GL_LEQUAL);

```

---
Tags: opengl, java, jogl
---


title: XNA 4.0 Point Vertex Rendering

text:
# Question
Title: XNA 4.0 Point Vertex Rendering
I have a buffer of about 134 million particles and a very powerful computer to render them smoothly, but I am getting an error when trying to render them as primitive lines. It says that I cannot render more than around 1 million. Is there a way I can do this? Is there a better way to render this other than with lines? I'm comfortable with having 1 pixel points or anything as long as the vertices are shown all the time. I'm basically just plotting the points.

# Answer
David indicated that you can likely do this by batching these into multiple draw calls. I assume (from experience using 16-bit index buffers) that XNA/your GPU won't care if the actual buffer (array) is much larger than what you are asking it to draw.

Your wireframe will likely be a LineStrip - which according to the documentation is an interconnected set of points.

I made some extension methods that will deal with the batching for you, requiring minimal code changes (just replace `DrawUserPrimitives` with `DrawMassUserPrimitives`). This may need tweaking as I haven't actually tested it (especially the calculations - LineStrip is correct though). In addition, if you need the other `Draw*` calls that has been left as an exercise for the student.

```
public static class GraphicsDeviceExtensions
{
    private const int MaxPrimitivesHiDef = 1048575;
    private const int MaxPrimitivesReach = 65535;

    // Given the number of primitives, calculate the number of vertices
    // required to create that number of primitives.
    private static readonly Func<int, int>[] CalculateVertices = new Func<int, int>[]
    {
        // TriangleList
        x => x * 3,
        // TriangleStrip
        x => x + 2,
        // LineList
        x => x * 2,
        // LineStrip
        x => x + 1
    };

    // Inverse of the above.
    private static readonly Func<int, int>[] CalculatePrimitives = new Func<int, int>[]
    {
        // TriangleList
        x => x / 3,
        // TriangleStrip
        x => x - 2,
        // LineList
        x => x / 2,
        // LineStrip
        x => x - 1
    };

    public static void DrawMassUserPrimitives<T>(this GraphicsDevice device, PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount)
        where T : struct, IVertexType
    {
        DrawMass(device, primitiveType, vertexOffset, primitiveCount, (batchVertexOffset, batchPrimitiveCount) =>
        {
            device.DrawUserPrimitives<T>(primitiveType, vertexData, batchVertexOffset, batchPrimitiveCount);
        });
    }

    public static void DrawMassUserPrimitives<T>(this GraphicsDevice device, PrimitiveType primitiveType, T[] vertexData, int vertexOffset, int primitiveCount, VertexDeclaration vertexDeclaration)
        where T : struct
    {
        DrawMass(device, primitiveType, vertexOffset, primitiveCount, (batchVertexOffset, batchPrimitiveCount) =>
        {
            device.DrawUserPrimitives<T>(primitiveType, vertexData, batchVertexOffset, batchPrimitiveCount, vertexDeclaration);
        });
    }

    private static void DrawMass(GraphicsDevice device, PrimitiveType primitiveType, int vertexOffset, int primitiveCount, Action<int, int> draw)
    {
        // Grab the calculation functions for our primitive type.
        var calculateVertices = CalculateVertices[(int)primitiveType];
        var calculatePrimitives = CalculatePrimitives[(int)primitiveType];

        // Work out:

        // The maximum number of primitives our profile supports.
        var maxPrimitives = device.GraphicsProfile == GraphicsProfile.HiDef ? MaxPrimitivesHiDef : MaxPrimitivesReach;
        // How many vertices would be rendered for that number of primitives.
        var maxVertices = calculateVertices(maxPrimitives);
        // The number of vertices the user wants to draw.
        var vertexCount = calculateVertices(primitiveCount);
        // The index of the last vertex the user wants to draw.
        var endVertex = vertexOffset + vertexCount;

        // Go over the range in steps of 'maxVertices'.
        for (var i = vertexOffset; i < endVertex; i += maxVertices)
        {
            // Make sure we don't draw too many vertices.
            var batchEnd = i + maxVertices;
            if (batchEnd > endVertex)
                batchEnd = endVertex;
            var batchCount = batchEnd - i;

            // Work out the number of primitives again.
            var batchPrimitives = calculatePrimitives(batchCount);

            // Ask the calling method to draw what we have worked out.
            draw(i, batchPrimitives);
        }
    }
}

```
> 3 votes

# Answer
The maximum number of primitives that you can draw with a single call in XNA while using the HiDef profile is 1048575 according to this article.

I've never tried it but since that limit is defined *per draw call* I think you should be able to draw more primitives by using separate draw calls. All of the DrawPrimitives type of methods take an offset and count into the buffer (e.g. startVertex and primitiveCount) so you can play with those values to draw different portions of the buffer in each call and keep incrementing the offset until everything is drawn.

You can also take a look into the `PrimitiveBatch` class available in this sample as it's pretty easy to use. Just increase the buffer size inside the class first. And while you're at it check this one too.
> 2 votes

---
Tags: xna, c#, directx, vertex
---


# Question
Title: XNA Development on PC but Designing for Xbox 360
I'm working on a project with a buddy, he doesn't have a 360 nor does he have the money to get one right now, but we want our game to be submitted to XBLIG. So right now we're both designing our game on the PC but we're using adapted 360 controllers. What are the things we need to keep in mind during the process so that we can "easily" port our game to the 360 from the PC?

# Answer
> 13 votes
You have to keep in mind that the Xbox360 has far poorer .NET performance than your average desktop PC (and a limited subset of it too!).

There are two main reasons: the Load/Hit/Store penalty (due to the architecture of the CPU/RAM/GPU) and the non-generational Garbage Collector.

For GC issues, which cause 'pauses' or 'freezes' in your game during runtime, you want to avoid any kind of runtime garbage, so be very careful with Strings (never concatenate for instance), never allocate reference type objects after your initial loading (ie no `var obj = new MyCoolObject();`), and be careful with foreach. I've made a blog post some time ago that covers some of these points: http://nextstopnowhere.wordpress.com/2010/03/26/garbages-out-pools-are-in/

But whatever you do, you will have to test on the Xbox360, and the sooner the better.

# Answer
> 9 votes
The best way is to periodically test the game in a console to check for performance problems or problematic garbage collections; otherwise you will end with a lengthy debugging and optimization session before publishing the game.

And when porting to Xbox 360, check all the cases specified in the peer review evil checklist.

# Answer
> 3 votes
No one seems to mention this, but be sure to, at the very least, compile your project for the X360 every day. The Xbox only features a subset of .NET (.NET Compact Framework 3.0), missing lots of interesting stuff like Tuples, some collections, optional parameters, etc., so you will get bitten if you rely on any of them and don't realize you shouldn't until too late in the project.

---
Tags: xna, xbox360, porting, xbox-live
---


# Question
Title: libGDX application does not support 800x480 resolution
I have an application written with libGDX that does not run with a resolution of 800x480, whereas on devices with other resolutions (e.g. 480x320) it works perfectly. It also works perfectly as a desktop application with a resolution of 800x480.

In onCreate() method I only have this code:

```
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
        initialize(new BreakTheBall(), false);
}

```

So what do I have to do to have it work in a resolution of 800x480? I have to ask this question because my samsung galaxy sx2 display only blank screen at the time of game execution but emulator work perfectly. I also want to said that all the given demo application by libGDX could not run on the same device resolution.

Also I like to mention the base class of my project which specify about stage, camera and viewport declaration

```
protected BreakTheBall game;
protected Stage stage;
protected World world;
protected OrthographicCamera camera;
protected Preferences preferences;
protected ArrayList<Obstacles> boxArrayList;
protected ArrayList<BlastBall> blastBallArrayList;

private static final int VIRTUAL_WIDTH = 480;
private static final int VIRTUAL_HEIGHT = 320;
private static final float ASPECT_RATIO = (float) VIRTUAL_WIDTH
        / (float) VIRTUAL_HEIGHT;
private Rectangle viewport;

// protected Box2DDebugRenderer renderer;

public AbstractScreen(BreakTheBall game) {
    this.game = game;

    Texture.setEnforcePotImages(false);
    stage = new Stage(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),
            false);

    Constant.setStageRatio(stage.width(), stage.height());

    world = new World(new Vector2(0.0f, 0.0f), false);
    // camera = new OrthographicCamera(Gdx.graphics.getWidth() / 10.0f,
    // Gdx.graphics.getHeight() / 10.0f);
    camera = new OrthographicCamera((float) VIRTUAL_WIDTH / 10.0f,
            (float) VIRTUAL_HEIGHT / 10.0f);

    // camera.position.scale(0.0f, 0.0f, 0.0f);

    // renderer = new Box2DDebugRenderer(true, false, false);
    Gdx.input.setInputProcessor(stage);

    preferences = new Preferences();
}

@Override
public void render(float deltaTime) {
    GL10 gl = Gdx.graphics.getGL10();

    camera.update();
    camera.apply(gl);

    gl.glClearColor(0f, 0f, 0f, 1f);
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    gl.glViewport(0, 0, (int) viewport.width, (int) viewport.height);

    world.step(1 / 60f, 3, 3);
    world.clearForces();

    stage.act(deltaTime);
    stage.setCamera(camera);
}

@Override
public void resize(int width, int height) {

    float aspectRatio = (float) width / (float) height;
    float scale = 1f;

    Vector2 crop = new Vector2(0f, 0f);

    if (aspectRatio > ASPECT_RATIO) {
        scale = (float) height / (float) VIRTUAL_HEIGHT;
        crop.x = (width - VIRTUAL_WIDTH * scale) / 2f;
    } else if (aspectRatio < ASPECT_RATIO) {
        scale = (float) width / (float) VIRTUAL_WIDTH;
        crop.y = (height - VIRTUAL_HEIGHT * scale) / 2f;
    } else {
        scale = (float) width / (float) VIRTUAL_WIDTH;
    }

    float w = (float) VIRTUAL_WIDTH * scale;
    float h = (float) VIRTUAL_HEIGHT * scale;

    viewport = new Rectangle(crop.x, crop.y, w, h);

}

```

I think above specified code provide more guidance to community members so please help me to come out of this problem.

# Answer
> 4 votes
Thank you for the community for giving response to me. I found the answer of my question after hard working towards it. The solution is that WVGA (800x480) screen resolution only support the 2nd power images with resolution. So other members also take care about that so they do not have to waste time in that.

# Answer
> 0 votes
Set your target version level higher at manifest. You are setting it too low and that cause app start as combatibility mode. This is just android behaviour nothing to do with libgdx.

---
Tags: libgdx
---


# Question
Title: Would it be too much overhead to keep a HashMap of variables on a server per object for the purpose of syncing object changes with the client?
I am currently writing a server for a multiplayer game. I am trying to find a good solution for synchronizing GameObjects across the server. The server sends each client a snapshot of every object in range over TCP once every 1/15th of a second and it sends minor updates over UDP every 1/30th of a second. I've come to the point in the code where after I've handled login and the basic information exchange I need to start synchronizing objects between the client and server. My original solution was to keep a boolean flag inside of each GameObject class to tell if it had been changed that update cycle or not and then send a serialized version of it across the server. However, the problem with that is that that sends the entire object even if only one variable was changed which wastes bandwidth not to mention the fact that I would need to serialize a representative class and not the actual one that may contain information that should only be server-side. A friend proposed the solution that I should write a class that contains a HashMap of variables that maps Strings to NetVars(a class containing the value and an index for referring to it). All variable changes would go through a get and set function so that we could tell if it had been modified. Each GameObject would keep one of these and when the server goes through its update cycle it would send the updates as a serialized list of NetVars that have been changed for each object to the clients who should receive them along with the object's id.

My question is would that be too much overhead? Would it slow down the server by having a NetVars class for each GameObject? and finally are there any better solutions than these and if so what?

Extra info: Using Java with Kryonet for networking and the game is expected to have a fair number of entities in player view at any one moment.

# Answer
> 2 votes
This would be fine; in fact, most games have some variation on this method, tracking individual variables that change and only transmitting those variables.

You can still have the per-object flag; that saves you from having to examine every field in the object when none of them have changed. Just make sure that your interface keeps everything in sync, so there's no chance of accidentally changing a variable while leaving the object flagged as unchanged. (Although there are times you may want to allow this, eg. for objects that you don't want to broadcast too often, maybe because they're uninteresting, or distant, etc.)

You may not need a hashmap: if your objects are identical at both ends of the network then a simple index will suffice for noting which field has changed.

# Answer
> 1 votes
Keeping a hashmap per object is unlikely to cause too much overhead.

**Justification:** Python's Objects are essentially hashmaps ('dicts' in the parlance) and it is possible to write this kind of client/server program in python up to a surprisingly good level of performance.

Besides which, in most cases, the nework latency will dwarf the processing costs by orders of magnitude, especially for something as well optimised as a hashmap lookup. In fact, it will almost always be worth compressing your message to improve network performance.

---
Tags: java, architecture, networking, mmo, client-server
---


title: Match-3 game level generator

text:
# Question
Title: Match-3 game level generator
I made match-3 game and now i trying to add level generator. Now I generate level by filling random cells with random blocks, but I want to create generator which for given number of moves and number of block kinds generate level. What algorithms I can use if they exists?

# Answer
I'm assuming Match-3 is like *Bejewelled*, right?

I have no experience with this, but I would try the following:

1. Generate random board
2. Override some cells to create some 3 matches and maybe a 4 match
3. Randomly move one of the cells in a valid way
4. Make a few other random moves if necessary
5. Validate by removing matches (if any) and replacing them

This doesn't give you any hard guarantees though. Experiment, I'd say :-)
> 2 votes

# Answer
Generating the blocks while the game is running, providing a good neighbors checking algorithm (depending on the difficulty level) would provide a less repetitive result.

Without a flexible algorithm a player will eventually memorize the pattern in a few tries. That's a possibility for any type of game depending of fixed patterns (even more complex games, like chess), and once it happens the trick gets old really fast.

This question is exactly about that concept: Connect-three game: Increasing level-of-difficulty as play progresses
> 0 votes

---
Tags: game-design, algorithm
---


# Question
Title: initialising units' properties & upgrades
I'm making a RTS in which units can get several cyber-upgrades (individual, not as a global tech-tree upgrade like in most RTS games) before they're created. Now, I'm trying to decide how to do this, logic-wise. The system I have right now is that each unit type (walker, car, etc.) is a class, and when I initiate an instance of the class I add all the modifiers to the constructor, and let the constructor handle all the modifications.

This seems to me like the wrong way to do it - it means copy-pasted code in all the constructors. The other idea I had was to have each modification as a static method that takes a Unit class and modifies it - but the modifications might need access to private memebers (health, speed, etc.), and if I write the methods per-class, again I achieved copy-pasted code. As far as I know there's no way that a external static method can access private fields, and I don't want to create properties for every field, so as not to make the classes too cumbersome to use.

Example, to clarify: let's say I create a new Agent, and I want him to have bionic feet (+5 speed), x-ray vision (change of sight-function) and armored body (change of hit effects). I could use a constructor like Agent(speed, vision, armor), but if I'd later want to create new upgrades, such as fast reactions (+5 initiative), I'd have to change the constructor's signature. I could use a constructor like Agent(List), and then in the constructor create a giant swtich/case for every available upgrade, but then, I'd have to copy it also to the constructor of Vehicle, and make sure I update both of them, exactly the same. What I'd like to do is have a basic constructor and after it have a:

```
internal delegate void Effect(Unit ent);

void setup(List<Effect> list)
{
    foreach(Effect effect in list) effect(this);
}

```

method, and then run every effect in the list on the new Unit, but then the Effect can't access the unit's private members.

Is there an elegant solution to the problem?

# Answer
Using your idea of a switch statement to apply the upgrades, you could achieve what you want here by having the walker and vehicle classes derive from a parent "Upgradeable" or "Stat" class. This can be used to handle all of the stats for both unit types, which will make changes easier to maintain.

For example:

Upgradeable Class:

```
public enum Upgrade {
    ARMOUR_MKI,
    ENGINE_MKII
}

public class Upgradeable {
    protected int hp;
    protected float speed;

    protected Upgradeable() {}
    protected virtual void ApplyUpgrades(List<Upgrade> upgrades) {
        foreach (Upgrade u in upgrades) {
            switch (u) {
                case Upgrade.ARMOUR_MKI:
                    hp += 100;
                break;

                case Upgrade.ENGINE_MKII:
                    speed += 5f;
                break;
            }
        }
    }
}

```

Then derive your other classes from this:

```
public class Walker : Upgradeable {
    public Walker(List<Upgrade> upgrades) : base() {
        hp = 100;
        speed = 4f;
        ApplyUpgrades(upgrades);
    }

    protected override void ApplyUpgrades(List<Upgrade> upgrades) {
        base.ApplyUpgrades(upgrades);
        // Class Specific Stuff
    }
}

public class Vehicle : Upgradeable {
    public Vehicle(List<Upgrade> upgrades) : base() {
        hp = 200
        speed = 2f;
        ApplyUpgrades(upgrades);
    }

    protected override void ApplyUpgrades(List<Upgrade> upgrades) {
        base.ApplyUpgrades(upgrades);
        // Class Specific Stuff
    }
}

```

This provides the type of interface you want, whilst maintaining protection of your object's members and upgrade method calls. The centralisation of the Upgradeable class also makes maintainability of the upgrades between unit types much simpler. And with the ApplyUpgrades method calls in the derived classes, you can implement specific upgrades or effects per-class too.
> 1 votes

# Answer
There are some things to consider: Are these upgrades just about modifying values or do we need things like adding new visual effects or new behavior when something is triggered. Jason's solution is alright for the limited requirements of the former. Although you would want to keep list of upgrades available too.

For the latter requirements, there are many different design patterns available. For instance, you could have base class Upgrade (or a more general name like "Attachable") which has events OnAttach or OnDetach which are evoked upon adding the upgrade to an object, and then it adds handlers to the object's events; and later removes them OnDetach.

Latter solution could be unwieldy and more inefficient if your requirements are smaller. Optimization is probably your least concern for now anyway.

And you can have some Factory-objects or methods to ease the generation of these composite-objects.
> 1 votes

# Answer
Why don't you add Effects as a property of your Unit class?

```
Effect armor = new Armor(5);
Agent a = new Agent("Name");
a.Augments.Add(armor);

```

Something like that.
> 0 votes

---
Tags: c#, logic
---


# Question
Title: What should my map creation workflow be for a turn-based tactics game?
I am planning to make a tile turn-based game like Final Fantasy Tactics. Now, I am brainstorming of how can I implements the map arena system (the battle arena where there are block by block tile so that character can walk on) such that it is easy to merge an art consisting of whole arena terrain onto the game.

I planned to create a full-map sprite, modelling it after a real place, then put it into the game. The problem is how do I code the program such that it will know the height and location of each tile out of a large single-sprite map? If I am to do that, then I should create some kind of editor that generate such data.

If I implements a tile by tile map creation, such that I use separate art sprite for each tile, then it would be hard to put the full map onto the game. I will have to build the map from tiny sprite, tile by tile.

I would kindly ask any professional or people who have done these type of game before, which method would you suggest me to do?

Another question that I want to ask is, if any of you know, how does game like final fantasy tactics layout their background map to make it look 3D? Do they simply make a sprite tile created from an angled (user's ) view instead of flat sprite with top-view? Or do they simply use flat top-view sprite and maps it on a 3D plane/terrain ?

# Answer
I would suggest that you create editing software to construct your maps; this hypothetical editor would let you paint individual tiles onto a grid -- probably an isometric grid, from the sounds of it -- and eventually export that map into a format consumable by your game.

In the long run, this will be a more efficient means of constructing your maps that trying to paint one sprite for the map. It may take longer to build up your initial tile set, but once you have a tile set creating new maps and adjusting existing maps will be much faster. The only real feasible approaches to starting with a single sprite and then extracting information from that about where each tile position would be are almost equivalent to constructing a tile-based editor anyhow, especially if you're going for an isometric approach because your 2D source image lacks any encoded depth information.

Plus, with this approach you'll already have a basis for a tool that allows you to set up additional level data, such as placing invisible triggers for events or other scripted behaviors, placing the initial enemy or player unit formations (which obviously couldn't be painted on to your "single sprite").

Such a tool can also be scalable into creating 3D tile-based geometry, which is what Final Fantasy Tactics actually uses (allowing the screen to be rotated).
> 4 votes

---
Tags: 2d, game-design, sprites
---


# Question
Title: XNA: How to Flip/Mirror a position over a custom vector?
I want to flip Horizontally my Sprite/Texture however the SpriteEffects.FlipHorizontally isn't cutting it for me as it just flips the texture in place.

I want to flip the texture over a specified Vector2/Vector3?

Thanks!

# Answer
some quick resources i found:

http://forums.create.msdn.com/forums/p/80526/487062.aspx

C = A - (2 * B * (A dot B)) where A is original vector, B the mirror, C result.

http://en.wikipedia.org/wiki/Reflection\_(mathematics)

edit: Sorry, I actually forgot what the actual question was. But yeah, you should be able to manipulate UV-values with that formula anyway.

edit2: http://mathworld.wolfram.com/Reflection.html

This has the actual formula you wanted.
> 1 votes

# Answer
To do this you would most likely have to write a custom shader which provides a mechanism for flipping.

Create your shader and load it as an effect in xna. Then set it before doing any draw calls. You can load this shader through the content manager.

In your shader you will want to change the pixel shader. What you will want to do is mirror the texture coordinate supplied to the pixel shader in the vector. Also, remember to create a global variable, for the vector, which you can set in your xna code trough;

```
effect.parameter["name"].setValue(Val);

```
> 0 votes

---
Tags: xna, mathematics, xna-4.0, linear-algebra
---


title: How to I create a resource manager?

text:
# Question
Title: How to I create a resource manager?
Currently I'm using XNA's `ContentManager` to load my content. For the unfamiliar the `ContentManager` deserializes classes from disk and keeps a reference for future requests.

I'm currently facing a problem with management, where for some resources I don't want to deserialize them repeatedly (e.g. a texture) but for others I do (e.g. destructible level geometry). As it is now when I replay a level I get back the original class with the player's changes.

For this reason I decided to inherit from `ContentManager` to provide some way of re-deserializing a resource to get a new copy (probably using the `protected ReadAsset<T>` method).

Now I'm thinking about how I should manage this. Ideally I want some way of saying you can re-use `Textures`, but not `Levels` (i.e. when a `Level` is requested it always deserializes a new instance).

While I think about that I'd also like to create my custom `ContentManager` with a view to get other niceties such as automatic unloading, on-demand or in advance loading of assets, pre-loaded place-holder assets etc.

How is this sort of class typically designed and how can I overcome my immediate problem (reloading particular types and re-using instances of others)?

# Answer
It sounds to me like ContentTracker has what you require. It allows for disposing and reloading of individual items, among many other things.

It should be what you're looking for, I think.

(Do note, that it's for XNA 3.1 only, however there is a link at the bottom of the Codeplex homepage where someone has kindly ported it to 4.0)
> 1 votes

# Answer
If I rembemer correctly, caching assets is done in Load method. So all you need to do is override this metod, and make custom caching (store loaded asset in dictionary with assetName as key). (This will help you later in unloading only certain items).

And then make new method LoadNew which will bypass caching (or create clone)
> 1 votes

# Answer
### update

After a bit of a chat with Kikaimaru, I realized the deep copy wont work as seamlessly as I thought. Too bad, I thought it was very elegant. The methods below will still work though.

---

If you are still set on doing it, try something like this. Just overload the method telling it to cache or not. I pretty much snagged this from this blog, and he goes into more detail there. You might find it useful should you decide to go this way.

```
public override T Load<T>(string assetName)
{
    return Load<T>(assetName, true);
}

public T Load<T>(strng assetName, bool cache)
{
    if (loadedAssets.ContainsKey(assetName))
        return (T)loadedAssets[assetName];

    T asset = ReadAsset<T>(assetName, null);

    if(cache)
        loadedAssets.Add(assetName, asset);

    return asset;
}

```

---

I had another thought. What you could do it something along the lines of creating an interface to make all your non-cacheable object implement. Have the load manager look for that, and don't cache if it is found. You could accomplish the same thing with an attribute if you wanted.

```
public interface INoCache{} //no member here, just empty...Maybe a bool "ShouldCache" if you want...

public class Destructible : INoCache

//In your ContentManager
public T Load<T>(string assetName)
{
    if (loadedAssets.ContainsKey(assetName))
        return (T)loadedAssets[assetName];

    T asset = ReadAsset<T>(assetName, null);

    //this logic seems a bit backwards, but
    //it makes for a little cleaner code IMHO
    if(!(asset is INoCache))
        loadedAssets.Add(assetName, asset);

    return asset;
}

```
> 1 votes

---
Tags: xna, c#, assets, xna-content-pipeline, asset-management
---


# Question
Title: How should I detect whether or not to enable Anti-Aliasing?
How can I detect the speed of the user's graphics card so that I can decide whether or not to enable advanced graphics features that would slow down the app on a slow card, such as anti-aliasing? I am using OpenGL.

# Answer
Usually you would just leave this up to the user to decide or alternately run a small bench test and recommend settings to the user.

If you want to bench test to recommend settings or just put it on regardless all you need to do is see how long it takes to complete your render call. If a frame is 25 milliseconds, for example, and all your draws are done in 12 milliseconds, then you can probably turn it on.
> 5 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: how to create a new game like pacman, snake, airplane fight game in C# with xna
I have a school project to create a game develop in c#.. I know all Basic of OOP and c#. I don't know where to start?..

Suggestion will appreciated Thank you

# Answer
> 1 votes
The best suggestion I can give you, and the one I passed out while tutoring many people, is do not sit down and start to program an entire game. It always seems a bit daunting and flusters people into wasting their time.

My suggestion is to pick your overall game, and then make something in it.. The easiest example I can give you goes like this for the game Frogger.

* Make A Frog
* Make the frog move around the screen
* Make a car
* Make the car move around on its own in a set pattern
* Add in collision between the car and the frog
* Use the collision to detect when a frog reaches the other side of the board
* Add death tiles where the frog can not go using the collision as well
* Add in the logs that the frog can jump on that move in the death tiles
* Create new vehicles and add them to the cars.
* Create a randomly spawning fly and detect when you pick it up.
* Add in an action tracking system. Notably this would be used for a scoring mechanism, but if you are bored you could also use it for replays if you store what you track.

And I think that gets the general idea.. At the end you will come up with a game. The trick is to keep the set of tasks small.. The person I walked through this setup with went from thinking making a game impossible to having most of the above done in around 4-6 hours of work.. and actually produced a very amusing version of Frogger :)

Hope this helps.

# Answer
> 0 votes
Lookup tutorials on http://create.msdn.com/en-US/ They have whole games with source code there, but all you need for games like snake is how to draw a texture on specific place and how to handle input.

For a snake

1. So i would suggest you to create a texture (an image) of one body part of a snake and find a way to display it. (Using **Content pipeline**, **ContentnManager.Load** and **SpriteBatch.Draw**)
2. Find out how to handle when someone presses keyboard and when he does move that body part and display it on next location (using **Keyboard.GetState()**)
3. Make moving of that body part automatical, and with keypress just change direction (using **Update** method on **Game1** class)
4. Draw other things like food
5. Find out how to handle collisions of snake and food (using **Rectangle** class and **Intersects** method)

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


# Question
Title: Bones Animation - Matrices and calculations
We are 'on final' when it comes to finishing the project, but just before implementing the animation system.

Our Client decided to choose "Bones Animation" - which is that I should export each Transformation Matrix ( matrix4x4 rotation+translation ) for every frame and for every bone that this animated object has.

Objects in our game are animated with 3DS Max Physique Modifier, so we will have bones / weighting data per vertex. But I will simplify things here just to get a bit of light on this subject.

I would like to split this post into 2 points, where :

1. **Exporting bones matrices for every frame**

* treats about the correct method of exporting the bones positions for later animation purposes, where i have to 'move' and 'rotate' every vertex influenced by this bone to bone position at frame X.
2. **Calculating final vertex position**

* treats about proper matrices operations to calculate new vertex position according to bone transformation in frame X.

***1. EXPORTING BONES MATRICES FOR EVERY FRAME***

Do I understand correctly that while exporting the animated object I should:

> 1. Grab BONE transformation matrix at frame 0 and Invert this matrix
> 2. Grab BONE transformation matrix at FRAMEx
> 3. Multiply 1 * 2 to get the transformation offset of the BONE at FRAMEx

```
[pseudocode]
// Animation export

// For each frame, export bone transformation offset
for(int iFrame = 0; iFrame < vFrames.size(); iFrame++)
{
    // For every bone in the object
    for(int iBone = 0; iBone < vBones.size(); iBone++)
    {
        // Grab transformation matrix for this bone at frame 0 and inverse it
        Matrix3 matBoneMatrixAtStart = pNode->GetObjectTMAfterWSM( 0 );
        matBoneMatrixAtStart.Inverse();

        // Grab transformation matrix for this bone at frame iFrame
        Matrix3 matBoneMatrixAtCurrentFrame = pNode->GetObjectTMAfterWSM( iFrame );

        // Multiply Inversed Transformation Matrix of this bone at frame 0 - with
        //  current frame transformation matrix
        Matrix3 matBoneTransformationOffset = matBoneMatrixAtStart
                                              * matBoneMatrixAtCurrentFrame ;

        // Save matBoneTransformationOffset - vertex will be multiplied by this
        //  matrix for animation purposes
        fwrite(.....)
    }

}
[/pseudocode]

```

Will that be enough ? Or there is something I am missing here?

***2. CALCULATING NEW VERTICES POSITIONS ( FINAL VERTEX POSITION AT FRAME X)***

Later on, when rendering, object vertices are going to be multiplied by exported bone transformation matrix for actual animation frame, and then multiplied by this whole model transformation matrix to place the object in correct position inside the level :

```
[pseudocode]

Update()
{
    // The model transformation matrix describing the position of
    //  the model in the level
    matModelTransformationMatrix

    // Calculate new vertex position according to it's bone transformation offset
    NewVertexPosition = (OriginalVertexPosition * matBoneTransformationOffset[iFrame])
                           * matModelTransformationMatrix;

    // Increment the frame for testing purposes
    iFrame++;
}

[/pseudocode]

```

Am I thinking correct here? So, Having bone transformation offset for frame X, multiplying every vertex affected by this bone by this offset should result in a vertex transformed exactly as this bone right?

# Answer
> 8 votes
It's best you read nVidia's pages containing some GPU Gems articles. There's the key formula which I will briefly explain to you in the following pseud-answer:

This is where you'll find the complete article, and it's a classic resource by now. I will only assume you want an explanation of that process, done in a simplistic manner (as much as I can).

The formula and its meaning:

You start with a mesh of vertices, i.e. a set {Pk} of vertices with connectivity. You don't care about the topology that much, so disregard the connectivity (that's something skinning shouldn't deteriorate, it should keep manifolds looking like manifolds, preserve topology, etc.). In that formula, *vBindpose* gives you the rest position of the character's vertex. This is in object space, i.e. the "world' space of that character's frame. Now, each bone has its own frame, and the way to transform a vector written in bone's *bone\[i\]* frame into the object's global frame is by multiplying it with *matrixBindpose\[i\]*. (imagine you have to assemble a robot, and its forearm vertices are given to you in its elbow frame of reference.. and the elbow is connected to the humerus/shoulder bone.. that's why you need these transformations, mainly to assemble vertex sets into a mesh)

So, what does *INV(matrixBindpose\[i\]) x vBindpose* mean then? It means that you get the coordinates of the *v* vertex in the local frame of that *bone\[i\]* bone. Why? Because each bone can memorize its own version of where a vertex it affects is with respect to its own frame of coordinates. That means, each bone can provide you with its own relative view of where a point it affects is, regardless of how other bones see that point.

Now, what happens when you multiply with the new bone transformation matrix *matrix\[i\]*? Recall from the last point that you now have a local version of the *v* vertex, i.e. how the *bone\[i\]* thinks that vertex looks like with respect to its own frame. By multiplying with *matrix\[i\]*, you end up with a vector/vertex situated in the global/object coordinate frame.

Next, you multiply that vertex with the bone's scalar contribution/weight. What do you have then? You end up with a weighted sum of vectors that lie in the same coordinate frame. That's why you can add them/i.e. take that sum over all bones that influence a vertex.

Your code doesn't really reflect that you completely understood the procedure. The nVidia article is focused more on how to do that via shaders, that's why they assume there are at most four bones that can affect one vertex of the initial/bindpose mesh.

As you said, if you take your starting pose, the bindpose, then *matrix\[i\] x matrix\[i\]^-1* is the identity matrix. That's ok because the sum will be equal to \_sum(w\_i)\*vBindpose\_. Since *vBindpose* is the vector written in the global/object frame, it's already assembled and in position. The sum of those weights, by construction is 1 (convex combination resulting from a weight normalization process - typically done by the system after weights are assigned to each vertex). So that formula can be used to check whether a model can be assembled correctly (it was normally done by the MD5 Doom3 animation model loaders if I remember correctly). That's it, in a nutshell.. it means that at each step you need to optimize a bit the computations so that you compute the result of that lil'ol formula there. Happy coding :)

---
Tags: opengl, animation, matrix, 3dsmax
---


title: XNA: Good way to queue up animations

text:
# Question
Title: XNA: Good way to queue up animations
I'm writing an AnimatedSprite class that has an Animation object (which itself contains a sprite sheet).

The AnimatedSprite plays certain animations during key input. My problem is that how do I cycle from one animation back to the original ? Is there a good method to do this?

Here is my Animation class. The AnimatedSprite just calls PlayAnimation

```
public class Animation
{
    public SpriteSheet SpriteSheet { get; set; }
    public bool IsActive { get; set; }
    public float FramesPerSecond { get; set; }
    public bool IsLooping { get; set; }
    public int FrameCount { get; set; }

    private int CurrentFrame { get; set; }
    private float ElapsedTime { get; set; }
    private float TimePerFrame { get { return 1.0f / FramesPerSecond; } }

    public Texture2D Texture { get { return SpriteSheet.Texture; } }
    public Rectangle Rectangle { get { return SpriteSheet.SourceRectangle(CurrentFrame);} }

    public Animation(SpriteSheet sheet)
    {
        SpriteSheet = sheet;
        FramesPerSecond = 20f;
        IsActive = true;
        IsLooping = false;
        FrameCount = SpriteSheet.NumberOfSprites;
        CurrentFrame = 0;
        ElapsedTime = 0;
    }

    public Animation(SpriteSheet sheet, int fps) : this(sheet)
    {
        FramesPerSecond = fps;
    }

    public virtual void Update(GameTime gameTime)
    {
        if (!IsActive)
            return;

        ElapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

        if (ElapsedTime > TimePerFrame)
        {
            CurrentFrame += 1;//move frame ahead one
            if (CurrentFrame >= FrameCount)
            {
                CurrentFrame = 0; //reset the animation;
                if (!IsLooping)
                    IsActive = false;
            }

            ElapsedTime -= TimePerFrame;
        }
    }

}

```

# Answer
One method is to have a stack of animations in your animated sprite class. When the user says jump, put the jump animation on the top of the stack. When the end condition for the animation has been met, remove it from the stack. If you are always using the animation on the top of the stack, then removing the top one will automatically continue the next one down.

Delegates could be used to attach functions to the Animation object, which will return a boolean signaling whether the animation should stop or not. This way the Animation object can call this delegate method during it's update and it can return this value as the return value for the update. So your AnimatedSprite object just updates the top animation and, if the udpate function returns true, it removes that object from the stack.

For example, a function could be attached which returns true if the player is on the ground and false if their not. Attaching this to a jump animation would cause it to stop, and therefore be removed from the stack if the player hits the ground.
> 2 votes

---
Tags: xna, 2d, xna-4.0, animation
---


title: XNA: Draw Bounding Box around Sprite

text:
# Question
Title: XNA: Draw Bounding Box around Sprite
I'm just starting with XNA and I wanted to draw Debug Lines around my Texture/Sprite to help me.

Is there an easy way to do it with SpriteBatch? I haven't used the GraphicsDevice yet to draw....

Thanks!

# Answer
http://www.xnawiki.com/index.php/Drawing\_2D\_lines\_without\_using\_primitives

I would suggest to create subclass of SpriteBatch that would have DrawLine and DrawRectangle function and in constructor create 1x1 texture.
> 4 votes

# Answer
Check out this forum post in which the poster details how he is making spriteBatch draw in wireframe mode.

Basically you just need to change your draw code to this;

```
spriteBatch.Begin(SpriteSortMode.Immediate,BlendState.Opaque);
RasterizerState state = new RasterizerState();
state.FillMode = FillMode.WireFrame;
spriteBatch.GraphicsDevice.RasterizerState = state;

spriteBatch.Draw(sprite, position, Color.White);

spriteBatch.End();

```

And obviously change "spriteBatch.Draw(sprite, position, Color.White)" to be a loop drawing all of your sprites.
> 0 votes

---
Tags: xna, 2d, xna-4.0
---


title: Errors on LibGDX tutorial

text:
# Question
Title: Errors on LibGDX tutorial
I get the following errors on the LibGDX tutorial "Simple App"

> Exception in thread "main" java.lang.UnsatisfiedLinkError: no gdx64 in java.library.path at java.lang.ClassLoader.loadLibrary(Unknown Source) at java.lang.Runtime.loadLibrary0(Unknown Source) at java.lang.System.loadLibrary(Unknown Source) at com.badlogic.gdx.utils.GdxNativesLoader.load(GdxNativesLoader.java:118) at com.badlogic.gdx.backends.lwjgl.LwjglNativesLoader.load(LwjglNativesLoader.java:41) at com.badlogic.gdx.backends.lwjgl.LwjglApplication.(LwjglApplication.java:52) at com.badlogic.drop.DesktopGame.main(DesktopGame.java:7)

I copied and pasted the final code onto the project, but I don't know why it wont run.

Whats the problem? Is it the project set-up?

# Answer
> 1 votes
Update the libraries of libGdx.

---
Tags: libgdx
---


# Question
Title: AS3 hittest with a tweening movieclip, what is the best way?
I'm making a simple game. The character is movable with the arrow keys. The enemies are moving around the screen with a (classic) tween.

I want to detect collision between the character and the enemies. At first I thought it was working properly, but it also seems to detect a collision on the starting position from the enemies. So even if the enemies are already moving/tweening away from their start position, there's a collision detected between the character and these starting positions. (please ask questions if you don't quite get what I mean)

First method:

```
addEventListener(Event.ENTER_FRAME, checkIfHitTest);
function checkIfHitTest(Event)
{
      if(player.hitTestObject(enemies))
      {
        trace("yes");

      }
      else
      {
           trace("no");

      }
}

```

This didn't work properly because it seems to detect the collition even if the enemy moved away from the starting point. (Probably because the ENTER\_FRAME but correct me if i'm wrong)

My question to you: What's causing the detection and what is the best way to detect collision between a tweening movieclip and a movieclip wich is movable with the arrowkeys?

# Answer
> 2 votes
From what you describe, your problem is *probably* relative to the movie-clip you are targeting to test collisions with.

To be more precise, I think you are testing your collisions against the movie-clip containing the enemy animation and the enemy graphics. But indeed this movie-clip doesn't move at all... it's fixed and only its content is moving (well at least it seems to be fixed from what I can read).

To solve this problem, you need to test against the movie-clip you animate inside the movie-clip containing the animation. So give a name to this movie-clip (e.g. enemyShape) inside the animation move-clip and try to test collision using this one *(take care to give the name on each key-frame of the tween animation)*.

Basically you will have to test against "***enemyClipXXX.enemyShape***" with XXX being any method you are using to name your enemies movie-clips.

---
Tags: collision-detection, actionscript-3, tweening
---